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/sched/signal.h>
17 #include <linux/uaccess.h>
18 #include <linux/capability.h>
19 #include <linux/kernel_stat.h>
20 #include <linux/gfp.h>
22 #include <linux/swap.h>
23 #include <linux/mman.h>
24 #include <linux/pagemap.h>
25 #include <linux/file.h>
26 #include <linux/uio.h>
27 #include <linux/hash.h>
28 #include <linux/writeback.h>
29 #include <linux/backing-dev.h>
30 #include <linux/pagevec.h>
31 #include <linux/blkdev.h>
32 #include <linux/security.h>
33 #include <linux/cpuset.h>
34 #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
35 #include <linux/hugetlb.h>
36 #include <linux/memcontrol.h>
37 #include <linux/cleancache.h>
38 #include <linux/rmap.h>
41 #define CREATE_TRACE_POINTS
42 #include <trace/events/filemap.h>
45 * FIXME: remove all knowledge of the buffer layer from the core VM
47 #include <linux/buffer_head.h> /* for try_to_free_buffers */
52 * Shared mappings implemented 30.11.1994. It's not fully working yet,
55 * Shared mappings now work. 15.8.1995 Bruno.
57 * finished 'unifying' the page and buffer cache and SMP-threaded the
58 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
60 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
66 * ->i_mmap_rwsem (truncate_pagecache)
67 * ->private_lock (__free_pte->__set_page_dirty_buffers)
68 * ->swap_lock (exclusive_swap_page, others)
69 * ->mapping->tree_lock
72 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
76 * ->page_table_lock or pte_lock (various, mainly in memory.c)
77 * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
80 * ->lock_page (access_process_vm)
82 * ->i_mutex (generic_perform_write)
83 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
86 * sb_lock (fs/fs-writeback.c)
87 * ->mapping->tree_lock (__sync_single_inode)
90 * ->anon_vma.lock (vma_adjust)
93 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
95 * ->page_table_lock or pte_lock
96 * ->swap_lock (try_to_unmap_one)
97 * ->private_lock (try_to_unmap_one)
98 * ->tree_lock (try_to_unmap_one)
99 * ->zone_lru_lock(zone) (follow_page->mark_page_accessed)
100 * ->zone_lru_lock(zone) (check_pte_range->isolate_lru_page)
101 * ->private_lock (page_remove_rmap->set_page_dirty)
102 * ->tree_lock (page_remove_rmap->set_page_dirty)
103 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
104 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
105 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
106 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
107 * ->inode->i_lock (zap_pte_range->set_page_dirty)
108 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
111 * ->tasklist_lock (memory_failure, collect_procs_ao)
114 static int page_cache_tree_insert(struct address_space
*mapping
,
115 struct page
*page
, void **shadowp
)
117 struct radix_tree_node
*node
;
121 error
= __radix_tree_create(&mapping
->page_tree
, page
->index
, 0,
128 p
= radix_tree_deref_slot_protected(slot
, &mapping
->tree_lock
);
129 if (!radix_tree_exceptional_entry(p
))
132 mapping
->nrexceptional
--;
133 if (!dax_mapping(mapping
)) {
137 /* DAX can replace empty locked entry with a hole */
139 dax_radix_locked_entry(0, RADIX_DAX_EMPTY
));
140 /* Wakeup waiters for exceptional entry lock */
141 dax_wake_mapping_entry_waiter(mapping
, page
->index
, p
,
145 __radix_tree_replace(&mapping
->page_tree
, node
, slot
, page
,
146 workingset_update_node
, mapping
);
151 static void page_cache_tree_delete(struct address_space
*mapping
,
152 struct page
*page
, void *shadow
)
156 /* hugetlb pages are represented by one entry in the radix tree */
157 nr
= PageHuge(page
) ? 1 : hpage_nr_pages(page
);
159 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
160 VM_BUG_ON_PAGE(PageTail(page
), page
);
161 VM_BUG_ON_PAGE(nr
!= 1 && shadow
, page
);
163 for (i
= 0; i
< nr
; i
++) {
164 struct radix_tree_node
*node
;
167 __radix_tree_lookup(&mapping
->page_tree
, page
->index
+ i
,
170 VM_BUG_ON_PAGE(!node
&& nr
!= 1, page
);
172 radix_tree_clear_tags(&mapping
->page_tree
, node
, slot
);
173 __radix_tree_replace(&mapping
->page_tree
, node
, slot
, shadow
,
174 workingset_update_node
, mapping
);
178 mapping
->nrexceptional
+= nr
;
180 * Make sure the nrexceptional update is committed before
181 * the nrpages update so that final truncate racing
182 * with reclaim does not see both counters 0 at the
183 * same time and miss a shadow entry.
187 mapping
->nrpages
-= nr
;
191 * Delete a page from the page cache and free it. Caller has to make
192 * sure the page is locked and that nobody else uses it - or that usage
193 * is safe. The caller must hold the mapping's tree_lock.
195 void __delete_from_page_cache(struct page
*page
, void *shadow
)
197 struct address_space
*mapping
= page
->mapping
;
198 int nr
= hpage_nr_pages(page
);
200 trace_mm_filemap_delete_from_page_cache(page
);
202 * if we're uptodate, flush out into the cleancache, otherwise
203 * invalidate any existing cleancache entries. We can't leave
204 * stale data around in the cleancache once our page is gone
206 if (PageUptodate(page
) && PageMappedToDisk(page
))
207 cleancache_put_page(page
);
209 cleancache_invalidate_page(mapping
, page
);
211 VM_BUG_ON_PAGE(PageTail(page
), page
);
212 VM_BUG_ON_PAGE(page_mapped(page
), page
);
213 if (!IS_ENABLED(CONFIG_DEBUG_VM
) && unlikely(page_mapped(page
))) {
216 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
217 current
->comm
, page_to_pfn(page
));
218 dump_page(page
, "still mapped when deleted");
220 add_taint(TAINT_BAD_PAGE
, LOCKDEP_NOW_UNRELIABLE
);
222 mapcount
= page_mapcount(page
);
223 if (mapping_exiting(mapping
) &&
224 page_count(page
) >= mapcount
+ 2) {
226 * All vmas have already been torn down, so it's
227 * a good bet that actually the page is unmapped,
228 * and we'd prefer not to leak it: if we're wrong,
229 * some other bad page check should catch it later.
231 page_mapcount_reset(page
);
232 page_ref_sub(page
, mapcount
);
236 page_cache_tree_delete(mapping
, page
, shadow
);
238 page
->mapping
= NULL
;
239 /* Leave page->index set: truncation lookup relies upon it */
241 /* hugetlb pages do not participate in page cache accounting. */
243 __mod_node_page_state(page_pgdat(page
), NR_FILE_PAGES
, -nr
);
244 if (PageSwapBacked(page
)) {
245 __mod_node_page_state(page_pgdat(page
), NR_SHMEM
, -nr
);
246 if (PageTransHuge(page
))
247 __dec_node_page_state(page
, NR_SHMEM_THPS
);
249 VM_BUG_ON_PAGE(PageTransHuge(page
) && !PageHuge(page
), page
);
253 * At this point page must be either written or cleaned by truncate.
254 * Dirty page here signals a bug and loss of unwritten data.
256 * This fixes dirty accounting after removing the page entirely but
257 * leaves PageDirty set: it has no effect for truncated page and
258 * anyway will be cleared before returning page into buddy allocator.
260 if (WARN_ON_ONCE(PageDirty(page
)))
261 account_page_cleaned(page
, mapping
, inode_to_wb(mapping
->host
));
265 * delete_from_page_cache - delete page from page cache
266 * @page: the page which the kernel is trying to remove from page cache
268 * This must be called only on pages that have been verified to be in the page
269 * cache and locked. It will never put the page into the free list, the caller
270 * has a reference on the page.
272 void delete_from_page_cache(struct page
*page
)
274 struct address_space
*mapping
= page_mapping(page
);
276 void (*freepage
)(struct page
*);
278 BUG_ON(!PageLocked(page
));
280 freepage
= mapping
->a_ops
->freepage
;
282 spin_lock_irqsave(&mapping
->tree_lock
, flags
);
283 __delete_from_page_cache(page
, NULL
);
284 spin_unlock_irqrestore(&mapping
->tree_lock
, flags
);
289 if (PageTransHuge(page
) && !PageHuge(page
)) {
290 page_ref_sub(page
, HPAGE_PMD_NR
);
291 VM_BUG_ON_PAGE(page_count(page
) <= 0, page
);
296 EXPORT_SYMBOL(delete_from_page_cache
);
298 int filemap_check_errors(struct address_space
*mapping
)
301 /* Check for outstanding write errors */
302 if (test_bit(AS_ENOSPC
, &mapping
->flags
) &&
303 test_and_clear_bit(AS_ENOSPC
, &mapping
->flags
))
305 if (test_bit(AS_EIO
, &mapping
->flags
) &&
306 test_and_clear_bit(AS_EIO
, &mapping
->flags
))
310 EXPORT_SYMBOL(filemap_check_errors
);
312 static int filemap_check_and_keep_errors(struct address_space
*mapping
)
314 /* Check for outstanding write errors */
315 if (test_bit(AS_EIO
, &mapping
->flags
))
317 if (test_bit(AS_ENOSPC
, &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
);
390 * filemap_range_has_page - check if a page exists in range.
391 * @mapping: address space within which to check
392 * @start_byte: offset in bytes where the range starts
393 * @end_byte: offset in bytes where the range ends (inclusive)
395 * Find at least one page in the range supplied, usually used to check if
396 * direct writing in this range will trigger a writeback.
398 bool filemap_range_has_page(struct address_space
*mapping
,
399 loff_t start_byte
, loff_t end_byte
)
401 pgoff_t index
= start_byte
>> PAGE_SHIFT
;
402 pgoff_t end
= end_byte
>> PAGE_SHIFT
;
406 if (end_byte
< start_byte
)
409 if (mapping
->nrpages
== 0)
412 pagevec_init(&pvec
, 0);
413 if (!pagevec_lookup(&pvec
, mapping
, index
, 1))
415 ret
= (pvec
.pages
[0]->index
<= end
);
416 pagevec_release(&pvec
);
419 EXPORT_SYMBOL(filemap_range_has_page
);
421 static void __filemap_fdatawait_range(struct address_space
*mapping
,
422 loff_t start_byte
, loff_t end_byte
)
424 pgoff_t index
= start_byte
>> PAGE_SHIFT
;
425 pgoff_t end
= end_byte
>> PAGE_SHIFT
;
429 if (end_byte
< start_byte
)
432 pagevec_init(&pvec
, 0);
433 while ((index
<= end
) &&
434 (nr_pages
= pagevec_lookup_tag(&pvec
, mapping
, &index
,
435 PAGECACHE_TAG_WRITEBACK
,
436 min(end
- index
, (pgoff_t
)PAGEVEC_SIZE
-1) + 1)) != 0) {
439 for (i
= 0; i
< nr_pages
; i
++) {
440 struct page
*page
= pvec
.pages
[i
];
442 /* until radix tree lookup accepts end_index */
443 if (page
->index
> end
)
446 wait_on_page_writeback(page
);
447 ClearPageError(page
);
449 pagevec_release(&pvec
);
455 * filemap_fdatawait_range - wait for writeback to complete
456 * @mapping: address space structure to wait for
457 * @start_byte: offset in bytes where the range starts
458 * @end_byte: offset in bytes where the range ends (inclusive)
460 * Walk the list of under-writeback pages of the given address space
461 * in the given range and wait for all of them. Check error status of
462 * the address space and return it.
464 * Since the error status of the address space is cleared by this function,
465 * callers are responsible for checking the return value and handling and/or
466 * reporting the error.
468 int filemap_fdatawait_range(struct address_space
*mapping
, loff_t start_byte
,
471 __filemap_fdatawait_range(mapping
, start_byte
, end_byte
);
472 return filemap_check_errors(mapping
);
474 EXPORT_SYMBOL(filemap_fdatawait_range
);
477 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
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. Unlike filemap_fdatawait(), this function
482 * does not clear error status of the address space.
484 * Use this function if callers don't handle errors themselves. Expected
485 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
488 int filemap_fdatawait_keep_errors(struct address_space
*mapping
)
490 loff_t i_size
= i_size_read(mapping
->host
);
495 __filemap_fdatawait_range(mapping
, 0, i_size
- 1);
496 return filemap_check_and_keep_errors(mapping
);
498 EXPORT_SYMBOL(filemap_fdatawait_keep_errors
);
501 * filemap_fdatawait - wait for all under-writeback pages to complete
502 * @mapping: address space structure to wait for
504 * Walk the list of under-writeback pages of the given address space
505 * and wait for all of them. Check error status of the address space
508 * Since the error status of the address space is cleared by this function,
509 * callers are responsible for checking the return value and handling and/or
510 * reporting the error.
512 int filemap_fdatawait(struct address_space
*mapping
)
514 loff_t i_size
= i_size_read(mapping
->host
);
519 return filemap_fdatawait_range(mapping
, 0, i_size
- 1);
521 EXPORT_SYMBOL(filemap_fdatawait
);
523 int filemap_write_and_wait(struct address_space
*mapping
)
527 if ((!dax_mapping(mapping
) && mapping
->nrpages
) ||
528 (dax_mapping(mapping
) && mapping
->nrexceptional
)) {
529 err
= filemap_fdatawrite(mapping
);
531 * Even if the above returned error, the pages may be
532 * written partially (e.g. -ENOSPC), so we wait for it.
533 * But the -EIO is special case, it may indicate the worst
534 * thing (e.g. bug) happened, so we avoid waiting for it.
537 int err2
= filemap_fdatawait(mapping
);
541 /* Clear any previously stored errors */
542 filemap_check_errors(mapping
);
545 err
= filemap_check_errors(mapping
);
549 EXPORT_SYMBOL(filemap_write_and_wait
);
552 * filemap_write_and_wait_range - write out & wait on a file range
553 * @mapping: the address_space for the pages
554 * @lstart: offset in bytes where the range starts
555 * @lend: offset in bytes where the range ends (inclusive)
557 * Write out and wait upon file offsets lstart->lend, inclusive.
559 * Note that @lend is inclusive (describes the last byte to be written) so
560 * that this function can be used to write to the very end-of-file (end = -1).
562 int filemap_write_and_wait_range(struct address_space
*mapping
,
563 loff_t lstart
, loff_t lend
)
567 if ((!dax_mapping(mapping
) && mapping
->nrpages
) ||
568 (dax_mapping(mapping
) && mapping
->nrexceptional
)) {
569 err
= __filemap_fdatawrite_range(mapping
, lstart
, lend
,
571 /* See comment of filemap_write_and_wait() */
573 int err2
= filemap_fdatawait_range(mapping
,
578 /* Clear any previously stored errors */
579 filemap_check_errors(mapping
);
582 err
= filemap_check_errors(mapping
);
586 EXPORT_SYMBOL(filemap_write_and_wait_range
);
588 void __filemap_set_wb_err(struct address_space
*mapping
, int err
)
590 errseq_t eseq
= __errseq_set(&mapping
->wb_err
, err
);
592 trace_filemap_set_wb_err(mapping
, eseq
);
594 EXPORT_SYMBOL(__filemap_set_wb_err
);
597 * file_check_and_advance_wb_err - report wb error (if any) that was previously
598 * and advance wb_err to current one
599 * @file: struct file on which the error is being reported
601 * When userland calls fsync (or something like nfsd does the equivalent), we
602 * want to report any writeback errors that occurred since the last fsync (or
603 * since the file was opened if there haven't been any).
605 * Grab the wb_err from the mapping. If it matches what we have in the file,
606 * then just quickly return 0. The file is all caught up.
608 * If it doesn't match, then take the mapping value, set the "seen" flag in
609 * it and try to swap it into place. If it works, or another task beat us
610 * to it with the new value, then update the f_wb_err and return the error
611 * portion. The error at this point must be reported via proper channels
612 * (a'la fsync, or NFS COMMIT operation, etc.).
614 * While we handle mapping->wb_err with atomic operations, the f_wb_err
615 * value is protected by the f_lock since we must ensure that it reflects
616 * the latest value swapped in for this file descriptor.
618 int file_check_and_advance_wb_err(struct file
*file
)
621 errseq_t old
= READ_ONCE(file
->f_wb_err
);
622 struct address_space
*mapping
= file
->f_mapping
;
624 /* Locklessly handle the common case where nothing has changed */
625 if (errseq_check(&mapping
->wb_err
, old
)) {
626 /* Something changed, must use slow path */
627 spin_lock(&file
->f_lock
);
628 old
= file
->f_wb_err
;
629 err
= errseq_check_and_advance(&mapping
->wb_err
,
631 trace_file_check_and_advance_wb_err(file
, old
);
632 spin_unlock(&file
->f_lock
);
636 EXPORT_SYMBOL(file_check_and_advance_wb_err
);
639 * file_write_and_wait_range - write out & wait on a file range
640 * @file: file pointing to address_space with pages
641 * @lstart: offset in bytes where the range starts
642 * @lend: offset in bytes where the range ends (inclusive)
644 * Write out and wait upon file offsets lstart->lend, inclusive.
646 * Note that @lend is inclusive (describes the last byte to be written) so
647 * that this function can be used to write to the very end-of-file (end = -1).
649 * After writing out and waiting on the data, we check and advance the
650 * f_wb_err cursor to the latest value, and return any errors detected there.
652 int file_write_and_wait_range(struct file
*file
, loff_t lstart
, loff_t lend
)
655 struct address_space
*mapping
= file
->f_mapping
;
657 if ((!dax_mapping(mapping
) && mapping
->nrpages
) ||
658 (dax_mapping(mapping
) && mapping
->nrexceptional
)) {
659 err
= __filemap_fdatawrite_range(mapping
, lstart
, lend
,
661 /* See comment of filemap_write_and_wait() */
663 __filemap_fdatawait_range(mapping
, lstart
, lend
);
665 err2
= file_check_and_advance_wb_err(file
);
670 EXPORT_SYMBOL(file_write_and_wait_range
);
673 * replace_page_cache_page - replace a pagecache page with a new one
674 * @old: page to be replaced
675 * @new: page to replace with
676 * @gfp_mask: allocation mode
678 * This function replaces a page in the pagecache with a new one. On
679 * success it acquires the pagecache reference for the new page and
680 * drops it for the old page. Both the old and new pages must be
681 * locked. This function does not add the new page to the LRU, the
682 * caller must do that.
684 * The remove + add is atomic. The only way this function can fail is
685 * memory allocation failure.
687 int replace_page_cache_page(struct page
*old
, struct page
*new, gfp_t gfp_mask
)
691 VM_BUG_ON_PAGE(!PageLocked(old
), old
);
692 VM_BUG_ON_PAGE(!PageLocked(new), new);
693 VM_BUG_ON_PAGE(new->mapping
, new);
695 error
= radix_tree_preload(gfp_mask
& ~__GFP_HIGHMEM
);
697 struct address_space
*mapping
= old
->mapping
;
698 void (*freepage
)(struct page
*);
701 pgoff_t offset
= old
->index
;
702 freepage
= mapping
->a_ops
->freepage
;
705 new->mapping
= mapping
;
708 spin_lock_irqsave(&mapping
->tree_lock
, flags
);
709 __delete_from_page_cache(old
, NULL
);
710 error
= page_cache_tree_insert(mapping
, new, NULL
);
714 * hugetlb pages do not participate in page cache accounting.
717 __inc_node_page_state(new, NR_FILE_PAGES
);
718 if (PageSwapBacked(new))
719 __inc_node_page_state(new, NR_SHMEM
);
720 spin_unlock_irqrestore(&mapping
->tree_lock
, flags
);
721 mem_cgroup_migrate(old
, new);
722 radix_tree_preload_end();
730 EXPORT_SYMBOL_GPL(replace_page_cache_page
);
732 static int __add_to_page_cache_locked(struct page
*page
,
733 struct address_space
*mapping
,
734 pgoff_t offset
, gfp_t gfp_mask
,
737 int huge
= PageHuge(page
);
738 struct mem_cgroup
*memcg
;
741 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
742 VM_BUG_ON_PAGE(PageSwapBacked(page
), page
);
745 error
= mem_cgroup_try_charge(page
, current
->mm
,
746 gfp_mask
, &memcg
, false);
751 error
= radix_tree_maybe_preload(gfp_mask
& ~__GFP_HIGHMEM
);
754 mem_cgroup_cancel_charge(page
, memcg
, false);
759 page
->mapping
= mapping
;
760 page
->index
= offset
;
762 spin_lock_irq(&mapping
->tree_lock
);
763 error
= page_cache_tree_insert(mapping
, page
, shadowp
);
764 radix_tree_preload_end();
768 /* hugetlb pages do not participate in page cache accounting. */
770 __inc_node_page_state(page
, NR_FILE_PAGES
);
771 spin_unlock_irq(&mapping
->tree_lock
);
773 mem_cgroup_commit_charge(page
, memcg
, false, false);
774 trace_mm_filemap_add_to_page_cache(page
);
777 page
->mapping
= NULL
;
778 /* Leave page->index set: truncation relies upon it */
779 spin_unlock_irq(&mapping
->tree_lock
);
781 mem_cgroup_cancel_charge(page
, memcg
, false);
787 * add_to_page_cache_locked - add a locked page to the pagecache
789 * @mapping: the page's address_space
790 * @offset: page index
791 * @gfp_mask: page allocation mode
793 * This function is used to add a page to the pagecache. It must be locked.
794 * This function does not add the page to the LRU. The caller must do that.
796 int add_to_page_cache_locked(struct page
*page
, struct address_space
*mapping
,
797 pgoff_t offset
, gfp_t gfp_mask
)
799 return __add_to_page_cache_locked(page
, mapping
, offset
,
802 EXPORT_SYMBOL(add_to_page_cache_locked
);
804 int add_to_page_cache_lru(struct page
*page
, struct address_space
*mapping
,
805 pgoff_t offset
, gfp_t gfp_mask
)
810 __SetPageLocked(page
);
811 ret
= __add_to_page_cache_locked(page
, mapping
, offset
,
814 __ClearPageLocked(page
);
817 * The page might have been evicted from cache only
818 * recently, in which case it should be activated like
819 * any other repeatedly accessed page.
820 * The exception is pages getting rewritten; evicting other
821 * data from the working set, only to cache data that will
822 * get overwritten with something else, is a waste of memory.
824 if (!(gfp_mask
& __GFP_WRITE
) &&
825 shadow
&& workingset_refault(shadow
)) {
827 workingset_activation(page
);
829 ClearPageActive(page
);
834 EXPORT_SYMBOL_GPL(add_to_page_cache_lru
);
837 struct page
*__page_cache_alloc(gfp_t gfp
)
842 if (cpuset_do_page_mem_spread()) {
843 unsigned int cpuset_mems_cookie
;
845 cpuset_mems_cookie
= read_mems_allowed_begin();
846 n
= cpuset_mem_spread_node();
847 page
= __alloc_pages_node(n
, gfp
, 0);
848 } while (!page
&& read_mems_allowed_retry(cpuset_mems_cookie
));
852 return alloc_pages(gfp
, 0);
854 EXPORT_SYMBOL(__page_cache_alloc
);
858 * In order to wait for pages to become available there must be
859 * waitqueues associated with pages. By using a hash table of
860 * waitqueues where the bucket discipline is to maintain all
861 * waiters on the same queue and wake all when any of the pages
862 * become available, and for the woken contexts to check to be
863 * sure the appropriate page became available, this saves space
864 * at a cost of "thundering herd" phenomena during rare hash
867 #define PAGE_WAIT_TABLE_BITS 8
868 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
869 static wait_queue_head_t page_wait_table
[PAGE_WAIT_TABLE_SIZE
] __cacheline_aligned
;
871 static wait_queue_head_t
*page_waitqueue(struct page
*page
)
873 return &page_wait_table
[hash_ptr(page
, PAGE_WAIT_TABLE_BITS
)];
876 void __init
pagecache_init(void)
880 for (i
= 0; i
< PAGE_WAIT_TABLE_SIZE
; i
++)
881 init_waitqueue_head(&page_wait_table
[i
]);
883 page_writeback_init();
886 struct wait_page_key
{
892 struct wait_page_queue
{
895 wait_queue_entry_t wait
;
898 static int wake_page_function(wait_queue_entry_t
*wait
, unsigned mode
, int sync
, void *arg
)
900 struct wait_page_key
*key
= arg
;
901 struct wait_page_queue
*wait_page
902 = container_of(wait
, struct wait_page_queue
, wait
);
904 if (wait_page
->page
!= key
->page
)
908 if (wait_page
->bit_nr
!= key
->bit_nr
)
910 if (test_bit(key
->bit_nr
, &key
->page
->flags
))
913 return autoremove_wake_function(wait
, mode
, sync
, key
);
916 static void wake_up_page_bit(struct page
*page
, int bit_nr
)
918 wait_queue_head_t
*q
= page_waitqueue(page
);
919 struct wait_page_key key
;
926 spin_lock_irqsave(&q
->lock
, flags
);
927 __wake_up_locked_key(q
, TASK_NORMAL
, &key
);
929 * It is possible for other pages to have collided on the waitqueue
930 * hash, so in that case check for a page match. That prevents a long-
933 * It is still possible to miss a case here, when we woke page waiters
934 * and removed them from the waitqueue, but there are still other
937 if (!waitqueue_active(q
) || !key
.page_match
) {
938 ClearPageWaiters(page
);
940 * It's possible to miss clearing Waiters here, when we woke
941 * our page waiters, but the hashed waitqueue has waiters for
944 * That's okay, it's a rare case. The next waker will clear it.
947 spin_unlock_irqrestore(&q
->lock
, flags
);
950 static void wake_up_page(struct page
*page
, int bit
)
952 if (!PageWaiters(page
))
954 wake_up_page_bit(page
, bit
);
957 static inline int wait_on_page_bit_common(wait_queue_head_t
*q
,
958 struct page
*page
, int bit_nr
, int state
, bool lock
)
960 struct wait_page_queue wait_page
;
961 wait_queue_entry_t
*wait
= &wait_page
.wait
;
965 wait
->func
= wake_page_function
;
966 wait_page
.page
= page
;
967 wait_page
.bit_nr
= bit_nr
;
970 spin_lock_irq(&q
->lock
);
972 if (likely(list_empty(&wait
->entry
))) {
974 __add_wait_queue_entry_tail_exclusive(q
, wait
);
976 __add_wait_queue(q
, wait
);
977 SetPageWaiters(page
);
980 set_current_state(state
);
982 spin_unlock_irq(&q
->lock
);
984 if (likely(test_bit(bit_nr
, &page
->flags
))) {
986 if (unlikely(signal_pending_state(state
, current
))) {
993 if (!test_and_set_bit_lock(bit_nr
, &page
->flags
))
996 if (!test_bit(bit_nr
, &page
->flags
))
1001 finish_wait(q
, wait
);
1004 * A signal could leave PageWaiters set. Clearing it here if
1005 * !waitqueue_active would be possible (by open-coding finish_wait),
1006 * but still fail to catch it in the case of wait hash collision. We
1007 * already can fail to clear wait hash collision cases, so don't
1008 * bother with signals either.
1014 void wait_on_page_bit(struct page
*page
, int bit_nr
)
1016 wait_queue_head_t
*q
= page_waitqueue(page
);
1017 wait_on_page_bit_common(q
, page
, bit_nr
, TASK_UNINTERRUPTIBLE
, false);
1019 EXPORT_SYMBOL(wait_on_page_bit
);
1021 int wait_on_page_bit_killable(struct page
*page
, int bit_nr
)
1023 wait_queue_head_t
*q
= page_waitqueue(page
);
1024 return wait_on_page_bit_common(q
, page
, bit_nr
, TASK_KILLABLE
, false);
1028 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1029 * @page: Page defining the wait queue of interest
1030 * @waiter: Waiter to add to the queue
1032 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1034 void add_page_wait_queue(struct page
*page
, wait_queue_entry_t
*waiter
)
1036 wait_queue_head_t
*q
= page_waitqueue(page
);
1037 unsigned long flags
;
1039 spin_lock_irqsave(&q
->lock
, flags
);
1040 __add_wait_queue(q
, waiter
);
1041 SetPageWaiters(page
);
1042 spin_unlock_irqrestore(&q
->lock
, flags
);
1044 EXPORT_SYMBOL_GPL(add_page_wait_queue
);
1046 #ifndef clear_bit_unlock_is_negative_byte
1049 * PG_waiters is the high bit in the same byte as PG_lock.
1051 * On x86 (and on many other architectures), we can clear PG_lock and
1052 * test the sign bit at the same time. But if the architecture does
1053 * not support that special operation, we just do this all by hand
1056 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1057 * being cleared, but a memory barrier should be unneccssary since it is
1058 * in the same byte as PG_locked.
1060 static inline bool clear_bit_unlock_is_negative_byte(long nr
, volatile void *mem
)
1062 clear_bit_unlock(nr
, mem
);
1063 /* smp_mb__after_atomic(); */
1064 return test_bit(PG_waiters
, mem
);
1070 * unlock_page - unlock a locked page
1073 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1074 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1075 * mechanism between PageLocked pages and PageWriteback pages is shared.
1076 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1078 * Note that this depends on PG_waiters being the sign bit in the byte
1079 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1080 * clear the PG_locked bit and test PG_waiters at the same time fairly
1081 * portably (architectures that do LL/SC can test any bit, while x86 can
1082 * test the sign bit).
1084 void unlock_page(struct page
*page
)
1086 BUILD_BUG_ON(PG_waiters
!= 7);
1087 page
= compound_head(page
);
1088 VM_BUG_ON_PAGE(!PageLocked(page
), page
);
1089 if (clear_bit_unlock_is_negative_byte(PG_locked
, &page
->flags
))
1090 wake_up_page_bit(page
, PG_locked
);
1092 EXPORT_SYMBOL(unlock_page
);
1095 * end_page_writeback - end writeback against a page
1098 void end_page_writeback(struct page
*page
)
1101 * TestClearPageReclaim could be used here but it is an atomic
1102 * operation and overkill in this particular case. Failing to
1103 * shuffle a page marked for immediate reclaim is too mild to
1104 * justify taking an atomic operation penalty at the end of
1105 * ever page writeback.
1107 if (PageReclaim(page
)) {
1108 ClearPageReclaim(page
);
1109 rotate_reclaimable_page(page
);
1112 if (!test_clear_page_writeback(page
))
1115 smp_mb__after_atomic();
1116 wake_up_page(page
, PG_writeback
);
1118 EXPORT_SYMBOL(end_page_writeback
);
1121 * After completing I/O on a page, call this routine to update the page
1122 * flags appropriately
1124 void page_endio(struct page
*page
, bool is_write
, int err
)
1128 SetPageUptodate(page
);
1130 ClearPageUptodate(page
);
1136 struct address_space
*mapping
;
1139 mapping
= page_mapping(page
);
1141 mapping_set_error(mapping
, err
);
1143 end_page_writeback(page
);
1146 EXPORT_SYMBOL_GPL(page_endio
);
1149 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1150 * @__page: the page to lock
1152 void __lock_page(struct page
*__page
)
1154 struct page
*page
= compound_head(__page
);
1155 wait_queue_head_t
*q
= page_waitqueue(page
);
1156 wait_on_page_bit_common(q
, page
, PG_locked
, TASK_UNINTERRUPTIBLE
, true);
1158 EXPORT_SYMBOL(__lock_page
);
1160 int __lock_page_killable(struct page
*__page
)
1162 struct page
*page
= compound_head(__page
);
1163 wait_queue_head_t
*q
= page_waitqueue(page
);
1164 return wait_on_page_bit_common(q
, page
, PG_locked
, TASK_KILLABLE
, true);
1166 EXPORT_SYMBOL_GPL(__lock_page_killable
);
1170 * 1 - page is locked; mmap_sem is still held.
1171 * 0 - page is not locked.
1172 * mmap_sem has been released (up_read()), unless flags had both
1173 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1174 * which case mmap_sem is still held.
1176 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1177 * with the page locked and the mmap_sem unperturbed.
1179 int __lock_page_or_retry(struct page
*page
, struct mm_struct
*mm
,
1182 if (flags
& FAULT_FLAG_ALLOW_RETRY
) {
1184 * CAUTION! In this case, mmap_sem is not released
1185 * even though return 0.
1187 if (flags
& FAULT_FLAG_RETRY_NOWAIT
)
1190 up_read(&mm
->mmap_sem
);
1191 if (flags
& FAULT_FLAG_KILLABLE
)
1192 wait_on_page_locked_killable(page
);
1194 wait_on_page_locked(page
);
1197 if (flags
& FAULT_FLAG_KILLABLE
) {
1200 ret
= __lock_page_killable(page
);
1202 up_read(&mm
->mmap_sem
);
1212 * page_cache_next_hole - find the next hole (not-present entry)
1215 * @max_scan: maximum range to search
1217 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
1218 * lowest indexed hole.
1220 * Returns: the index of the hole if found, otherwise returns an index
1221 * outside of the set specified (in which case 'return - index >=
1222 * max_scan' will be true). In rare cases of index wrap-around, 0 will
1225 * page_cache_next_hole may be called under rcu_read_lock. However,
1226 * like radix_tree_gang_lookup, this will not atomically search a
1227 * snapshot of the tree at a single point in time. For example, if a
1228 * hole is created at index 5, then subsequently a hole is created at
1229 * index 10, page_cache_next_hole covering both indexes may return 10
1230 * if called under rcu_read_lock.
1232 pgoff_t
page_cache_next_hole(struct address_space
*mapping
,
1233 pgoff_t index
, unsigned long max_scan
)
1237 for (i
= 0; i
< max_scan
; i
++) {
1240 page
= radix_tree_lookup(&mapping
->page_tree
, index
);
1241 if (!page
|| radix_tree_exceptional_entry(page
))
1250 EXPORT_SYMBOL(page_cache_next_hole
);
1253 * page_cache_prev_hole - find the prev hole (not-present entry)
1256 * @max_scan: maximum range to search
1258 * Search backwards in the range [max(index-max_scan+1, 0), index] for
1261 * Returns: the index of the hole if found, otherwise returns an index
1262 * outside of the set specified (in which case 'index - return >=
1263 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
1266 * page_cache_prev_hole may be called under rcu_read_lock. However,
1267 * like radix_tree_gang_lookup, this will not atomically search a
1268 * snapshot of the tree at a single point in time. For example, if a
1269 * hole is created at index 10, then subsequently a hole is created at
1270 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1271 * called under rcu_read_lock.
1273 pgoff_t
page_cache_prev_hole(struct address_space
*mapping
,
1274 pgoff_t index
, unsigned long max_scan
)
1278 for (i
= 0; i
< max_scan
; i
++) {
1281 page
= radix_tree_lookup(&mapping
->page_tree
, index
);
1282 if (!page
|| radix_tree_exceptional_entry(page
))
1285 if (index
== ULONG_MAX
)
1291 EXPORT_SYMBOL(page_cache_prev_hole
);
1294 * find_get_entry - find and get a page cache entry
1295 * @mapping: the address_space to search
1296 * @offset: the page cache index
1298 * Looks up the page cache slot at @mapping & @offset. If there is a
1299 * page cache page, it is returned with an increased refcount.
1301 * If the slot holds a shadow entry of a previously evicted page, or a
1302 * swap entry from shmem/tmpfs, it is returned.
1304 * Otherwise, %NULL is returned.
1306 struct page
*find_get_entry(struct address_space
*mapping
, pgoff_t offset
)
1309 struct page
*head
, *page
;
1314 pagep
= radix_tree_lookup_slot(&mapping
->page_tree
, offset
);
1316 page
= radix_tree_deref_slot(pagep
);
1317 if (unlikely(!page
))
1319 if (radix_tree_exception(page
)) {
1320 if (radix_tree_deref_retry(page
))
1323 * A shadow entry of a recently evicted page,
1324 * or a swap entry from shmem/tmpfs. Return
1325 * it without attempting to raise page count.
1330 head
= compound_head(page
);
1331 if (!page_cache_get_speculative(head
))
1334 /* The page was split under us? */
1335 if (compound_head(page
) != head
) {
1341 * Has the page moved?
1342 * This is part of the lockless pagecache protocol. See
1343 * include/linux/pagemap.h for details.
1345 if (unlikely(page
!= *pagep
)) {
1355 EXPORT_SYMBOL(find_get_entry
);
1358 * find_lock_entry - locate, pin and lock a page cache entry
1359 * @mapping: the address_space to search
1360 * @offset: the page cache index
1362 * Looks up the page cache slot at @mapping & @offset. If there is a
1363 * page cache page, it is returned locked and with an increased
1366 * If the slot holds a shadow entry of a previously evicted page, or a
1367 * swap entry from shmem/tmpfs, it is returned.
1369 * Otherwise, %NULL is returned.
1371 * find_lock_entry() may sleep.
1373 struct page
*find_lock_entry(struct address_space
*mapping
, pgoff_t offset
)
1378 page
= find_get_entry(mapping
, offset
);
1379 if (page
&& !radix_tree_exception(page
)) {
1381 /* Has the page been truncated? */
1382 if (unlikely(page_mapping(page
) != mapping
)) {
1387 VM_BUG_ON_PAGE(page_to_pgoff(page
) != offset
, page
);
1391 EXPORT_SYMBOL(find_lock_entry
);
1394 * pagecache_get_page - find and get a page reference
1395 * @mapping: the address_space to search
1396 * @offset: the page index
1397 * @fgp_flags: PCG flags
1398 * @gfp_mask: gfp mask to use for the page cache data page allocation
1400 * Looks up the page cache slot at @mapping & @offset.
1402 * PCG flags modify how the page is returned.
1404 * @fgp_flags can be:
1406 * - FGP_ACCESSED: the page will be marked accessed
1407 * - FGP_LOCK: Page is return locked
1408 * - FGP_CREAT: If page is not present then a new page is allocated using
1409 * @gfp_mask and added to the page cache and the VM's LRU
1410 * list. The page is returned locked and with an increased
1411 * refcount. Otherwise, NULL is returned.
1413 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1414 * if the GFP flags specified for FGP_CREAT are atomic.
1416 * If there is a page cache page, it is returned with an increased refcount.
1418 struct page
*pagecache_get_page(struct address_space
*mapping
, pgoff_t offset
,
1419 int fgp_flags
, gfp_t gfp_mask
)
1424 page
= find_get_entry(mapping
, offset
);
1425 if (radix_tree_exceptional_entry(page
))
1430 if (fgp_flags
& FGP_LOCK
) {
1431 if (fgp_flags
& FGP_NOWAIT
) {
1432 if (!trylock_page(page
)) {
1440 /* Has the page been truncated? */
1441 if (unlikely(page
->mapping
!= mapping
)) {
1446 VM_BUG_ON_PAGE(page
->index
!= offset
, page
);
1449 if (page
&& (fgp_flags
& FGP_ACCESSED
))
1450 mark_page_accessed(page
);
1453 if (!page
&& (fgp_flags
& FGP_CREAT
)) {
1455 if ((fgp_flags
& FGP_WRITE
) && mapping_cap_account_dirty(mapping
))
1456 gfp_mask
|= __GFP_WRITE
;
1457 if (fgp_flags
& FGP_NOFS
)
1458 gfp_mask
&= ~__GFP_FS
;
1460 page
= __page_cache_alloc(gfp_mask
);
1464 if (WARN_ON_ONCE(!(fgp_flags
& FGP_LOCK
)))
1465 fgp_flags
|= FGP_LOCK
;
1467 /* Init accessed so avoid atomic mark_page_accessed later */
1468 if (fgp_flags
& FGP_ACCESSED
)
1469 __SetPageReferenced(page
);
1471 err
= add_to_page_cache_lru(page
, mapping
, offset
,
1472 gfp_mask
& GFP_RECLAIM_MASK
);
1473 if (unlikely(err
)) {
1483 EXPORT_SYMBOL(pagecache_get_page
);
1486 * find_get_entries - gang pagecache lookup
1487 * @mapping: The address_space to search
1488 * @start: The starting page cache index
1489 * @nr_entries: The maximum number of entries
1490 * @entries: Where the resulting entries are placed
1491 * @indices: The cache indices corresponding to the entries in @entries
1493 * find_get_entries() will search for and return a group of up to
1494 * @nr_entries entries in the mapping. The entries are placed at
1495 * @entries. find_get_entries() takes a reference against any actual
1498 * The search returns a group of mapping-contiguous page cache entries
1499 * with ascending indexes. There may be holes in the indices due to
1500 * not-present pages.
1502 * Any shadow entries of evicted pages, or swap entries from
1503 * shmem/tmpfs, are included in the returned array.
1505 * find_get_entries() returns the number of pages and shadow entries
1508 unsigned find_get_entries(struct address_space
*mapping
,
1509 pgoff_t start
, unsigned int nr_entries
,
1510 struct page
**entries
, pgoff_t
*indices
)
1513 unsigned int ret
= 0;
1514 struct radix_tree_iter iter
;
1520 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, start
) {
1521 struct page
*head
, *page
;
1523 page
= radix_tree_deref_slot(slot
);
1524 if (unlikely(!page
))
1526 if (radix_tree_exception(page
)) {
1527 if (radix_tree_deref_retry(page
)) {
1528 slot
= radix_tree_iter_retry(&iter
);
1532 * A shadow entry of a recently evicted page, a swap
1533 * entry from shmem/tmpfs or a DAX entry. Return it
1534 * without attempting to raise page count.
1539 head
= compound_head(page
);
1540 if (!page_cache_get_speculative(head
))
1543 /* The page was split under us? */
1544 if (compound_head(page
) != head
) {
1549 /* Has the page moved? */
1550 if (unlikely(page
!= *slot
)) {
1555 indices
[ret
] = iter
.index
;
1556 entries
[ret
] = page
;
1557 if (++ret
== nr_entries
)
1565 * find_get_pages - gang pagecache lookup
1566 * @mapping: The address_space to search
1567 * @start: The starting page index
1568 * @nr_pages: The maximum number of pages
1569 * @pages: Where the resulting pages are placed
1571 * find_get_pages() will search for and return a group of up to
1572 * @nr_pages pages in the mapping. The pages are placed at @pages.
1573 * find_get_pages() takes a reference against the returned pages.
1575 * The search returns a group of mapping-contiguous pages with ascending
1576 * indexes. There may be holes in the indices due to not-present pages.
1578 * find_get_pages() returns the number of pages which were found.
1580 unsigned find_get_pages(struct address_space
*mapping
, pgoff_t start
,
1581 unsigned int nr_pages
, struct page
**pages
)
1583 struct radix_tree_iter iter
;
1587 if (unlikely(!nr_pages
))
1591 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
, start
) {
1592 struct page
*head
, *page
;
1594 page
= radix_tree_deref_slot(slot
);
1595 if (unlikely(!page
))
1598 if (radix_tree_exception(page
)) {
1599 if (radix_tree_deref_retry(page
)) {
1600 slot
= radix_tree_iter_retry(&iter
);
1604 * A shadow entry of a recently evicted page,
1605 * or a swap entry from shmem/tmpfs. Skip
1611 head
= compound_head(page
);
1612 if (!page_cache_get_speculative(head
))
1615 /* The page was split under us? */
1616 if (compound_head(page
) != head
) {
1621 /* Has the page moved? */
1622 if (unlikely(page
!= *slot
)) {
1628 if (++ret
== nr_pages
)
1637 * find_get_pages_contig - gang contiguous pagecache lookup
1638 * @mapping: The address_space to search
1639 * @index: The starting page index
1640 * @nr_pages: The maximum number of pages
1641 * @pages: Where the resulting pages are placed
1643 * find_get_pages_contig() works exactly like find_get_pages(), except
1644 * that the returned number of pages are guaranteed to be contiguous.
1646 * find_get_pages_contig() returns the number of pages which were found.
1648 unsigned find_get_pages_contig(struct address_space
*mapping
, pgoff_t index
,
1649 unsigned int nr_pages
, struct page
**pages
)
1651 struct radix_tree_iter iter
;
1653 unsigned int ret
= 0;
1655 if (unlikely(!nr_pages
))
1659 radix_tree_for_each_contig(slot
, &mapping
->page_tree
, &iter
, index
) {
1660 struct page
*head
, *page
;
1662 page
= radix_tree_deref_slot(slot
);
1663 /* The hole, there no reason to continue */
1664 if (unlikely(!page
))
1667 if (radix_tree_exception(page
)) {
1668 if (radix_tree_deref_retry(page
)) {
1669 slot
= radix_tree_iter_retry(&iter
);
1673 * A shadow entry of a recently evicted page,
1674 * or a swap entry from shmem/tmpfs. Stop
1675 * looking for contiguous pages.
1680 head
= compound_head(page
);
1681 if (!page_cache_get_speculative(head
))
1684 /* The page was split under us? */
1685 if (compound_head(page
) != head
) {
1690 /* Has the page moved? */
1691 if (unlikely(page
!= *slot
)) {
1697 * must check mapping and index after taking the ref.
1698 * otherwise we can get both false positives and false
1699 * negatives, which is just confusing to the caller.
1701 if (page
->mapping
== NULL
|| page_to_pgoff(page
) != iter
.index
) {
1707 if (++ret
== nr_pages
)
1713 EXPORT_SYMBOL(find_get_pages_contig
);
1716 * find_get_pages_tag - find and return pages that match @tag
1717 * @mapping: the address_space to search
1718 * @index: the starting page index
1719 * @tag: the tag index
1720 * @nr_pages: the maximum number of pages
1721 * @pages: where the resulting pages are placed
1723 * Like find_get_pages, except we only return pages which are tagged with
1724 * @tag. We update @index to index the next page for the traversal.
1726 unsigned find_get_pages_tag(struct address_space
*mapping
, pgoff_t
*index
,
1727 int tag
, unsigned int nr_pages
, struct page
**pages
)
1729 struct radix_tree_iter iter
;
1733 if (unlikely(!nr_pages
))
1737 radix_tree_for_each_tagged(slot
, &mapping
->page_tree
,
1738 &iter
, *index
, tag
) {
1739 struct page
*head
, *page
;
1741 page
= radix_tree_deref_slot(slot
);
1742 if (unlikely(!page
))
1745 if (radix_tree_exception(page
)) {
1746 if (radix_tree_deref_retry(page
)) {
1747 slot
= radix_tree_iter_retry(&iter
);
1751 * A shadow entry of a recently evicted page.
1753 * Those entries should never be tagged, but
1754 * this tree walk is lockless and the tags are
1755 * looked up in bulk, one radix tree node at a
1756 * time, so there is a sizable window for page
1757 * reclaim to evict a page we saw tagged.
1764 head
= compound_head(page
);
1765 if (!page_cache_get_speculative(head
))
1768 /* The page was split under us? */
1769 if (compound_head(page
) != head
) {
1774 /* Has the page moved? */
1775 if (unlikely(page
!= *slot
)) {
1781 if (++ret
== nr_pages
)
1788 *index
= pages
[ret
- 1]->index
+ 1;
1792 EXPORT_SYMBOL(find_get_pages_tag
);
1795 * find_get_entries_tag - find and return entries that match @tag
1796 * @mapping: the address_space to search
1797 * @start: the starting page cache index
1798 * @tag: the tag index
1799 * @nr_entries: the maximum number of entries
1800 * @entries: where the resulting entries are placed
1801 * @indices: the cache indices corresponding to the entries in @entries
1803 * Like find_get_entries, except we only return entries which are tagged with
1806 unsigned find_get_entries_tag(struct address_space
*mapping
, pgoff_t start
,
1807 int tag
, unsigned int nr_entries
,
1808 struct page
**entries
, pgoff_t
*indices
)
1811 unsigned int ret
= 0;
1812 struct radix_tree_iter iter
;
1818 radix_tree_for_each_tagged(slot
, &mapping
->page_tree
,
1819 &iter
, start
, tag
) {
1820 struct page
*head
, *page
;
1822 page
= radix_tree_deref_slot(slot
);
1823 if (unlikely(!page
))
1825 if (radix_tree_exception(page
)) {
1826 if (radix_tree_deref_retry(page
)) {
1827 slot
= radix_tree_iter_retry(&iter
);
1832 * A shadow entry of a recently evicted page, a swap
1833 * entry from shmem/tmpfs or a DAX entry. Return it
1834 * without attempting to raise page count.
1839 head
= compound_head(page
);
1840 if (!page_cache_get_speculative(head
))
1843 /* The page was split under us? */
1844 if (compound_head(page
) != head
) {
1849 /* Has the page moved? */
1850 if (unlikely(page
!= *slot
)) {
1855 indices
[ret
] = iter
.index
;
1856 entries
[ret
] = page
;
1857 if (++ret
== nr_entries
)
1863 EXPORT_SYMBOL(find_get_entries_tag
);
1866 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1867 * a _large_ part of the i/o request. Imagine the worst scenario:
1869 * ---R__________________________________________B__________
1870 * ^ reading here ^ bad block(assume 4k)
1872 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1873 * => failing the whole request => read(R) => read(R+1) =>
1874 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1875 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1876 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1878 * It is going insane. Fix it by quickly scaling down the readahead size.
1880 static void shrink_readahead_size_eio(struct file
*filp
,
1881 struct file_ra_state
*ra
)
1887 * do_generic_file_read - generic file read routine
1888 * @filp: the file to read
1889 * @ppos: current file position
1890 * @iter: data destination
1891 * @written: already copied
1893 * This is a generic file read routine, and uses the
1894 * mapping->a_ops->readpage() function for the actual low-level stuff.
1896 * This is really ugly. But the goto's actually try to clarify some
1897 * of the logic when it comes to error handling etc.
1899 static ssize_t
do_generic_file_read(struct file
*filp
, loff_t
*ppos
,
1900 struct iov_iter
*iter
, ssize_t written
)
1902 struct address_space
*mapping
= filp
->f_mapping
;
1903 struct inode
*inode
= mapping
->host
;
1904 struct file_ra_state
*ra
= &filp
->f_ra
;
1908 unsigned long offset
; /* offset into pagecache page */
1909 unsigned int prev_offset
;
1912 if (unlikely(*ppos
>= inode
->i_sb
->s_maxbytes
))
1914 iov_iter_truncate(iter
, inode
->i_sb
->s_maxbytes
);
1916 index
= *ppos
>> PAGE_SHIFT
;
1917 prev_index
= ra
->prev_pos
>> PAGE_SHIFT
;
1918 prev_offset
= ra
->prev_pos
& (PAGE_SIZE
-1);
1919 last_index
= (*ppos
+ iter
->count
+ PAGE_SIZE
-1) >> PAGE_SHIFT
;
1920 offset
= *ppos
& ~PAGE_MASK
;
1926 unsigned long nr
, ret
;
1930 if (fatal_signal_pending(current
)) {
1935 page
= find_get_page(mapping
, index
);
1937 page_cache_sync_readahead(mapping
,
1939 index
, last_index
- index
);
1940 page
= find_get_page(mapping
, index
);
1941 if (unlikely(page
== NULL
))
1942 goto no_cached_page
;
1944 if (PageReadahead(page
)) {
1945 page_cache_async_readahead(mapping
,
1947 index
, last_index
- index
);
1949 if (!PageUptodate(page
)) {
1951 * See comment in do_read_cache_page on why
1952 * wait_on_page_locked is used to avoid unnecessarily
1953 * serialisations and why it's safe.
1955 error
= wait_on_page_locked_killable(page
);
1956 if (unlikely(error
))
1957 goto readpage_error
;
1958 if (PageUptodate(page
))
1961 if (inode
->i_blkbits
== PAGE_SHIFT
||
1962 !mapping
->a_ops
->is_partially_uptodate
)
1963 goto page_not_up_to_date
;
1964 /* pipes can't handle partially uptodate pages */
1965 if (unlikely(iter
->type
& ITER_PIPE
))
1966 goto page_not_up_to_date
;
1967 if (!trylock_page(page
))
1968 goto page_not_up_to_date
;
1969 /* Did it get truncated before we got the lock? */
1971 goto page_not_up_to_date_locked
;
1972 if (!mapping
->a_ops
->is_partially_uptodate(page
,
1973 offset
, iter
->count
))
1974 goto page_not_up_to_date_locked
;
1979 * i_size must be checked after we know the page is Uptodate.
1981 * Checking i_size after the check allows us to calculate
1982 * the correct value for "nr", which means the zero-filled
1983 * part of the page is not copied back to userspace (unless
1984 * another truncate extends the file - this is desired though).
1987 isize
= i_size_read(inode
);
1988 end_index
= (isize
- 1) >> PAGE_SHIFT
;
1989 if (unlikely(!isize
|| index
> end_index
)) {
1994 /* nr is the maximum number of bytes to copy from this page */
1996 if (index
== end_index
) {
1997 nr
= ((isize
- 1) & ~PAGE_MASK
) + 1;
2005 /* If users can be writing to this page using arbitrary
2006 * virtual addresses, take care about potential aliasing
2007 * before reading the page on the kernel side.
2009 if (mapping_writably_mapped(mapping
))
2010 flush_dcache_page(page
);
2013 * When a sequential read accesses a page several times,
2014 * only mark it as accessed the first time.
2016 if (prev_index
!= index
|| offset
!= prev_offset
)
2017 mark_page_accessed(page
);
2021 * Ok, we have the page, and it's up-to-date, so
2022 * now we can copy it to user space...
2025 ret
= copy_page_to_iter(page
, offset
, nr
, iter
);
2027 index
+= offset
>> PAGE_SHIFT
;
2028 offset
&= ~PAGE_MASK
;
2029 prev_offset
= offset
;
2033 if (!iov_iter_count(iter
))
2041 page_not_up_to_date
:
2042 /* Get exclusive access to the page ... */
2043 error
= lock_page_killable(page
);
2044 if (unlikely(error
))
2045 goto readpage_error
;
2047 page_not_up_to_date_locked
:
2048 /* Did it get truncated before we got the lock? */
2049 if (!page
->mapping
) {
2055 /* Did somebody else fill it already? */
2056 if (PageUptodate(page
)) {
2063 * A previous I/O error may have been due to temporary
2064 * failures, eg. multipath errors.
2065 * PG_error will be set again if readpage fails.
2067 ClearPageError(page
);
2068 /* Start the actual read. The read will unlock the page. */
2069 error
= mapping
->a_ops
->readpage(filp
, page
);
2071 if (unlikely(error
)) {
2072 if (error
== AOP_TRUNCATED_PAGE
) {
2077 goto readpage_error
;
2080 if (!PageUptodate(page
)) {
2081 error
= lock_page_killable(page
);
2082 if (unlikely(error
))
2083 goto readpage_error
;
2084 if (!PageUptodate(page
)) {
2085 if (page
->mapping
== NULL
) {
2087 * invalidate_mapping_pages got it
2094 shrink_readahead_size_eio(filp
, ra
);
2096 goto readpage_error
;
2104 /* UHHUH! A synchronous read error occurred. Report it */
2110 * Ok, it wasn't cached, so we need to create a new
2113 page
= page_cache_alloc_cold(mapping
);
2118 error
= add_to_page_cache_lru(page
, mapping
, index
,
2119 mapping_gfp_constraint(mapping
, GFP_KERNEL
));
2122 if (error
== -EEXIST
) {
2132 ra
->prev_pos
= prev_index
;
2133 ra
->prev_pos
<<= PAGE_SHIFT
;
2134 ra
->prev_pos
|= prev_offset
;
2136 *ppos
= ((loff_t
)index
<< PAGE_SHIFT
) + offset
;
2137 file_accessed(filp
);
2138 return written
? written
: error
;
2142 * generic_file_read_iter - generic filesystem read routine
2143 * @iocb: kernel I/O control block
2144 * @iter: destination for the data read
2146 * This is the "read_iter()" routine for all filesystems
2147 * that can use the page cache directly.
2150 generic_file_read_iter(struct kiocb
*iocb
, struct iov_iter
*iter
)
2152 struct file
*file
= iocb
->ki_filp
;
2154 size_t count
= iov_iter_count(iter
);
2157 goto out
; /* skip atime */
2159 if (iocb
->ki_flags
& IOCB_DIRECT
) {
2160 struct address_space
*mapping
= file
->f_mapping
;
2161 struct inode
*inode
= mapping
->host
;
2164 size
= i_size_read(inode
);
2165 if (iocb
->ki_flags
& IOCB_NOWAIT
) {
2166 if (filemap_range_has_page(mapping
, iocb
->ki_pos
,
2167 iocb
->ki_pos
+ count
- 1))
2170 retval
= filemap_write_and_wait_range(mapping
,
2172 iocb
->ki_pos
+ count
- 1);
2177 file_accessed(file
);
2179 retval
= mapping
->a_ops
->direct_IO(iocb
, iter
);
2181 iocb
->ki_pos
+= retval
;
2184 iov_iter_revert(iter
, count
- iov_iter_count(iter
));
2187 * Btrfs can have a short DIO read if we encounter
2188 * compressed extents, so if there was an error, or if
2189 * we've already read everything we wanted to, or if
2190 * there was a short read because we hit EOF, go ahead
2191 * and return. Otherwise fallthrough to buffered io for
2192 * the rest of the read. Buffered reads will not work for
2193 * DAX files, so don't bother trying.
2195 if (retval
< 0 || !count
|| iocb
->ki_pos
>= size
||
2200 retval
= do_generic_file_read(file
, &iocb
->ki_pos
, iter
, retval
);
2204 EXPORT_SYMBOL(generic_file_read_iter
);
2208 * page_cache_read - adds requested page to the page cache if not already there
2209 * @file: file to read
2210 * @offset: page index
2211 * @gfp_mask: memory allocation flags
2213 * This adds the requested page to the page cache if it isn't already there,
2214 * and schedules an I/O to read in its contents from disk.
2216 static int page_cache_read(struct file
*file
, pgoff_t offset
, gfp_t gfp_mask
)
2218 struct address_space
*mapping
= file
->f_mapping
;
2223 page
= __page_cache_alloc(gfp_mask
|__GFP_COLD
);
2227 ret
= add_to_page_cache_lru(page
, mapping
, offset
, gfp_mask
& GFP_KERNEL
);
2229 ret
= mapping
->a_ops
->readpage(file
, page
);
2230 else if (ret
== -EEXIST
)
2231 ret
= 0; /* losing race to add is OK */
2235 } while (ret
== AOP_TRUNCATED_PAGE
);
2240 #define MMAP_LOTSAMISS (100)
2243 * Synchronous readahead happens when we don't even find
2244 * a page in the page cache at all.
2246 static void do_sync_mmap_readahead(struct vm_area_struct
*vma
,
2247 struct file_ra_state
*ra
,
2251 struct address_space
*mapping
= file
->f_mapping
;
2253 /* If we don't want any read-ahead, don't bother */
2254 if (vma
->vm_flags
& VM_RAND_READ
)
2259 if (vma
->vm_flags
& VM_SEQ_READ
) {
2260 page_cache_sync_readahead(mapping
, ra
, file
, offset
,
2265 /* Avoid banging the cache line if not needed */
2266 if (ra
->mmap_miss
< MMAP_LOTSAMISS
* 10)
2270 * Do we miss much more than hit in this file? If so,
2271 * stop bothering with read-ahead. It will only hurt.
2273 if (ra
->mmap_miss
> MMAP_LOTSAMISS
)
2279 ra
->start
= max_t(long, 0, offset
- ra
->ra_pages
/ 2);
2280 ra
->size
= ra
->ra_pages
;
2281 ra
->async_size
= ra
->ra_pages
/ 4;
2282 ra_submit(ra
, mapping
, file
);
2286 * Asynchronous readahead happens when we find the page and PG_readahead,
2287 * so we want to possibly extend the readahead further..
2289 static void do_async_mmap_readahead(struct vm_area_struct
*vma
,
2290 struct file_ra_state
*ra
,
2295 struct address_space
*mapping
= file
->f_mapping
;
2297 /* If we don't want any read-ahead, don't bother */
2298 if (vma
->vm_flags
& VM_RAND_READ
)
2300 if (ra
->mmap_miss
> 0)
2302 if (PageReadahead(page
))
2303 page_cache_async_readahead(mapping
, ra
, file
,
2304 page
, offset
, ra
->ra_pages
);
2308 * filemap_fault - read in file data for page fault handling
2309 * @vmf: struct vm_fault containing details of the fault
2311 * filemap_fault() is invoked via the vma operations vector for a
2312 * mapped memory region to read in file data during a page fault.
2314 * The goto's are kind of ugly, but this streamlines the normal case of having
2315 * it in the page cache, and handles the special cases reasonably without
2316 * having a lot of duplicated code.
2318 * vma->vm_mm->mmap_sem must be held on entry.
2320 * If our return value has VM_FAULT_RETRY set, it's because
2321 * lock_page_or_retry() returned 0.
2322 * The mmap_sem has usually been released in this case.
2323 * See __lock_page_or_retry() for the exception.
2325 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2326 * has not been released.
2328 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2330 int filemap_fault(struct vm_fault
*vmf
)
2333 struct file
*file
= vmf
->vma
->vm_file
;
2334 struct address_space
*mapping
= file
->f_mapping
;
2335 struct file_ra_state
*ra
= &file
->f_ra
;
2336 struct inode
*inode
= mapping
->host
;
2337 pgoff_t offset
= vmf
->pgoff
;
2342 max_off
= DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
);
2343 if (unlikely(offset
>= max_off
))
2344 return VM_FAULT_SIGBUS
;
2347 * Do we have something in the page cache already?
2349 page
= find_get_page(mapping
, offset
);
2350 if (likely(page
) && !(vmf
->flags
& FAULT_FLAG_TRIED
)) {
2352 * We found the page, so try async readahead before
2353 * waiting for the lock.
2355 do_async_mmap_readahead(vmf
->vma
, ra
, file
, page
, offset
);
2357 /* No page in the page cache at all */
2358 do_sync_mmap_readahead(vmf
->vma
, ra
, file
, offset
);
2359 count_vm_event(PGMAJFAULT
);
2360 count_memcg_event_mm(vmf
->vma
->vm_mm
, PGMAJFAULT
);
2361 ret
= VM_FAULT_MAJOR
;
2363 page
= find_get_page(mapping
, offset
);
2365 goto no_cached_page
;
2368 if (!lock_page_or_retry(page
, vmf
->vma
->vm_mm
, vmf
->flags
)) {
2370 return ret
| VM_FAULT_RETRY
;
2373 /* Did it get truncated? */
2374 if (unlikely(page
->mapping
!= mapping
)) {
2379 VM_BUG_ON_PAGE(page
->index
!= offset
, page
);
2382 * We have a locked page in the page cache, now we need to check
2383 * that it's up-to-date. If not, it is going to be due to an error.
2385 if (unlikely(!PageUptodate(page
)))
2386 goto page_not_uptodate
;
2389 * Found the page and have a reference on it.
2390 * We must recheck i_size under page lock.
2392 max_off
= DIV_ROUND_UP(i_size_read(inode
), PAGE_SIZE
);
2393 if (unlikely(offset
>= max_off
)) {
2396 return VM_FAULT_SIGBUS
;
2400 return ret
| VM_FAULT_LOCKED
;
2404 * We're only likely to ever get here if MADV_RANDOM is in
2407 error
= page_cache_read(file
, offset
, vmf
->gfp_mask
);
2410 * The page we want has now been added to the page cache.
2411 * In the unlikely event that someone removed it in the
2412 * meantime, we'll just come back here and read it again.
2418 * An error return from page_cache_read can result if the
2419 * system is low on memory, or a problem occurs while trying
2422 if (error
== -ENOMEM
)
2423 return VM_FAULT_OOM
;
2424 return VM_FAULT_SIGBUS
;
2428 * Umm, take care of errors if the page isn't up-to-date.
2429 * Try to re-read it _once_. We do this synchronously,
2430 * because there really aren't any performance issues here
2431 * and we need to check for errors.
2433 ClearPageError(page
);
2434 error
= mapping
->a_ops
->readpage(file
, page
);
2436 wait_on_page_locked(page
);
2437 if (!PageUptodate(page
))
2442 if (!error
|| error
== AOP_TRUNCATED_PAGE
)
2445 /* Things didn't work out. Return zero to tell the mm layer so. */
2446 shrink_readahead_size_eio(file
, ra
);
2447 return VM_FAULT_SIGBUS
;
2449 EXPORT_SYMBOL(filemap_fault
);
2451 void filemap_map_pages(struct vm_fault
*vmf
,
2452 pgoff_t start_pgoff
, pgoff_t end_pgoff
)
2454 struct radix_tree_iter iter
;
2456 struct file
*file
= vmf
->vma
->vm_file
;
2457 struct address_space
*mapping
= file
->f_mapping
;
2458 pgoff_t last_pgoff
= start_pgoff
;
2459 unsigned long max_idx
;
2460 struct page
*head
, *page
;
2463 radix_tree_for_each_slot(slot
, &mapping
->page_tree
, &iter
,
2465 if (iter
.index
> end_pgoff
)
2468 page
= radix_tree_deref_slot(slot
);
2469 if (unlikely(!page
))
2471 if (radix_tree_exception(page
)) {
2472 if (radix_tree_deref_retry(page
)) {
2473 slot
= radix_tree_iter_retry(&iter
);
2479 head
= compound_head(page
);
2480 if (!page_cache_get_speculative(head
))
2483 /* The page was split under us? */
2484 if (compound_head(page
) != head
) {
2489 /* Has the page moved? */
2490 if (unlikely(page
!= *slot
)) {
2495 if (!PageUptodate(page
) ||
2496 PageReadahead(page
) ||
2499 if (!trylock_page(page
))
2502 if (page
->mapping
!= mapping
|| !PageUptodate(page
))
2505 max_idx
= DIV_ROUND_UP(i_size_read(mapping
->host
), PAGE_SIZE
);
2506 if (page
->index
>= max_idx
)
2509 if (file
->f_ra
.mmap_miss
> 0)
2510 file
->f_ra
.mmap_miss
--;
2512 vmf
->address
+= (iter
.index
- last_pgoff
) << PAGE_SHIFT
;
2514 vmf
->pte
+= iter
.index
- last_pgoff
;
2515 last_pgoff
= iter
.index
;
2516 if (alloc_set_pte(vmf
, NULL
, page
))
2525 /* Huge page is mapped? No need to proceed. */
2526 if (pmd_trans_huge(*vmf
->pmd
))
2528 if (iter
.index
== end_pgoff
)
2533 EXPORT_SYMBOL(filemap_map_pages
);
2535 int filemap_page_mkwrite(struct vm_fault
*vmf
)
2537 struct page
*page
= vmf
->page
;
2538 struct inode
*inode
= file_inode(vmf
->vma
->vm_file
);
2539 int ret
= VM_FAULT_LOCKED
;
2541 sb_start_pagefault(inode
->i_sb
);
2542 file_update_time(vmf
->vma
->vm_file
);
2544 if (page
->mapping
!= inode
->i_mapping
) {
2546 ret
= VM_FAULT_NOPAGE
;
2550 * We mark the page dirty already here so that when freeze is in
2551 * progress, we are guaranteed that writeback during freezing will
2552 * see the dirty page and writeprotect it again.
2554 set_page_dirty(page
);
2555 wait_for_stable_page(page
);
2557 sb_end_pagefault(inode
->i_sb
);
2560 EXPORT_SYMBOL(filemap_page_mkwrite
);
2562 const struct vm_operations_struct generic_file_vm_ops
= {
2563 .fault
= filemap_fault
,
2564 .map_pages
= filemap_map_pages
,
2565 .page_mkwrite
= filemap_page_mkwrite
,
2568 /* This is used for a general mmap of a disk file */
2570 int generic_file_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2572 struct address_space
*mapping
= file
->f_mapping
;
2574 if (!mapping
->a_ops
->readpage
)
2576 file_accessed(file
);
2577 vma
->vm_ops
= &generic_file_vm_ops
;
2582 * This is for filesystems which do not implement ->writepage.
2584 int generic_file_readonly_mmap(struct file
*file
, struct vm_area_struct
*vma
)
2586 if ((vma
->vm_flags
& VM_SHARED
) && (vma
->vm_flags
& VM_MAYWRITE
))
2588 return generic_file_mmap(file
, vma
);
2591 int generic_file_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2595 int generic_file_readonly_mmap(struct file
* file
, struct vm_area_struct
* vma
)
2599 #endif /* CONFIG_MMU */
2601 EXPORT_SYMBOL(generic_file_mmap
);
2602 EXPORT_SYMBOL(generic_file_readonly_mmap
);
2604 static struct page
*wait_on_page_read(struct page
*page
)
2606 if (!IS_ERR(page
)) {
2607 wait_on_page_locked(page
);
2608 if (!PageUptodate(page
)) {
2610 page
= ERR_PTR(-EIO
);
2616 static struct page
*do_read_cache_page(struct address_space
*mapping
,
2618 int (*filler
)(void *, struct page
*),
2625 page
= find_get_page(mapping
, index
);
2627 page
= __page_cache_alloc(gfp
| __GFP_COLD
);
2629 return ERR_PTR(-ENOMEM
);
2630 err
= add_to_page_cache_lru(page
, mapping
, index
, gfp
);
2631 if (unlikely(err
)) {
2635 /* Presumably ENOMEM for radix tree node */
2636 return ERR_PTR(err
);
2640 err
= filler(data
, page
);
2643 return ERR_PTR(err
);
2646 page
= wait_on_page_read(page
);
2651 if (PageUptodate(page
))
2655 * Page is not up to date and may be locked due one of the following
2656 * case a: Page is being filled and the page lock is held
2657 * case b: Read/write error clearing the page uptodate status
2658 * case c: Truncation in progress (page locked)
2659 * case d: Reclaim in progress
2661 * Case a, the page will be up to date when the page is unlocked.
2662 * There is no need to serialise on the page lock here as the page
2663 * is pinned so the lock gives no additional protection. Even if the
2664 * the page is truncated, the data is still valid if PageUptodate as
2665 * it's a race vs truncate race.
2666 * Case b, the page will not be up to date
2667 * Case c, the page may be truncated but in itself, the data may still
2668 * be valid after IO completes as it's a read vs truncate race. The
2669 * operation must restart if the page is not uptodate on unlock but
2670 * otherwise serialising on page lock to stabilise the mapping gives
2671 * no additional guarantees to the caller as the page lock is
2672 * released before return.
2673 * Case d, similar to truncation. If reclaim holds the page lock, it
2674 * will be a race with remove_mapping that determines if the mapping
2675 * is valid on unlock but otherwise the data is valid and there is
2676 * no need to serialise with page lock.
2678 * As the page lock gives no additional guarantee, we optimistically
2679 * wait on the page to be unlocked and check if it's up to date and
2680 * use the page if it is. Otherwise, the page lock is required to
2681 * distinguish between the different cases. The motivation is that we
2682 * avoid spurious serialisations and wakeups when multiple processes
2683 * wait on the same page for IO to complete.
2685 wait_on_page_locked(page
);
2686 if (PageUptodate(page
))
2689 /* Distinguish between all the cases under the safety of the lock */
2692 /* Case c or d, restart the operation */
2693 if (!page
->mapping
) {
2699 /* Someone else locked and filled the page in a very small window */
2700 if (PageUptodate(page
)) {
2707 mark_page_accessed(page
);
2712 * read_cache_page - read into page cache, fill it if needed
2713 * @mapping: the page's address_space
2714 * @index: the page index
2715 * @filler: function to perform the read
2716 * @data: first arg to filler(data, page) function, often left as NULL
2718 * Read into the page cache. If a page already exists, and PageUptodate() is
2719 * not set, try to fill the page and wait for it to become unlocked.
2721 * If the page does not get brought uptodate, return -EIO.
2723 struct page
*read_cache_page(struct address_space
*mapping
,
2725 int (*filler
)(void *, struct page
*),
2728 return do_read_cache_page(mapping
, index
, filler
, data
, mapping_gfp_mask(mapping
));
2730 EXPORT_SYMBOL(read_cache_page
);
2733 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2734 * @mapping: the page's address_space
2735 * @index: the page index
2736 * @gfp: the page allocator flags to use if allocating
2738 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2739 * any new page allocations done using the specified allocation flags.
2741 * If the page does not get brought uptodate, return -EIO.
2743 struct page
*read_cache_page_gfp(struct address_space
*mapping
,
2747 filler_t
*filler
= (filler_t
*)mapping
->a_ops
->readpage
;
2749 return do_read_cache_page(mapping
, index
, filler
, NULL
, gfp
);
2751 EXPORT_SYMBOL(read_cache_page_gfp
);
2754 * Performs necessary checks before doing a write
2756 * Can adjust writing position or amount of bytes to write.
2757 * Returns appropriate error code that caller should return or
2758 * zero in case that write should be allowed.
2760 inline ssize_t
generic_write_checks(struct kiocb
*iocb
, struct iov_iter
*from
)
2762 struct file
*file
= iocb
->ki_filp
;
2763 struct inode
*inode
= file
->f_mapping
->host
;
2764 unsigned long limit
= rlimit(RLIMIT_FSIZE
);
2767 if (!iov_iter_count(from
))
2770 /* FIXME: this is for backwards compatibility with 2.4 */
2771 if (iocb
->ki_flags
& IOCB_APPEND
)
2772 iocb
->ki_pos
= i_size_read(inode
);
2776 if ((iocb
->ki_flags
& IOCB_NOWAIT
) && !(iocb
->ki_flags
& IOCB_DIRECT
))
2779 if (limit
!= RLIM_INFINITY
) {
2780 if (iocb
->ki_pos
>= limit
) {
2781 send_sig(SIGXFSZ
, current
, 0);
2784 iov_iter_truncate(from
, limit
- (unsigned long)pos
);
2790 if (unlikely(pos
+ iov_iter_count(from
) > MAX_NON_LFS
&&
2791 !(file
->f_flags
& O_LARGEFILE
))) {
2792 if (pos
>= MAX_NON_LFS
)
2794 iov_iter_truncate(from
, MAX_NON_LFS
- (unsigned long)pos
);
2798 * Are we about to exceed the fs block limit ?
2800 * If we have written data it becomes a short write. If we have
2801 * exceeded without writing data we send a signal and return EFBIG.
2802 * Linus frestrict idea will clean these up nicely..
2804 if (unlikely(pos
>= inode
->i_sb
->s_maxbytes
))
2807 iov_iter_truncate(from
, inode
->i_sb
->s_maxbytes
- pos
);
2808 return iov_iter_count(from
);
2810 EXPORT_SYMBOL(generic_write_checks
);
2812 int pagecache_write_begin(struct file
*file
, struct address_space
*mapping
,
2813 loff_t pos
, unsigned len
, unsigned flags
,
2814 struct page
**pagep
, void **fsdata
)
2816 const struct address_space_operations
*aops
= mapping
->a_ops
;
2818 return aops
->write_begin(file
, mapping
, pos
, len
, flags
,
2821 EXPORT_SYMBOL(pagecache_write_begin
);
2823 int pagecache_write_end(struct file
*file
, struct address_space
*mapping
,
2824 loff_t pos
, unsigned len
, unsigned copied
,
2825 struct page
*page
, void *fsdata
)
2827 const struct address_space_operations
*aops
= mapping
->a_ops
;
2829 return aops
->write_end(file
, mapping
, pos
, len
, copied
, page
, fsdata
);
2831 EXPORT_SYMBOL(pagecache_write_end
);
2834 generic_file_direct_write(struct kiocb
*iocb
, struct iov_iter
*from
)
2836 struct file
*file
= iocb
->ki_filp
;
2837 struct address_space
*mapping
= file
->f_mapping
;
2838 struct inode
*inode
= mapping
->host
;
2839 loff_t pos
= iocb
->ki_pos
;
2844 write_len
= iov_iter_count(from
);
2845 end
= (pos
+ write_len
- 1) >> PAGE_SHIFT
;
2847 if (iocb
->ki_flags
& IOCB_NOWAIT
) {
2848 /* If there are pages to writeback, return */
2849 if (filemap_range_has_page(inode
->i_mapping
, pos
,
2850 pos
+ iov_iter_count(from
)))
2853 written
= filemap_write_and_wait_range(mapping
, pos
,
2854 pos
+ write_len
- 1);
2860 * After a write we want buffered reads to be sure to go to disk to get
2861 * the new data. We invalidate clean cached page from the region we're
2862 * about to write. We do this *before* the write so that we can return
2863 * without clobbering -EIOCBQUEUED from ->direct_IO().
2865 written
= invalidate_inode_pages2_range(mapping
,
2866 pos
>> PAGE_SHIFT
, end
);
2868 * If a page can not be invalidated, return 0 to fall back
2869 * to buffered write.
2872 if (written
== -EBUSY
)
2877 written
= mapping
->a_ops
->direct_IO(iocb
, from
);
2880 * Finally, try again to invalidate clean pages which might have been
2881 * cached by non-direct readahead, or faulted in by get_user_pages()
2882 * if the source of the write was an mmap'ed region of the file
2883 * we're writing. Either one is a pretty crazy thing to do,
2884 * so we don't support it 100%. If this invalidation
2885 * fails, tough, the write still worked...
2887 invalidate_inode_pages2_range(mapping
,
2888 pos
>> PAGE_SHIFT
, end
);
2892 write_len
-= written
;
2893 if (pos
> i_size_read(inode
) && !S_ISBLK(inode
->i_mode
)) {
2894 i_size_write(inode
, pos
);
2895 mark_inode_dirty(inode
);
2899 iov_iter_revert(from
, write_len
- iov_iter_count(from
));
2903 EXPORT_SYMBOL(generic_file_direct_write
);
2906 * Find or create a page at the given pagecache position. Return the locked
2907 * page. This function is specifically for buffered writes.
2909 struct page
*grab_cache_page_write_begin(struct address_space
*mapping
,
2910 pgoff_t index
, unsigned flags
)
2913 int fgp_flags
= FGP_LOCK
|FGP_WRITE
|FGP_CREAT
;
2915 if (flags
& AOP_FLAG_NOFS
)
2916 fgp_flags
|= FGP_NOFS
;
2918 page
= pagecache_get_page(mapping
, index
, fgp_flags
,
2919 mapping_gfp_mask(mapping
));
2921 wait_for_stable_page(page
);
2925 EXPORT_SYMBOL(grab_cache_page_write_begin
);
2927 ssize_t
generic_perform_write(struct file
*file
,
2928 struct iov_iter
*i
, loff_t pos
)
2930 struct address_space
*mapping
= file
->f_mapping
;
2931 const struct address_space_operations
*a_ops
= mapping
->a_ops
;
2933 ssize_t written
= 0;
2934 unsigned int flags
= 0;
2938 unsigned long offset
; /* Offset into pagecache page */
2939 unsigned long bytes
; /* Bytes to write to page */
2940 size_t copied
; /* Bytes copied from user */
2943 offset
= (pos
& (PAGE_SIZE
- 1));
2944 bytes
= min_t(unsigned long, PAGE_SIZE
- offset
,
2949 * Bring in the user page that we will copy from _first_.
2950 * Otherwise there's a nasty deadlock on copying from the
2951 * same page as we're writing to, without it being marked
2954 * Not only is this an optimisation, but it is also required
2955 * to check that the address is actually valid, when atomic
2956 * usercopies are used, below.
2958 if (unlikely(iov_iter_fault_in_readable(i
, bytes
))) {
2963 if (fatal_signal_pending(current
)) {
2968 status
= a_ops
->write_begin(file
, mapping
, pos
, bytes
, flags
,
2970 if (unlikely(status
< 0))
2973 if (mapping_writably_mapped(mapping
))
2974 flush_dcache_page(page
);
2976 copied
= iov_iter_copy_from_user_atomic(page
, i
, offset
, bytes
);
2977 flush_dcache_page(page
);
2979 status
= a_ops
->write_end(file
, mapping
, pos
, bytes
, copied
,
2981 if (unlikely(status
< 0))
2987 iov_iter_advance(i
, copied
);
2988 if (unlikely(copied
== 0)) {
2990 * If we were unable to copy any data at all, we must
2991 * fall back to a single segment length write.
2993 * If we didn't fallback here, we could livelock
2994 * because not all segments in the iov can be copied at
2995 * once without a pagefault.
2997 bytes
= min_t(unsigned long, PAGE_SIZE
- offset
,
2998 iov_iter_single_seg_count(i
));
3004 balance_dirty_pages_ratelimited(mapping
);
3005 } while (iov_iter_count(i
));
3007 return written
? written
: status
;
3009 EXPORT_SYMBOL(generic_perform_write
);
3012 * __generic_file_write_iter - write data to a file
3013 * @iocb: IO state structure (file, offset, etc.)
3014 * @from: iov_iter with data to write
3016 * This function does all the work needed for actually writing data to a
3017 * file. It does all basic checks, removes SUID from the file, updates
3018 * modification times and calls proper subroutines depending on whether we
3019 * do direct IO or a standard buffered write.
3021 * It expects i_mutex to be grabbed unless we work on a block device or similar
3022 * object which does not need locking at all.
3024 * This function does *not* take care of syncing data in case of O_SYNC write.
3025 * A caller has to handle it. This is mainly due to the fact that we want to
3026 * avoid syncing under i_mutex.
3028 ssize_t
__generic_file_write_iter(struct kiocb
*iocb
, struct iov_iter
*from
)
3030 struct file
*file
= iocb
->ki_filp
;
3031 struct address_space
* mapping
= file
->f_mapping
;
3032 struct inode
*inode
= mapping
->host
;
3033 ssize_t written
= 0;
3037 /* We can write back this queue in page reclaim */
3038 current
->backing_dev_info
= inode_to_bdi(inode
);
3039 err
= file_remove_privs(file
);
3043 err
= file_update_time(file
);
3047 if (iocb
->ki_flags
& IOCB_DIRECT
) {
3048 loff_t pos
, endbyte
;
3050 written
= generic_file_direct_write(iocb
, from
);
3052 * If the write stopped short of completing, fall back to
3053 * buffered writes. Some filesystems do this for writes to
3054 * holes, for example. For DAX files, a buffered write will
3055 * not succeed (even if it did, DAX does not handle dirty
3056 * page-cache pages correctly).
3058 if (written
< 0 || !iov_iter_count(from
) || IS_DAX(inode
))
3061 status
= generic_perform_write(file
, from
, pos
= iocb
->ki_pos
);
3063 * If generic_perform_write() returned a synchronous error
3064 * then we want to return the number of bytes which were
3065 * direct-written, or the error code if that was zero. Note
3066 * that this differs from normal direct-io semantics, which
3067 * will return -EFOO even if some bytes were written.
3069 if (unlikely(status
< 0)) {
3074 * We need to ensure that the page cache pages are written to
3075 * disk and invalidated to preserve the expected O_DIRECT
3078 endbyte
= pos
+ status
- 1;
3079 err
= filemap_write_and_wait_range(mapping
, pos
, endbyte
);
3081 iocb
->ki_pos
= endbyte
+ 1;
3083 invalidate_mapping_pages(mapping
,
3085 endbyte
>> PAGE_SHIFT
);
3088 * We don't know how much we wrote, so just return
3089 * the number of bytes which were direct-written
3093 written
= generic_perform_write(file
, from
, iocb
->ki_pos
);
3094 if (likely(written
> 0))
3095 iocb
->ki_pos
+= written
;
3098 current
->backing_dev_info
= NULL
;
3099 return written
? written
: err
;
3101 EXPORT_SYMBOL(__generic_file_write_iter
);
3104 * generic_file_write_iter - write data to a file
3105 * @iocb: IO state structure
3106 * @from: iov_iter with data to write
3108 * This is a wrapper around __generic_file_write_iter() to be used by most
3109 * filesystems. It takes care of syncing the file in case of O_SYNC file
3110 * and acquires i_mutex as needed.
3112 ssize_t
generic_file_write_iter(struct kiocb
*iocb
, struct iov_iter
*from
)
3114 struct file
*file
= iocb
->ki_filp
;
3115 struct inode
*inode
= file
->f_mapping
->host
;
3119 ret
= generic_write_checks(iocb
, from
);
3121 ret
= __generic_file_write_iter(iocb
, from
);
3122 inode_unlock(inode
);
3125 ret
= generic_write_sync(iocb
, ret
);
3128 EXPORT_SYMBOL(generic_file_write_iter
);
3131 * try_to_release_page() - release old fs-specific metadata on a page
3133 * @page: the page which the kernel is trying to free
3134 * @gfp_mask: memory allocation flags (and I/O mode)
3136 * The address_space is to try to release any data against the page
3137 * (presumably at page->private). If the release was successful, return '1'.
3138 * Otherwise return zero.
3140 * This may also be called if PG_fscache is set on a page, indicating that the
3141 * page is known to the local caching routines.
3143 * The @gfp_mask argument specifies whether I/O may be performed to release
3144 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3147 int try_to_release_page(struct page
*page
, gfp_t gfp_mask
)
3149 struct address_space
* const mapping
= page
->mapping
;
3151 BUG_ON(!PageLocked(page
));
3152 if (PageWriteback(page
))
3155 if (mapping
&& mapping
->a_ops
->releasepage
)
3156 return mapping
->a_ops
->releasepage(page
, gfp_mask
);
3157 return try_to_free_buffers(page
);
3160 EXPORT_SYMBOL(try_to_release_page
);