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--;
136 __radix_tree_replace(&mapping->page_tree, node, slot, page,
137 workingset_update_node, mapping);
142 static void page_cache_tree_delete(struct address_space *mapping,
143 struct page *page, void *shadow)
147 /* hugetlb pages are represented by one entry in the radix tree */
148 nr = PageHuge(page) ? 1 : hpage_nr_pages(page);
150 VM_BUG_ON_PAGE(!PageLocked(page), page);
151 VM_BUG_ON_PAGE(PageTail(page), page);
152 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
154 for (i = 0; i < nr; i++) {
155 struct radix_tree_node *node;
158 __radix_tree_lookup(&mapping->page_tree, page->index + i,
161 VM_BUG_ON_PAGE(!node && nr != 1, page);
163 radix_tree_clear_tags(&mapping->page_tree, node, slot);
164 __radix_tree_replace(&mapping->page_tree, node, slot, shadow,
165 workingset_update_node, mapping);
169 mapping->nrexceptional += nr;
171 * Make sure the nrexceptional update is committed before
172 * the nrpages update so that final truncate racing
173 * with reclaim does not see both counters 0 at the
174 * same time and miss a shadow entry.
178 mapping->nrpages -= nr;
182 * Delete a page from the page cache and free it. Caller has to make
183 * sure the page is locked and that nobody else uses it - or that usage
184 * is safe. The caller must hold the mapping's tree_lock.
186 void __delete_from_page_cache(struct page *page, void *shadow)
188 struct address_space *mapping = page->mapping;
189 int nr = hpage_nr_pages(page);
191 trace_mm_filemap_delete_from_page_cache(page);
193 * if we're uptodate, flush out into the cleancache, otherwise
194 * invalidate any existing cleancache entries. We can't leave
195 * stale data around in the cleancache once our page is gone
197 if (PageUptodate(page) && PageMappedToDisk(page))
198 cleancache_put_page(page);
200 cleancache_invalidate_page(mapping, page);
202 VM_BUG_ON_PAGE(PageTail(page), page);
203 VM_BUG_ON_PAGE(page_mapped(page), page);
204 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
207 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
208 current->comm, page_to_pfn(page));
209 dump_page(page, "still mapped when deleted");
211 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
213 mapcount = page_mapcount(page);
214 if (mapping_exiting(mapping) &&
215 page_count(page) >= mapcount + 2) {
217 * All vmas have already been torn down, so it's
218 * a good bet that actually the page is unmapped,
219 * and we'd prefer not to leak it: if we're wrong,
220 * some other bad page check should catch it later.
222 page_mapcount_reset(page);
223 page_ref_sub(page, mapcount);
227 page_cache_tree_delete(mapping, page, shadow);
229 page->mapping = NULL;
230 /* Leave page->index set: truncation lookup relies upon it */
232 /* hugetlb pages do not participate in page cache accounting. */
236 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, -nr);
237 if (PageSwapBacked(page)) {
238 __mod_node_page_state(page_pgdat(page), NR_SHMEM, -nr);
239 if (PageTransHuge(page))
240 __dec_node_page_state(page, NR_SHMEM_THPS);
242 VM_BUG_ON_PAGE(PageTransHuge(page), page);
246 * At this point page must be either written or cleaned by truncate.
247 * Dirty page here signals a bug and loss of unwritten data.
249 * This fixes dirty accounting after removing the page entirely but
250 * leaves PageDirty set: it has no effect for truncated page and
251 * anyway will be cleared before returning page into buddy allocator.
253 if (WARN_ON_ONCE(PageDirty(page)))
254 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
257 static void page_cache_free_page(struct address_space *mapping,
260 void (*freepage)(struct page *);
262 freepage = mapping->a_ops->freepage;
266 if (PageTransHuge(page) && !PageHuge(page)) {
267 page_ref_sub(page, HPAGE_PMD_NR);
268 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
275 * delete_from_page_cache - delete page from page cache
276 * @page: the page which the kernel is trying to remove from page cache
278 * This must be called only on pages that have been verified to be in the page
279 * cache and locked. It will never put the page into the free list, the caller
280 * has a reference on the page.
282 void delete_from_page_cache(struct page *page)
284 struct address_space *mapping = page_mapping(page);
287 BUG_ON(!PageLocked(page));
288 spin_lock_irqsave(&mapping->tree_lock, flags);
289 __delete_from_page_cache(page, NULL);
290 spin_unlock_irqrestore(&mapping->tree_lock, flags);
292 page_cache_free_page(mapping, page);
294 EXPORT_SYMBOL(delete_from_page_cache);
296 int filemap_check_errors(struct address_space *mapping)
299 /* Check for outstanding write errors */
300 if (test_bit(AS_ENOSPC, &mapping->flags) &&
301 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
303 if (test_bit(AS_EIO, &mapping->flags) &&
304 test_and_clear_bit(AS_EIO, &mapping->flags))
308 EXPORT_SYMBOL(filemap_check_errors);
310 static int filemap_check_and_keep_errors(struct address_space *mapping)
312 /* Check for outstanding write errors */
313 if (test_bit(AS_EIO, &mapping->flags))
315 if (test_bit(AS_ENOSPC, &mapping->flags))
321 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
322 * @mapping: address space structure to write
323 * @start: offset in bytes where the range starts
324 * @end: offset in bytes where the range ends (inclusive)
325 * @sync_mode: enable synchronous operation
327 * Start writeback against all of a mapping's dirty pages that lie
328 * within the byte offsets <start, end> inclusive.
330 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
331 * opposed to a regular memory cleansing writeback. The difference between
332 * these two operations is that if a dirty page/buffer is encountered, it must
333 * be waited upon, and not just skipped over.
335 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
336 loff_t end, int sync_mode)
339 struct writeback_control wbc = {
340 .sync_mode = sync_mode,
341 .nr_to_write = LONG_MAX,
342 .range_start = start,
346 if (!mapping_cap_writeback_dirty(mapping))
349 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
350 ret = do_writepages(mapping, &wbc);
351 wbc_detach_inode(&wbc);
355 static inline int __filemap_fdatawrite(struct address_space *mapping,
358 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
361 int filemap_fdatawrite(struct address_space *mapping)
363 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
365 EXPORT_SYMBOL(filemap_fdatawrite);
367 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
370 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
372 EXPORT_SYMBOL(filemap_fdatawrite_range);
375 * filemap_flush - mostly a non-blocking flush
376 * @mapping: target address_space
378 * This is a mostly non-blocking flush. Not suitable for data-integrity
379 * purposes - I/O may not be started against all dirty pages.
381 int filemap_flush(struct address_space *mapping)
383 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
385 EXPORT_SYMBOL(filemap_flush);
388 * filemap_range_has_page - check if a page exists in range.
389 * @mapping: address space within which to check
390 * @start_byte: offset in bytes where the range starts
391 * @end_byte: offset in bytes where the range ends (inclusive)
393 * Find at least one page in the range supplied, usually used to check if
394 * direct writing in this range will trigger a writeback.
396 bool filemap_range_has_page(struct address_space *mapping,
397 loff_t start_byte, loff_t end_byte)
399 pgoff_t index = start_byte >> PAGE_SHIFT;
400 pgoff_t end = end_byte >> PAGE_SHIFT;
403 if (end_byte < start_byte)
406 if (mapping->nrpages == 0)
409 if (!find_get_pages_range(mapping, &index, end, 1, &page))
414 EXPORT_SYMBOL(filemap_range_has_page);
416 static void __filemap_fdatawait_range(struct address_space *mapping,
417 loff_t start_byte, loff_t end_byte)
419 pgoff_t index = start_byte >> PAGE_SHIFT;
420 pgoff_t end = end_byte >> PAGE_SHIFT;
424 if (end_byte < start_byte)
427 pagevec_init(&pvec, 0);
428 while (index <= end) {
431 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
432 end, PAGECACHE_TAG_WRITEBACK);
436 for (i = 0; i < nr_pages; i++) {
437 struct page *page = pvec.pages[i];
439 wait_on_page_writeback(page);
440 ClearPageError(page);
442 pagevec_release(&pvec);
448 * filemap_fdatawait_range - wait for writeback to complete
449 * @mapping: address space structure to wait for
450 * @start_byte: offset in bytes where the range starts
451 * @end_byte: offset in bytes where the range ends (inclusive)
453 * Walk the list of under-writeback pages of the given address space
454 * in the given range and wait for all of them. Check error status of
455 * the address space and return it.
457 * Since the error status of the address space is cleared by this function,
458 * callers are responsible for checking the return value and handling and/or
459 * reporting the error.
461 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
464 __filemap_fdatawait_range(mapping, start_byte, end_byte);
465 return filemap_check_errors(mapping);
467 EXPORT_SYMBOL(filemap_fdatawait_range);
470 * file_fdatawait_range - wait for writeback to complete
471 * @file: file pointing to address space structure to wait for
472 * @start_byte: offset in bytes where the range starts
473 * @end_byte: offset in bytes where the range ends (inclusive)
475 * Walk the list of under-writeback pages of the address space that file
476 * refers to, in the given range and wait for all of them. Check error
477 * status of the address space vs. the file->f_wb_err cursor and return it.
479 * Since the error status of the file is advanced by this function,
480 * callers are responsible for checking the return value and handling and/or
481 * reporting the error.
483 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
485 struct address_space *mapping = file->f_mapping;
487 __filemap_fdatawait_range(mapping, start_byte, end_byte);
488 return file_check_and_advance_wb_err(file);
490 EXPORT_SYMBOL(file_fdatawait_range);
493 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
494 * @mapping: address space structure to wait for
496 * Walk the list of under-writeback pages of the given address space
497 * and wait for all of them. Unlike filemap_fdatawait(), this function
498 * does not clear error status of the address space.
500 * Use this function if callers don't handle errors themselves. Expected
501 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
504 int filemap_fdatawait_keep_errors(struct address_space *mapping)
506 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
507 return filemap_check_and_keep_errors(mapping);
509 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
511 static bool mapping_needs_writeback(struct address_space *mapping)
513 return (!dax_mapping(mapping) && mapping->nrpages) ||
514 (dax_mapping(mapping) && mapping->nrexceptional);
517 int filemap_write_and_wait(struct address_space *mapping)
521 if (mapping_needs_writeback(mapping)) {
522 err = filemap_fdatawrite(mapping);
524 * Even if the above returned error, the pages may be
525 * written partially (e.g. -ENOSPC), so we wait for it.
526 * But the -EIO is special case, it may indicate the worst
527 * thing (e.g. bug) happened, so we avoid waiting for it.
530 int err2 = filemap_fdatawait(mapping);
534 /* Clear any previously stored errors */
535 filemap_check_errors(mapping);
538 err = filemap_check_errors(mapping);
542 EXPORT_SYMBOL(filemap_write_and_wait);
545 * filemap_write_and_wait_range - write out & wait on a file range
546 * @mapping: the address_space for the pages
547 * @lstart: offset in bytes where the range starts
548 * @lend: offset in bytes where the range ends (inclusive)
550 * Write out and wait upon file offsets lstart->lend, inclusive.
552 * Note that @lend is inclusive (describes the last byte to be written) so
553 * that this function can be used to write to the very end-of-file (end = -1).
555 int filemap_write_and_wait_range(struct address_space *mapping,
556 loff_t lstart, loff_t lend)
560 if (mapping_needs_writeback(mapping)) {
561 err = __filemap_fdatawrite_range(mapping, lstart, lend,
563 /* See comment of filemap_write_and_wait() */
565 int err2 = filemap_fdatawait_range(mapping,
570 /* Clear any previously stored errors */
571 filemap_check_errors(mapping);
574 err = filemap_check_errors(mapping);
578 EXPORT_SYMBOL(filemap_write_and_wait_range);
580 void __filemap_set_wb_err(struct address_space *mapping, int err)
582 errseq_t eseq = errseq_set(&mapping->wb_err, err);
584 trace_filemap_set_wb_err(mapping, eseq);
586 EXPORT_SYMBOL(__filemap_set_wb_err);
589 * file_check_and_advance_wb_err - report wb error (if any) that was previously
590 * and advance wb_err to current one
591 * @file: struct file on which the error is being reported
593 * When userland calls fsync (or something like nfsd does the equivalent), we
594 * want to report any writeback errors that occurred since the last fsync (or
595 * since the file was opened if there haven't been any).
597 * Grab the wb_err from the mapping. If it matches what we have in the file,
598 * then just quickly return 0. The file is all caught up.
600 * If it doesn't match, then take the mapping value, set the "seen" flag in
601 * it and try to swap it into place. If it works, or another task beat us
602 * to it with the new value, then update the f_wb_err and return the error
603 * portion. The error at this point must be reported via proper channels
604 * (a'la fsync, or NFS COMMIT operation, etc.).
606 * While we handle mapping->wb_err with atomic operations, the f_wb_err
607 * value is protected by the f_lock since we must ensure that it reflects
608 * the latest value swapped in for this file descriptor.
610 int file_check_and_advance_wb_err(struct file *file)
613 errseq_t old = READ_ONCE(file->f_wb_err);
614 struct address_space *mapping = file->f_mapping;
616 /* Locklessly handle the common case where nothing has changed */
617 if (errseq_check(&mapping->wb_err, old)) {
618 /* Something changed, must use slow path */
619 spin_lock(&file->f_lock);
620 old = file->f_wb_err;
621 err = errseq_check_and_advance(&mapping->wb_err,
623 trace_file_check_and_advance_wb_err(file, old);
624 spin_unlock(&file->f_lock);
628 * We're mostly using this function as a drop in replacement for
629 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
630 * that the legacy code would have had on these flags.
632 clear_bit(AS_EIO, &mapping->flags);
633 clear_bit(AS_ENOSPC, &mapping->flags);
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 (mapping_needs_writeback(mapping)) {
658 err = __filemap_fdatawrite_range(mapping, lstart, lend,
660 /* See comment of filemap_write_and_wait() */
662 __filemap_fdatawait_range(mapping, lstart, lend);
664 err2 = file_check_and_advance_wb_err(file);
669 EXPORT_SYMBOL(file_write_and_wait_range);
672 * replace_page_cache_page - replace a pagecache page with a new one
673 * @old: page to be replaced
674 * @new: page to replace with
675 * @gfp_mask: allocation mode
677 * This function replaces a page in the pagecache with a new one. On
678 * success it acquires the pagecache reference for the new page and
679 * drops it for the old page. Both the old and new pages must be
680 * locked. This function does not add the new page to the LRU, the
681 * caller must do that.
683 * The remove + add is atomic. The only way this function can fail is
684 * memory allocation failure.
686 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
690 VM_BUG_ON_PAGE(!PageLocked(old), old);
691 VM_BUG_ON_PAGE(!PageLocked(new), new);
692 VM_BUG_ON_PAGE(new->mapping, new);
694 error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
696 struct address_space *mapping = old->mapping;
697 void (*freepage)(struct page *);
700 pgoff_t offset = old->index;
701 freepage = mapping->a_ops->freepage;
704 new->mapping = mapping;
707 spin_lock_irqsave(&mapping->tree_lock, flags);
708 __delete_from_page_cache(old, NULL);
709 error = page_cache_tree_insert(mapping, new, NULL);
713 * hugetlb pages do not participate in page cache accounting.
716 __inc_node_page_state(new, NR_FILE_PAGES);
717 if (PageSwapBacked(new))
718 __inc_node_page_state(new, NR_SHMEM);
719 spin_unlock_irqrestore(&mapping->tree_lock, flags);
720 mem_cgroup_migrate(old, new);
721 radix_tree_preload_end();
729 EXPORT_SYMBOL_GPL(replace_page_cache_page);
731 static int __add_to_page_cache_locked(struct page *page,
732 struct address_space *mapping,
733 pgoff_t offset, gfp_t gfp_mask,
736 int huge = PageHuge(page);
737 struct mem_cgroup *memcg;
740 VM_BUG_ON_PAGE(!PageLocked(page), page);
741 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
744 error = mem_cgroup_try_charge(page, current->mm,
745 gfp_mask, &memcg, false);
750 error = radix_tree_maybe_preload(gfp_mask & ~__GFP_HIGHMEM);
753 mem_cgroup_cancel_charge(page, memcg, false);
758 page->mapping = mapping;
759 page->index = offset;
761 spin_lock_irq(&mapping->tree_lock);
762 error = page_cache_tree_insert(mapping, page, shadowp);
763 radix_tree_preload_end();
767 /* hugetlb pages do not participate in page cache accounting. */
769 __inc_node_page_state(page, NR_FILE_PAGES);
770 spin_unlock_irq(&mapping->tree_lock);
772 mem_cgroup_commit_charge(page, memcg, false, false);
773 trace_mm_filemap_add_to_page_cache(page);
776 page->mapping = NULL;
777 /* Leave page->index set: truncation relies upon it */
778 spin_unlock_irq(&mapping->tree_lock);
780 mem_cgroup_cancel_charge(page, memcg, false);
786 * add_to_page_cache_locked - add a locked page to the pagecache
788 * @mapping: the page's address_space
789 * @offset: page index
790 * @gfp_mask: page allocation mode
792 * This function is used to add a page to the pagecache. It must be locked.
793 * This function does not add the page to the LRU. The caller must do that.
795 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
796 pgoff_t offset, gfp_t gfp_mask)
798 return __add_to_page_cache_locked(page, mapping, offset,
801 EXPORT_SYMBOL(add_to_page_cache_locked);
803 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
804 pgoff_t offset, gfp_t gfp_mask)
809 __SetPageLocked(page);
810 ret = __add_to_page_cache_locked(page, mapping, offset,
813 __ClearPageLocked(page);
816 * The page might have been evicted from cache only
817 * recently, in which case it should be activated like
818 * any other repeatedly accessed page.
819 * The exception is pages getting rewritten; evicting other
820 * data from the working set, only to cache data that will
821 * get overwritten with something else, is a waste of memory.
823 if (!(gfp_mask & __GFP_WRITE) &&
824 shadow && workingset_refault(shadow)) {
826 workingset_activation(page);
828 ClearPageActive(page);
833 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
836 struct page *__page_cache_alloc(gfp_t gfp)
841 if (cpuset_do_page_mem_spread()) {
842 unsigned int cpuset_mems_cookie;
844 cpuset_mems_cookie = read_mems_allowed_begin();
845 n = cpuset_mem_spread_node();
846 page = __alloc_pages_node(n, gfp, 0);
847 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
851 return alloc_pages(gfp, 0);
853 EXPORT_SYMBOL(__page_cache_alloc);
857 * In order to wait for pages to become available there must be
858 * waitqueues associated with pages. By using a hash table of
859 * waitqueues where the bucket discipline is to maintain all
860 * waiters on the same queue and wake all when any of the pages
861 * become available, and for the woken contexts to check to be
862 * sure the appropriate page became available, this saves space
863 * at a cost of "thundering herd" phenomena during rare hash
866 #define PAGE_WAIT_TABLE_BITS 8
867 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
868 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
870 static wait_queue_head_t *page_waitqueue(struct page *page)
872 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
875 void __init pagecache_init(void)
879 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
880 init_waitqueue_head(&page_wait_table[i]);
882 page_writeback_init();
885 /* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
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)
911 /* Stop walking if it's locked */
912 if (test_bit(key->bit_nr, &key->page->flags))
915 return autoremove_wake_function(wait, mode, sync, key);
918 static void wake_up_page_bit(struct page *page, int bit_nr)
920 wait_queue_head_t *q = page_waitqueue(page);
921 struct wait_page_key key;
923 wait_queue_entry_t bookmark;
930 bookmark.private = NULL;
931 bookmark.func = NULL;
932 INIT_LIST_HEAD(&bookmark.entry);
934 spin_lock_irqsave(&q->lock, flags);
935 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
937 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
939 * Take a breather from holding the lock,
940 * allow pages that finish wake up asynchronously
941 * to acquire the lock and remove themselves
944 spin_unlock_irqrestore(&q->lock, flags);
946 spin_lock_irqsave(&q->lock, flags);
947 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
951 * It is possible for other pages to have collided on the waitqueue
952 * hash, so in that case check for a page match. That prevents a long-
955 * It is still possible to miss a case here, when we woke page waiters
956 * and removed them from the waitqueue, but there are still other
959 if (!waitqueue_active(q) || !key.page_match) {
960 ClearPageWaiters(page);
962 * It's possible to miss clearing Waiters here, when we woke
963 * our page waiters, but the hashed waitqueue has waiters for
966 * That's okay, it's a rare case. The next waker will clear it.
969 spin_unlock_irqrestore(&q->lock, flags);
972 static void wake_up_page(struct page *page, int bit)
974 if (!PageWaiters(page))
976 wake_up_page_bit(page, bit);
979 static inline int wait_on_page_bit_common(wait_queue_head_t *q,
980 struct page *page, int bit_nr, int state, bool lock)
982 struct wait_page_queue wait_page;
983 wait_queue_entry_t *wait = &wait_page.wait;
987 wait->flags = lock ? WQ_FLAG_EXCLUSIVE : 0;
988 wait->func = wake_page_function;
989 wait_page.page = page;
990 wait_page.bit_nr = bit_nr;
993 spin_lock_irq(&q->lock);
995 if (likely(list_empty(&wait->entry))) {
996 __add_wait_queue_entry_tail(q, wait);
997 SetPageWaiters(page);
1000 set_current_state(state);
1002 spin_unlock_irq(&q->lock);
1004 if (likely(test_bit(bit_nr, &page->flags))) {
1009 if (!test_and_set_bit_lock(bit_nr, &page->flags))
1012 if (!test_bit(bit_nr, &page->flags))
1016 if (unlikely(signal_pending_state(state, current))) {
1022 finish_wait(q, wait);
1025 * A signal could leave PageWaiters set. Clearing it here if
1026 * !waitqueue_active would be possible (by open-coding finish_wait),
1027 * but still fail to catch it in the case of wait hash collision. We
1028 * already can fail to clear wait hash collision cases, so don't
1029 * bother with signals either.
1035 void wait_on_page_bit(struct page *page, int bit_nr)
1037 wait_queue_head_t *q = page_waitqueue(page);
1038 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, false);
1040 EXPORT_SYMBOL(wait_on_page_bit);
1042 int wait_on_page_bit_killable(struct page *page, int bit_nr)
1044 wait_queue_head_t *q = page_waitqueue(page);
1045 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, false);
1049 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1050 * @page: Page defining the wait queue of interest
1051 * @waiter: Waiter to add to the queue
1053 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1055 void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1057 wait_queue_head_t *q = page_waitqueue(page);
1058 unsigned long flags;
1060 spin_lock_irqsave(&q->lock, flags);
1061 __add_wait_queue_entry_tail(q, waiter);
1062 SetPageWaiters(page);
1063 spin_unlock_irqrestore(&q->lock, flags);
1065 EXPORT_SYMBOL_GPL(add_page_wait_queue);
1067 #ifndef clear_bit_unlock_is_negative_byte
1070 * PG_waiters is the high bit in the same byte as PG_lock.
1072 * On x86 (and on many other architectures), we can clear PG_lock and
1073 * test the sign bit at the same time. But if the architecture does
1074 * not support that special operation, we just do this all by hand
1077 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1078 * being cleared, but a memory barrier should be unneccssary since it is
1079 * in the same byte as PG_locked.
1081 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1083 clear_bit_unlock(nr, mem);
1084 /* smp_mb__after_atomic(); */
1085 return test_bit(PG_waiters, mem);
1091 * unlock_page - unlock a locked page
1094 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1095 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1096 * mechanism between PageLocked pages and PageWriteback pages is shared.
1097 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1099 * Note that this depends on PG_waiters being the sign bit in the byte
1100 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1101 * clear the PG_locked bit and test PG_waiters at the same time fairly
1102 * portably (architectures that do LL/SC can test any bit, while x86 can
1103 * test the sign bit).
1105 void unlock_page(struct page *page)
1107 BUILD_BUG_ON(PG_waiters != 7);
1108 page = compound_head(page);
1109 VM_BUG_ON_PAGE(!PageLocked(page), page);
1110 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1111 wake_up_page_bit(page, PG_locked);
1113 EXPORT_SYMBOL(unlock_page);
1116 * end_page_writeback - end writeback against a page
1119 void end_page_writeback(struct page *page)
1122 * TestClearPageReclaim could be used here but it is an atomic
1123 * operation and overkill in this particular case. Failing to
1124 * shuffle a page marked for immediate reclaim is too mild to
1125 * justify taking an atomic operation penalty at the end of
1126 * ever page writeback.
1128 if (PageReclaim(page)) {
1129 ClearPageReclaim(page);
1130 rotate_reclaimable_page(page);
1133 if (!test_clear_page_writeback(page))
1136 smp_mb__after_atomic();
1137 wake_up_page(page, PG_writeback);
1139 EXPORT_SYMBOL(end_page_writeback);
1142 * After completing I/O on a page, call this routine to update the page
1143 * flags appropriately
1145 void page_endio(struct page *page, bool is_write, int err)
1149 SetPageUptodate(page);
1151 ClearPageUptodate(page);
1157 struct address_space *mapping;
1160 mapping = page_mapping(page);
1162 mapping_set_error(mapping, err);
1164 end_page_writeback(page);
1167 EXPORT_SYMBOL_GPL(page_endio);
1170 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1171 * @__page: the page to lock
1173 void __lock_page(struct page *__page)
1175 struct page *page = compound_head(__page);
1176 wait_queue_head_t *q = page_waitqueue(page);
1177 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, true);
1179 EXPORT_SYMBOL(__lock_page);
1181 int __lock_page_killable(struct page *__page)
1183 struct page *page = compound_head(__page);
1184 wait_queue_head_t *q = page_waitqueue(page);
1185 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE, true);
1187 EXPORT_SYMBOL_GPL(__lock_page_killable);
1191 * 1 - page is locked; mmap_sem is still held.
1192 * 0 - page is not locked.
1193 * mmap_sem has been released (up_read()), unless flags had both
1194 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1195 * which case mmap_sem is still held.
1197 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1198 * with the page locked and the mmap_sem unperturbed.
1200 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1203 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1205 * CAUTION! In this case, mmap_sem is not released
1206 * even though return 0.
1208 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1211 up_read(&mm->mmap_sem);
1212 if (flags & FAULT_FLAG_KILLABLE)
1213 wait_on_page_locked_killable(page);
1215 wait_on_page_locked(page);
1218 if (flags & FAULT_FLAG_KILLABLE) {
1221 ret = __lock_page_killable(page);
1223 up_read(&mm->mmap_sem);
1233 * page_cache_next_hole - find the next hole (not-present entry)
1236 * @max_scan: maximum range to search
1238 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
1239 * lowest indexed hole.
1241 * Returns: the index of the hole if found, otherwise returns an index
1242 * outside of the set specified (in which case 'return - index >=
1243 * max_scan' will be true). In rare cases of index wrap-around, 0 will
1246 * page_cache_next_hole may be called under rcu_read_lock. However,
1247 * like radix_tree_gang_lookup, this will not atomically search a
1248 * snapshot of the tree at a single point in time. For example, if a
1249 * hole is created at index 5, then subsequently a hole is created at
1250 * index 10, page_cache_next_hole covering both indexes may return 10
1251 * if called under rcu_read_lock.
1253 pgoff_t page_cache_next_hole(struct address_space *mapping,
1254 pgoff_t index, unsigned long max_scan)
1258 for (i = 0; i < max_scan; i++) {
1261 page = radix_tree_lookup(&mapping->page_tree, index);
1262 if (!page || radix_tree_exceptional_entry(page))
1271 EXPORT_SYMBOL(page_cache_next_hole);
1274 * page_cache_prev_hole - find the prev hole (not-present entry)
1277 * @max_scan: maximum range to search
1279 * Search backwards in the range [max(index-max_scan+1, 0), index] for
1282 * Returns: the index of the hole if found, otherwise returns an index
1283 * outside of the set specified (in which case 'index - return >=
1284 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
1287 * page_cache_prev_hole may be called under rcu_read_lock. However,
1288 * like radix_tree_gang_lookup, this will not atomically search a
1289 * snapshot of the tree at a single point in time. For example, if a
1290 * hole is created at index 10, then subsequently a hole is created at
1291 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1292 * called under rcu_read_lock.
1294 pgoff_t page_cache_prev_hole(struct address_space *mapping,
1295 pgoff_t index, unsigned long max_scan)
1299 for (i = 0; i < max_scan; i++) {
1302 page = radix_tree_lookup(&mapping->page_tree, index);
1303 if (!page || radix_tree_exceptional_entry(page))
1306 if (index == ULONG_MAX)
1312 EXPORT_SYMBOL(page_cache_prev_hole);
1315 * find_get_entry - find and get a page cache entry
1316 * @mapping: the address_space to search
1317 * @offset: the page cache index
1319 * Looks up the page cache slot at @mapping & @offset. If there is a
1320 * page cache page, it is returned with an increased refcount.
1322 * If the slot holds a shadow entry of a previously evicted page, or a
1323 * swap entry from shmem/tmpfs, it is returned.
1325 * Otherwise, %NULL is returned.
1327 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1330 struct page *head, *page;
1335 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
1337 page = radix_tree_deref_slot(pagep);
1338 if (unlikely(!page))
1340 if (radix_tree_exception(page)) {
1341 if (radix_tree_deref_retry(page))
1344 * A shadow entry of a recently evicted page,
1345 * or a swap entry from shmem/tmpfs. Return
1346 * it without attempting to raise page count.
1351 head = compound_head(page);
1352 if (!page_cache_get_speculative(head))
1355 /* The page was split under us? */
1356 if (compound_head(page) != head) {
1362 * Has the page moved?
1363 * This is part of the lockless pagecache protocol. See
1364 * include/linux/pagemap.h for details.
1366 if (unlikely(page != *pagep)) {
1376 EXPORT_SYMBOL(find_get_entry);
1379 * find_lock_entry - locate, pin and lock a page cache entry
1380 * @mapping: the address_space to search
1381 * @offset: the page cache index
1383 * Looks up the page cache slot at @mapping & @offset. If there is a
1384 * page cache page, it is returned locked and with an increased
1387 * If the slot holds a shadow entry of a previously evicted page, or a
1388 * swap entry from shmem/tmpfs, it is returned.
1390 * Otherwise, %NULL is returned.
1392 * find_lock_entry() may sleep.
1394 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1399 page = find_get_entry(mapping, offset);
1400 if (page && !radix_tree_exception(page)) {
1402 /* Has the page been truncated? */
1403 if (unlikely(page_mapping(page) != mapping)) {
1408 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
1412 EXPORT_SYMBOL(find_lock_entry);
1415 * pagecache_get_page - find and get a page reference
1416 * @mapping: the address_space to search
1417 * @offset: the page index
1418 * @fgp_flags: PCG flags
1419 * @gfp_mask: gfp mask to use for the page cache data page allocation
1421 * Looks up the page cache slot at @mapping & @offset.
1423 * PCG flags modify how the page is returned.
1425 * @fgp_flags can be:
1427 * - FGP_ACCESSED: the page will be marked accessed
1428 * - FGP_LOCK: Page is return locked
1429 * - FGP_CREAT: If page is not present then a new page is allocated using
1430 * @gfp_mask and added to the page cache and the VM's LRU
1431 * list. The page is returned locked and with an increased
1432 * refcount. Otherwise, NULL is returned.
1434 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1435 * if the GFP flags specified for FGP_CREAT are atomic.
1437 * If there is a page cache page, it is returned with an increased refcount.
1439 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1440 int fgp_flags, gfp_t gfp_mask)
1445 page = find_get_entry(mapping, offset);
1446 if (radix_tree_exceptional_entry(page))
1451 if (fgp_flags & FGP_LOCK) {
1452 if (fgp_flags & FGP_NOWAIT) {
1453 if (!trylock_page(page)) {
1461 /* Has the page been truncated? */
1462 if (unlikely(page->mapping != mapping)) {
1467 VM_BUG_ON_PAGE(page->index != offset, page);
1470 if (page && (fgp_flags & FGP_ACCESSED))
1471 mark_page_accessed(page);
1474 if (!page && (fgp_flags & FGP_CREAT)) {
1476 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1477 gfp_mask |= __GFP_WRITE;
1478 if (fgp_flags & FGP_NOFS)
1479 gfp_mask &= ~__GFP_FS;
1481 page = __page_cache_alloc(gfp_mask);
1485 if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
1486 fgp_flags |= FGP_LOCK;
1488 /* Init accessed so avoid atomic mark_page_accessed later */
1489 if (fgp_flags & FGP_ACCESSED)
1490 __SetPageReferenced(page);
1492 err = add_to_page_cache_lru(page, mapping, offset,
1493 gfp_mask & GFP_RECLAIM_MASK);
1494 if (unlikely(err)) {
1504 EXPORT_SYMBOL(pagecache_get_page);
1507 * find_get_entries - gang pagecache lookup
1508 * @mapping: The address_space to search
1509 * @start: The starting page cache index
1510 * @nr_entries: The maximum number of entries
1511 * @entries: Where the resulting entries are placed
1512 * @indices: The cache indices corresponding to the entries in @entries
1514 * find_get_entries() will search for and return a group of up to
1515 * @nr_entries entries in the mapping. The entries are placed at
1516 * @entries. find_get_entries() takes a reference against any actual
1519 * The search returns a group of mapping-contiguous page cache entries
1520 * with ascending indexes. There may be holes in the indices due to
1521 * not-present pages.
1523 * Any shadow entries of evicted pages, or swap entries from
1524 * shmem/tmpfs, are included in the returned array.
1526 * find_get_entries() returns the number of pages and shadow entries
1529 unsigned find_get_entries(struct address_space *mapping,
1530 pgoff_t start, unsigned int nr_entries,
1531 struct page **entries, pgoff_t *indices)
1534 unsigned int ret = 0;
1535 struct radix_tree_iter iter;
1541 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1542 struct page *head, *page;
1544 page = radix_tree_deref_slot(slot);
1545 if (unlikely(!page))
1547 if (radix_tree_exception(page)) {
1548 if (radix_tree_deref_retry(page)) {
1549 slot = radix_tree_iter_retry(&iter);
1553 * A shadow entry of a recently evicted page, a swap
1554 * entry from shmem/tmpfs or a DAX entry. Return it
1555 * without attempting to raise page count.
1560 head = compound_head(page);
1561 if (!page_cache_get_speculative(head))
1564 /* The page was split under us? */
1565 if (compound_head(page) != head) {
1570 /* Has the page moved? */
1571 if (unlikely(page != *slot)) {
1576 indices[ret] = iter.index;
1577 entries[ret] = page;
1578 if (++ret == nr_entries)
1586 * find_get_pages_range - gang pagecache lookup
1587 * @mapping: The address_space to search
1588 * @start: The starting page index
1589 * @end: The final page index (inclusive)
1590 * @nr_pages: The maximum number of pages
1591 * @pages: Where the resulting pages are placed
1593 * find_get_pages_range() will search for and return a group of up to @nr_pages
1594 * pages in the mapping starting at index @start and up to index @end
1595 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1596 * a reference against the returned pages.
1598 * The search returns a group of mapping-contiguous pages with ascending
1599 * indexes. There may be holes in the indices due to not-present pages.
1600 * We also update @start to index the next page for the traversal.
1602 * find_get_pages_range() returns the number of pages which were found. If this
1603 * number is smaller than @nr_pages, the end of specified range has been
1606 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1607 pgoff_t end, unsigned int nr_pages,
1608 struct page **pages)
1610 struct radix_tree_iter iter;
1614 if (unlikely(!nr_pages))
1618 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, *start) {
1619 struct page *head, *page;
1621 if (iter.index > end)
1624 page = radix_tree_deref_slot(slot);
1625 if (unlikely(!page))
1628 if (radix_tree_exception(page)) {
1629 if (radix_tree_deref_retry(page)) {
1630 slot = radix_tree_iter_retry(&iter);
1634 * A shadow entry of a recently evicted page,
1635 * or a swap entry from shmem/tmpfs. Skip
1641 head = compound_head(page);
1642 if (!page_cache_get_speculative(head))
1645 /* The page was split under us? */
1646 if (compound_head(page) != head) {
1651 /* Has the page moved? */
1652 if (unlikely(page != *slot)) {
1658 if (++ret == nr_pages) {
1659 *start = pages[ret - 1]->index + 1;
1665 * We come here when there is no page beyond @end. We take care to not
1666 * overflow the index @start as it confuses some of the callers. This
1667 * breaks the iteration when there is page at index -1 but that is
1668 * already broken anyway.
1670 if (end == (pgoff_t)-1)
1671 *start = (pgoff_t)-1;
1681 * find_get_pages_contig - gang contiguous pagecache lookup
1682 * @mapping: The address_space to search
1683 * @index: The starting page index
1684 * @nr_pages: The maximum number of pages
1685 * @pages: Where the resulting pages are placed
1687 * find_get_pages_contig() works exactly like find_get_pages(), except
1688 * that the returned number of pages are guaranteed to be contiguous.
1690 * find_get_pages_contig() returns the number of pages which were found.
1692 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1693 unsigned int nr_pages, struct page **pages)
1695 struct radix_tree_iter iter;
1697 unsigned int ret = 0;
1699 if (unlikely(!nr_pages))
1703 radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
1704 struct page *head, *page;
1706 page = radix_tree_deref_slot(slot);
1707 /* The hole, there no reason to continue */
1708 if (unlikely(!page))
1711 if (radix_tree_exception(page)) {
1712 if (radix_tree_deref_retry(page)) {
1713 slot = radix_tree_iter_retry(&iter);
1717 * A shadow entry of a recently evicted page,
1718 * or a swap entry from shmem/tmpfs. Stop
1719 * looking for contiguous pages.
1724 head = compound_head(page);
1725 if (!page_cache_get_speculative(head))
1728 /* The page was split under us? */
1729 if (compound_head(page) != head) {
1734 /* Has the page moved? */
1735 if (unlikely(page != *slot)) {
1741 * must check mapping and index after taking the ref.
1742 * otherwise we can get both false positives and false
1743 * negatives, which is just confusing to the caller.
1745 if (page->mapping == NULL || page_to_pgoff(page) != iter.index) {
1751 if (++ret == nr_pages)
1757 EXPORT_SYMBOL(find_get_pages_contig);
1760 * find_get_pages_range_tag - find and return pages in given range matching @tag
1761 * @mapping: the address_space to search
1762 * @index: the starting page index
1763 * @end: The final page index (inclusive)
1764 * @tag: the tag index
1765 * @nr_pages: the maximum number of pages
1766 * @pages: where the resulting pages are placed
1768 * Like find_get_pages, except we only return pages which are tagged with
1769 * @tag. We update @index to index the next page for the traversal.
1771 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
1772 pgoff_t end, int tag, unsigned int nr_pages,
1773 struct page **pages)
1775 struct radix_tree_iter iter;
1779 if (unlikely(!nr_pages))
1783 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1784 &iter, *index, tag) {
1785 struct page *head, *page;
1787 if (iter.index > end)
1790 page = radix_tree_deref_slot(slot);
1791 if (unlikely(!page))
1794 if (radix_tree_exception(page)) {
1795 if (radix_tree_deref_retry(page)) {
1796 slot = radix_tree_iter_retry(&iter);
1800 * A shadow entry of a recently evicted page.
1802 * Those entries should never be tagged, but
1803 * this tree walk is lockless and the tags are
1804 * looked up in bulk, one radix tree node at a
1805 * time, so there is a sizable window for page
1806 * reclaim to evict a page we saw tagged.
1813 head = compound_head(page);
1814 if (!page_cache_get_speculative(head))
1817 /* The page was split under us? */
1818 if (compound_head(page) != head) {
1823 /* Has the page moved? */
1824 if (unlikely(page != *slot)) {
1830 if (++ret == nr_pages) {
1831 *index = pages[ret - 1]->index + 1;
1837 * We come here when we got at @end. We take care to not overflow the
1838 * index @index as it confuses some of the callers. This breaks the
1839 * iteration when there is page at index -1 but that is already broken
1842 if (end == (pgoff_t)-1)
1843 *index = (pgoff_t)-1;
1851 EXPORT_SYMBOL(find_get_pages_range_tag);
1854 * find_get_entries_tag - find and return entries that match @tag
1855 * @mapping: the address_space to search
1856 * @start: the starting page cache index
1857 * @tag: the tag index
1858 * @nr_entries: the maximum number of entries
1859 * @entries: where the resulting entries are placed
1860 * @indices: the cache indices corresponding to the entries in @entries
1862 * Like find_get_entries, except we only return entries which are tagged with
1865 unsigned find_get_entries_tag(struct address_space *mapping, pgoff_t start,
1866 int tag, unsigned int nr_entries,
1867 struct page **entries, pgoff_t *indices)
1870 unsigned int ret = 0;
1871 struct radix_tree_iter iter;
1877 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1878 &iter, start, tag) {
1879 struct page *head, *page;
1881 page = radix_tree_deref_slot(slot);
1882 if (unlikely(!page))
1884 if (radix_tree_exception(page)) {
1885 if (radix_tree_deref_retry(page)) {
1886 slot = radix_tree_iter_retry(&iter);
1891 * A shadow entry of a recently evicted page, a swap
1892 * entry from shmem/tmpfs or a DAX entry. Return it
1893 * without attempting to raise page count.
1898 head = compound_head(page);
1899 if (!page_cache_get_speculative(head))
1902 /* The page was split under us? */
1903 if (compound_head(page) != head) {
1908 /* Has the page moved? */
1909 if (unlikely(page != *slot)) {
1914 indices[ret] = iter.index;
1915 entries[ret] = page;
1916 if (++ret == nr_entries)
1922 EXPORT_SYMBOL(find_get_entries_tag);
1925 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1926 * a _large_ part of the i/o request. Imagine the worst scenario:
1928 * ---R__________________________________________B__________
1929 * ^ reading here ^ bad block(assume 4k)
1931 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1932 * => failing the whole request => read(R) => read(R+1) =>
1933 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1934 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1935 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1937 * It is going insane. Fix it by quickly scaling down the readahead size.
1939 static void shrink_readahead_size_eio(struct file *filp,
1940 struct file_ra_state *ra)
1946 * generic_file_buffered_read - generic file read routine
1947 * @iocb: the iocb to read
1948 * @iter: data destination
1949 * @written: already copied
1951 * This is a generic file read routine, and uses the
1952 * mapping->a_ops->readpage() function for the actual low-level stuff.
1954 * This is really ugly. But the goto's actually try to clarify some
1955 * of the logic when it comes to error handling etc.
1957 static ssize_t generic_file_buffered_read(struct kiocb *iocb,
1958 struct iov_iter *iter, ssize_t written)
1960 struct file *filp = iocb->ki_filp;
1961 struct address_space *mapping = filp->f_mapping;
1962 struct inode *inode = mapping->host;
1963 struct file_ra_state *ra = &filp->f_ra;
1964 loff_t *ppos = &iocb->ki_pos;
1968 unsigned long offset; /* offset into pagecache page */
1969 unsigned int prev_offset;
1972 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
1974 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
1976 index = *ppos >> PAGE_SHIFT;
1977 prev_index = ra->prev_pos >> PAGE_SHIFT;
1978 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
1979 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
1980 offset = *ppos & ~PAGE_MASK;
1986 unsigned long nr, ret;
1990 if (fatal_signal_pending(current)) {
1995 page = find_get_page(mapping, index);
1997 if (iocb->ki_flags & IOCB_NOWAIT)
1999 page_cache_sync_readahead(mapping,
2001 index, last_index - index);
2002 page = find_get_page(mapping, index);
2003 if (unlikely(page == NULL))
2004 goto no_cached_page;
2006 if (PageReadahead(page)) {
2007 page_cache_async_readahead(mapping,
2009 index, last_index - index);
2011 if (!PageUptodate(page)) {
2012 if (iocb->ki_flags & IOCB_NOWAIT) {
2018 * See comment in do_read_cache_page on why
2019 * wait_on_page_locked is used to avoid unnecessarily
2020 * serialisations and why it's safe.
2022 error = wait_on_page_locked_killable(page);
2023 if (unlikely(error))
2024 goto readpage_error;
2025 if (PageUptodate(page))
2028 if (inode->i_blkbits == PAGE_SHIFT ||
2029 !mapping->a_ops->is_partially_uptodate)
2030 goto page_not_up_to_date;
2031 /* pipes can't handle partially uptodate pages */
2032 if (unlikely(iter->type & ITER_PIPE))
2033 goto page_not_up_to_date;
2034 if (!trylock_page(page))
2035 goto page_not_up_to_date;
2036 /* Did it get truncated before we got the lock? */
2038 goto page_not_up_to_date_locked;
2039 if (!mapping->a_ops->is_partially_uptodate(page,
2040 offset, iter->count))
2041 goto page_not_up_to_date_locked;
2046 * i_size must be checked after we know the page is Uptodate.
2048 * Checking i_size after the check allows us to calculate
2049 * the correct value for "nr", which means the zero-filled
2050 * part of the page is not copied back to userspace (unless
2051 * another truncate extends the file - this is desired though).
2054 isize = i_size_read(inode);
2055 end_index = (isize - 1) >> PAGE_SHIFT;
2056 if (unlikely(!isize || index > end_index)) {
2061 /* nr is the maximum number of bytes to copy from this page */
2063 if (index == end_index) {
2064 nr = ((isize - 1) & ~PAGE_MASK) + 1;
2072 /* If users can be writing to this page using arbitrary
2073 * virtual addresses, take care about potential aliasing
2074 * before reading the page on the kernel side.
2076 if (mapping_writably_mapped(mapping))
2077 flush_dcache_page(page);
2080 * When a sequential read accesses a page several times,
2081 * only mark it as accessed the first time.
2083 if (prev_index != index || offset != prev_offset)
2084 mark_page_accessed(page);
2088 * Ok, we have the page, and it's up-to-date, so
2089 * now we can copy it to user space...
2092 ret = copy_page_to_iter(page, offset, nr, iter);
2094 index += offset >> PAGE_SHIFT;
2095 offset &= ~PAGE_MASK;
2096 prev_offset = offset;
2100 if (!iov_iter_count(iter))
2108 page_not_up_to_date:
2109 /* Get exclusive access to the page ... */
2110 error = lock_page_killable(page);
2111 if (unlikely(error))
2112 goto readpage_error;
2114 page_not_up_to_date_locked:
2115 /* Did it get truncated before we got the lock? */
2116 if (!page->mapping) {
2122 /* Did somebody else fill it already? */
2123 if (PageUptodate(page)) {
2130 * A previous I/O error may have been due to temporary
2131 * failures, eg. multipath errors.
2132 * PG_error will be set again if readpage fails.
2134 ClearPageError(page);
2135 /* Start the actual read. The read will unlock the page. */
2136 error = mapping->a_ops->readpage(filp, page);
2138 if (unlikely(error)) {
2139 if (error == AOP_TRUNCATED_PAGE) {
2144 goto readpage_error;
2147 if (!PageUptodate(page)) {
2148 error = lock_page_killable(page);
2149 if (unlikely(error))
2150 goto readpage_error;
2151 if (!PageUptodate(page)) {
2152 if (page->mapping == NULL) {
2154 * invalidate_mapping_pages got it
2161 shrink_readahead_size_eio(filp, ra);
2163 goto readpage_error;
2171 /* UHHUH! A synchronous read error occurred. Report it */
2177 * Ok, it wasn't cached, so we need to create a new
2180 page = page_cache_alloc_cold(mapping);
2185 error = add_to_page_cache_lru(page, mapping, index,
2186 mapping_gfp_constraint(mapping, GFP_KERNEL));
2189 if (error == -EEXIST) {
2201 ra->prev_pos = prev_index;
2202 ra->prev_pos <<= PAGE_SHIFT;
2203 ra->prev_pos |= prev_offset;
2205 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
2206 file_accessed(filp);
2207 return written ? written : error;
2211 * generic_file_read_iter - generic filesystem read routine
2212 * @iocb: kernel I/O control block
2213 * @iter: destination for the data read
2215 * This is the "read_iter()" routine for all filesystems
2216 * that can use the page cache directly.
2219 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2221 size_t count = iov_iter_count(iter);
2225 goto out; /* skip atime */
2227 if (iocb->ki_flags & IOCB_DIRECT) {
2228 struct file *file = iocb->ki_filp;
2229 struct address_space *mapping = file->f_mapping;
2230 struct inode *inode = mapping->host;
2233 size = i_size_read(inode);
2234 if (iocb->ki_flags & IOCB_NOWAIT) {
2235 if (filemap_range_has_page(mapping, iocb->ki_pos,
2236 iocb->ki_pos + count - 1))
2239 retval = filemap_write_and_wait_range(mapping,
2241 iocb->ki_pos + count - 1);
2246 file_accessed(file);
2248 retval = mapping->a_ops->direct_IO(iocb, iter);
2250 iocb->ki_pos += retval;
2253 iov_iter_revert(iter, count - iov_iter_count(iter));
2256 * Btrfs can have a short DIO read if we encounter
2257 * compressed extents, so if there was an error, or if
2258 * we've already read everything we wanted to, or if
2259 * there was a short read because we hit EOF, go ahead
2260 * and return. Otherwise fallthrough to buffered io for
2261 * the rest of the read. Buffered reads will not work for
2262 * DAX files, so don't bother trying.
2264 if (retval < 0 || !count || iocb->ki_pos >= size ||
2269 retval = generic_file_buffered_read(iocb, iter, retval);
2273 EXPORT_SYMBOL(generic_file_read_iter);
2277 * page_cache_read - adds requested page to the page cache if not already there
2278 * @file: file to read
2279 * @offset: page index
2280 * @gfp_mask: memory allocation flags
2282 * This adds the requested page to the page cache if it isn't already there,
2283 * and schedules an I/O to read in its contents from disk.
2285 static int page_cache_read(struct file *file, pgoff_t offset, gfp_t gfp_mask)
2287 struct address_space *mapping = file->f_mapping;
2292 page = __page_cache_alloc(gfp_mask|__GFP_COLD);
2296 ret = add_to_page_cache_lru(page, mapping, offset, gfp_mask & GFP_KERNEL);
2298 ret = mapping->a_ops->readpage(file, page);
2299 else if (ret == -EEXIST)
2300 ret = 0; /* losing race to add is OK */
2304 } while (ret == AOP_TRUNCATED_PAGE);
2309 #define MMAP_LOTSAMISS (100)
2312 * Synchronous readahead happens when we don't even find
2313 * a page in the page cache at all.
2315 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
2316 struct file_ra_state *ra,
2320 struct address_space *mapping = file->f_mapping;
2322 /* If we don't want any read-ahead, don't bother */
2323 if (vma->vm_flags & VM_RAND_READ)
2328 if (vma->vm_flags & VM_SEQ_READ) {
2329 page_cache_sync_readahead(mapping, ra, file, offset,
2334 /* Avoid banging the cache line if not needed */
2335 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
2339 * Do we miss much more than hit in this file? If so,
2340 * stop bothering with read-ahead. It will only hurt.
2342 if (ra->mmap_miss > MMAP_LOTSAMISS)
2348 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2349 ra->size = ra->ra_pages;
2350 ra->async_size = ra->ra_pages / 4;
2351 ra_submit(ra, mapping, file);
2355 * Asynchronous readahead happens when we find the page and PG_readahead,
2356 * so we want to possibly extend the readahead further..
2358 static void do_async_mmap_readahead(struct vm_area_struct *vma,
2359 struct file_ra_state *ra,
2364 struct address_space *mapping = file->f_mapping;
2366 /* If we don't want any read-ahead, don't bother */
2367 if (vma->vm_flags & VM_RAND_READ)
2369 if (ra->mmap_miss > 0)
2371 if (PageReadahead(page))
2372 page_cache_async_readahead(mapping, ra, file,
2373 page, offset, ra->ra_pages);
2377 * filemap_fault - read in file data for page fault handling
2378 * @vmf: struct vm_fault containing details of the fault
2380 * filemap_fault() is invoked via the vma operations vector for a
2381 * mapped memory region to read in file data during a page fault.
2383 * The goto's are kind of ugly, but this streamlines the normal case of having
2384 * it in the page cache, and handles the special cases reasonably without
2385 * having a lot of duplicated code.
2387 * vma->vm_mm->mmap_sem must be held on entry.
2389 * If our return value has VM_FAULT_RETRY set, it's because
2390 * lock_page_or_retry() returned 0.
2391 * The mmap_sem has usually been released in this case.
2392 * See __lock_page_or_retry() for the exception.
2394 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2395 * has not been released.
2397 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2399 int filemap_fault(struct vm_fault *vmf)
2402 struct file *file = vmf->vma->vm_file;
2403 struct address_space *mapping = file->f_mapping;
2404 struct file_ra_state *ra = &file->f_ra;
2405 struct inode *inode = mapping->host;
2406 pgoff_t offset = vmf->pgoff;
2411 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2412 if (unlikely(offset >= max_off))
2413 return VM_FAULT_SIGBUS;
2416 * Do we have something in the page cache already?
2418 page = find_get_page(mapping, offset);
2419 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
2421 * We found the page, so try async readahead before
2422 * waiting for the lock.
2424 do_async_mmap_readahead(vmf->vma, ra, file, page, offset);
2426 /* No page in the page cache at all */
2427 do_sync_mmap_readahead(vmf->vma, ra, file, offset);
2428 count_vm_event(PGMAJFAULT);
2429 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
2430 ret = VM_FAULT_MAJOR;
2432 page = find_get_page(mapping, offset);
2434 goto no_cached_page;
2437 if (!lock_page_or_retry(page, vmf->vma->vm_mm, vmf->flags)) {
2439 return ret | VM_FAULT_RETRY;
2442 /* Did it get truncated? */
2443 if (unlikely(page->mapping != mapping)) {
2448 VM_BUG_ON_PAGE(page->index != offset, page);
2451 * We have a locked page in the page cache, now we need to check
2452 * that it's up-to-date. If not, it is going to be due to an error.
2454 if (unlikely(!PageUptodate(page)))
2455 goto page_not_uptodate;
2458 * Found the page and have a reference on it.
2459 * We must recheck i_size under page lock.
2461 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2462 if (unlikely(offset >= max_off)) {
2465 return VM_FAULT_SIGBUS;
2469 return ret | VM_FAULT_LOCKED;
2473 * We're only likely to ever get here if MADV_RANDOM is in
2476 error = page_cache_read(file, offset, vmf->gfp_mask);
2479 * The page we want has now been added to the page cache.
2480 * In the unlikely event that someone removed it in the
2481 * meantime, we'll just come back here and read it again.
2487 * An error return from page_cache_read can result if the
2488 * system is low on memory, or a problem occurs while trying
2491 if (error == -ENOMEM)
2492 return VM_FAULT_OOM;
2493 return VM_FAULT_SIGBUS;
2497 * Umm, take care of errors if the page isn't up-to-date.
2498 * Try to re-read it _once_. We do this synchronously,
2499 * because there really aren't any performance issues here
2500 * and we need to check for errors.
2502 ClearPageError(page);
2503 error = mapping->a_ops->readpage(file, page);
2505 wait_on_page_locked(page);
2506 if (!PageUptodate(page))
2511 if (!error || error == AOP_TRUNCATED_PAGE)
2514 /* Things didn't work out. Return zero to tell the mm layer so. */
2515 shrink_readahead_size_eio(file, ra);
2516 return VM_FAULT_SIGBUS;
2518 EXPORT_SYMBOL(filemap_fault);
2520 void filemap_map_pages(struct vm_fault *vmf,
2521 pgoff_t start_pgoff, pgoff_t end_pgoff)
2523 struct radix_tree_iter iter;
2525 struct file *file = vmf->vma->vm_file;
2526 struct address_space *mapping = file->f_mapping;
2527 pgoff_t last_pgoff = start_pgoff;
2528 unsigned long max_idx;
2529 struct page *head, *page;
2532 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter,
2534 if (iter.index > end_pgoff)
2537 page = radix_tree_deref_slot(slot);
2538 if (unlikely(!page))
2540 if (radix_tree_exception(page)) {
2541 if (radix_tree_deref_retry(page)) {
2542 slot = radix_tree_iter_retry(&iter);
2548 head = compound_head(page);
2549 if (!page_cache_get_speculative(head))
2552 /* The page was split under us? */
2553 if (compound_head(page) != head) {
2558 /* Has the page moved? */
2559 if (unlikely(page != *slot)) {
2564 if (!PageUptodate(page) ||
2565 PageReadahead(page) ||
2568 if (!trylock_page(page))
2571 if (page->mapping != mapping || !PageUptodate(page))
2574 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2575 if (page->index >= max_idx)
2578 if (file->f_ra.mmap_miss > 0)
2579 file->f_ra.mmap_miss--;
2581 vmf->address += (iter.index - last_pgoff) << PAGE_SHIFT;
2583 vmf->pte += iter.index - last_pgoff;
2584 last_pgoff = iter.index;
2585 if (alloc_set_pte(vmf, NULL, page))
2594 /* Huge page is mapped? No need to proceed. */
2595 if (pmd_trans_huge(*vmf->pmd))
2597 if (iter.index == end_pgoff)
2602 EXPORT_SYMBOL(filemap_map_pages);
2604 int filemap_page_mkwrite(struct vm_fault *vmf)
2606 struct page *page = vmf->page;
2607 struct inode *inode = file_inode(vmf->vma->vm_file);
2608 int ret = VM_FAULT_LOCKED;
2610 sb_start_pagefault(inode->i_sb);
2611 file_update_time(vmf->vma->vm_file);
2613 if (page->mapping != inode->i_mapping) {
2615 ret = VM_FAULT_NOPAGE;
2619 * We mark the page dirty already here so that when freeze is in
2620 * progress, we are guaranteed that writeback during freezing will
2621 * see the dirty page and writeprotect it again.
2623 set_page_dirty(page);
2624 wait_for_stable_page(page);
2626 sb_end_pagefault(inode->i_sb);
2629 EXPORT_SYMBOL(filemap_page_mkwrite);
2631 const struct vm_operations_struct generic_file_vm_ops = {
2632 .fault = filemap_fault,
2633 .map_pages = filemap_map_pages,
2634 .page_mkwrite = filemap_page_mkwrite,
2637 /* This is used for a general mmap of a disk file */
2639 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2641 struct address_space *mapping = file->f_mapping;
2643 if (!mapping->a_ops->readpage)
2645 file_accessed(file);
2646 vma->vm_ops = &generic_file_vm_ops;
2651 * This is for filesystems which do not implement ->writepage.
2653 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2655 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2657 return generic_file_mmap(file, vma);
2660 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2664 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2668 #endif /* CONFIG_MMU */
2670 EXPORT_SYMBOL(generic_file_mmap);
2671 EXPORT_SYMBOL(generic_file_readonly_mmap);
2673 static struct page *wait_on_page_read(struct page *page)
2675 if (!IS_ERR(page)) {
2676 wait_on_page_locked(page);
2677 if (!PageUptodate(page)) {
2679 page = ERR_PTR(-EIO);
2685 static struct page *do_read_cache_page(struct address_space *mapping,
2687 int (*filler)(void *, struct page *),
2694 page = find_get_page(mapping, index);
2696 page = __page_cache_alloc(gfp | __GFP_COLD);
2698 return ERR_PTR(-ENOMEM);
2699 err = add_to_page_cache_lru(page, mapping, index, gfp);
2700 if (unlikely(err)) {
2704 /* Presumably ENOMEM for radix tree node */
2705 return ERR_PTR(err);
2709 err = filler(data, page);
2712 return ERR_PTR(err);
2715 page = wait_on_page_read(page);
2720 if (PageUptodate(page))
2724 * Page is not up to date and may be locked due one of the following
2725 * case a: Page is being filled and the page lock is held
2726 * case b: Read/write error clearing the page uptodate status
2727 * case c: Truncation in progress (page locked)
2728 * case d: Reclaim in progress
2730 * Case a, the page will be up to date when the page is unlocked.
2731 * There is no need to serialise on the page lock here as the page
2732 * is pinned so the lock gives no additional protection. Even if the
2733 * the page is truncated, the data is still valid if PageUptodate as
2734 * it's a race vs truncate race.
2735 * Case b, the page will not be up to date
2736 * Case c, the page may be truncated but in itself, the data may still
2737 * be valid after IO completes as it's a read vs truncate race. The
2738 * operation must restart if the page is not uptodate on unlock but
2739 * otherwise serialising on page lock to stabilise the mapping gives
2740 * no additional guarantees to the caller as the page lock is
2741 * released before return.
2742 * Case d, similar to truncation. If reclaim holds the page lock, it
2743 * will be a race with remove_mapping that determines if the mapping
2744 * is valid on unlock but otherwise the data is valid and there is
2745 * no need to serialise with page lock.
2747 * As the page lock gives no additional guarantee, we optimistically
2748 * wait on the page to be unlocked and check if it's up to date and
2749 * use the page if it is. Otherwise, the page lock is required to
2750 * distinguish between the different cases. The motivation is that we
2751 * avoid spurious serialisations and wakeups when multiple processes
2752 * wait on the same page for IO to complete.
2754 wait_on_page_locked(page);
2755 if (PageUptodate(page))
2758 /* Distinguish between all the cases under the safety of the lock */
2761 /* Case c or d, restart the operation */
2762 if (!page->mapping) {
2768 /* Someone else locked and filled the page in a very small window */
2769 if (PageUptodate(page)) {
2776 mark_page_accessed(page);
2781 * read_cache_page - read into page cache, fill it if needed
2782 * @mapping: the page's address_space
2783 * @index: the page index
2784 * @filler: function to perform the read
2785 * @data: first arg to filler(data, page) function, often left as NULL
2787 * Read into the page cache. If a page already exists, and PageUptodate() is
2788 * not set, try to fill the page and wait for it to become unlocked.
2790 * If the page does not get brought uptodate, return -EIO.
2792 struct page *read_cache_page(struct address_space *mapping,
2794 int (*filler)(void *, struct page *),
2797 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2799 EXPORT_SYMBOL(read_cache_page);
2802 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2803 * @mapping: the page's address_space
2804 * @index: the page index
2805 * @gfp: the page allocator flags to use if allocating
2807 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2808 * any new page allocations done using the specified allocation flags.
2810 * If the page does not get brought uptodate, return -EIO.
2812 struct page *read_cache_page_gfp(struct address_space *mapping,
2816 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2818 return do_read_cache_page(mapping, index, filler, NULL, gfp);
2820 EXPORT_SYMBOL(read_cache_page_gfp);
2823 * Performs necessary checks before doing a write
2825 * Can adjust writing position or amount of bytes to write.
2826 * Returns appropriate error code that caller should return or
2827 * zero in case that write should be allowed.
2829 inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
2831 struct file *file = iocb->ki_filp;
2832 struct inode *inode = file->f_mapping->host;
2833 unsigned long limit = rlimit(RLIMIT_FSIZE);
2836 if (!iov_iter_count(from))
2839 /* FIXME: this is for backwards compatibility with 2.4 */
2840 if (iocb->ki_flags & IOCB_APPEND)
2841 iocb->ki_pos = i_size_read(inode);
2845 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2848 if (limit != RLIM_INFINITY) {
2849 if (iocb->ki_pos >= limit) {
2850 send_sig(SIGXFSZ, current, 0);
2853 iov_iter_truncate(from, limit - (unsigned long)pos);
2859 if (unlikely(pos + iov_iter_count(from) > MAX_NON_LFS &&
2860 !(file->f_flags & O_LARGEFILE))) {
2861 if (pos >= MAX_NON_LFS)
2863 iov_iter_truncate(from, MAX_NON_LFS - (unsigned long)pos);
2867 * Are we about to exceed the fs block limit ?
2869 * If we have written data it becomes a short write. If we have
2870 * exceeded without writing data we send a signal and return EFBIG.
2871 * Linus frestrict idea will clean these up nicely..
2873 if (unlikely(pos >= inode->i_sb->s_maxbytes))
2876 iov_iter_truncate(from, inode->i_sb->s_maxbytes - pos);
2877 return iov_iter_count(from);
2879 EXPORT_SYMBOL(generic_write_checks);
2881 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2882 loff_t pos, unsigned len, unsigned flags,
2883 struct page **pagep, void **fsdata)
2885 const struct address_space_operations *aops = mapping->a_ops;
2887 return aops->write_begin(file, mapping, pos, len, flags,
2890 EXPORT_SYMBOL(pagecache_write_begin);
2892 int pagecache_write_end(struct file *file, struct address_space *mapping,
2893 loff_t pos, unsigned len, unsigned copied,
2894 struct page *page, void *fsdata)
2896 const struct address_space_operations *aops = mapping->a_ops;
2898 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2900 EXPORT_SYMBOL(pagecache_write_end);
2903 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
2905 struct file *file = iocb->ki_filp;
2906 struct address_space *mapping = file->f_mapping;
2907 struct inode *inode = mapping->host;
2908 loff_t pos = iocb->ki_pos;
2913 write_len = iov_iter_count(from);
2914 end = (pos + write_len - 1) >> PAGE_SHIFT;
2916 if (iocb->ki_flags & IOCB_NOWAIT) {
2917 /* If there are pages to writeback, return */
2918 if (filemap_range_has_page(inode->i_mapping, pos,
2919 pos + iov_iter_count(from)))
2922 written = filemap_write_and_wait_range(mapping, pos,
2923 pos + write_len - 1);
2929 * After a write we want buffered reads to be sure to go to disk to get
2930 * the new data. We invalidate clean cached page from the region we're
2931 * about to write. We do this *before* the write so that we can return
2932 * without clobbering -EIOCBQUEUED from ->direct_IO().
2934 written = invalidate_inode_pages2_range(mapping,
2935 pos >> PAGE_SHIFT, end);
2937 * If a page can not be invalidated, return 0 to fall back
2938 * to buffered write.
2941 if (written == -EBUSY)
2946 written = mapping->a_ops->direct_IO(iocb, from);
2949 * Finally, try again to invalidate clean pages which might have been
2950 * cached by non-direct readahead, or faulted in by get_user_pages()
2951 * if the source of the write was an mmap'ed region of the file
2952 * we're writing. Either one is a pretty crazy thing to do,
2953 * so we don't support it 100%. If this invalidation
2954 * fails, tough, the write still worked...
2956 * Most of the time we do not need this since dio_complete() will do
2957 * the invalidation for us. However there are some file systems that
2958 * do not end up with dio_complete() being called, so let's not break
2959 * them by removing it completely
2961 if (mapping->nrpages)
2962 invalidate_inode_pages2_range(mapping,
2963 pos >> PAGE_SHIFT, end);
2967 write_len -= written;
2968 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2969 i_size_write(inode, pos);
2970 mark_inode_dirty(inode);
2974 iov_iter_revert(from, write_len - iov_iter_count(from));
2978 EXPORT_SYMBOL(generic_file_direct_write);
2981 * Find or create a page at the given pagecache position. Return the locked
2982 * page. This function is specifically for buffered writes.
2984 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2985 pgoff_t index, unsigned flags)
2988 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
2990 if (flags & AOP_FLAG_NOFS)
2991 fgp_flags |= FGP_NOFS;
2993 page = pagecache_get_page(mapping, index, fgp_flags,
2994 mapping_gfp_mask(mapping));
2996 wait_for_stable_page(page);
3000 EXPORT_SYMBOL(grab_cache_page_write_begin);
3002 ssize_t generic_perform_write(struct file *file,
3003 struct iov_iter *i, loff_t pos)
3005 struct address_space *mapping = file->f_mapping;
3006 const struct address_space_operations *a_ops = mapping->a_ops;
3008 ssize_t written = 0;
3009 unsigned int flags = 0;
3013 unsigned long offset; /* Offset into pagecache page */
3014 unsigned long bytes; /* Bytes to write to page */
3015 size_t copied; /* Bytes copied from user */
3018 offset = (pos & (PAGE_SIZE - 1));
3019 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3024 * Bring in the user page that we will copy from _first_.
3025 * Otherwise there's a nasty deadlock on copying from the
3026 * same page as we're writing to, without it being marked
3029 * Not only is this an optimisation, but it is also required
3030 * to check that the address is actually valid, when atomic
3031 * usercopies are used, below.
3033 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3038 if (fatal_signal_pending(current)) {
3043 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3045 if (unlikely(status < 0))
3048 if (mapping_writably_mapped(mapping))
3049 flush_dcache_page(page);
3051 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
3052 flush_dcache_page(page);
3054 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3056 if (unlikely(status < 0))
3062 iov_iter_advance(i, copied);
3063 if (unlikely(copied == 0)) {
3065 * If we were unable to copy any data at all, we must
3066 * fall back to a single segment length write.
3068 * If we didn't fallback here, we could livelock
3069 * because not all segments in the iov can be copied at
3070 * once without a pagefault.
3072 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3073 iov_iter_single_seg_count(i));
3079 balance_dirty_pages_ratelimited(mapping);
3080 } while (iov_iter_count(i));
3082 return written ? written : status;
3084 EXPORT_SYMBOL(generic_perform_write);
3087 * __generic_file_write_iter - write data to a file
3088 * @iocb: IO state structure (file, offset, etc.)
3089 * @from: iov_iter with data to write
3091 * This function does all the work needed for actually writing data to a
3092 * file. It does all basic checks, removes SUID from the file, updates
3093 * modification times and calls proper subroutines depending on whether we
3094 * do direct IO or a standard buffered write.
3096 * It expects i_mutex to be grabbed unless we work on a block device or similar
3097 * object which does not need locking at all.
3099 * This function does *not* take care of syncing data in case of O_SYNC write.
3100 * A caller has to handle it. This is mainly due to the fact that we want to
3101 * avoid syncing under i_mutex.
3103 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3105 struct file *file = iocb->ki_filp;
3106 struct address_space * mapping = file->f_mapping;
3107 struct inode *inode = mapping->host;
3108 ssize_t written = 0;
3112 /* We can write back this queue in page reclaim */
3113 current->backing_dev_info = inode_to_bdi(inode);
3114 err = file_remove_privs(file);
3118 err = file_update_time(file);
3122 if (iocb->ki_flags & IOCB_DIRECT) {
3123 loff_t pos, endbyte;
3125 written = generic_file_direct_write(iocb, from);
3127 * If the write stopped short of completing, fall back to
3128 * buffered writes. Some filesystems do this for writes to
3129 * holes, for example. For DAX files, a buffered write will
3130 * not succeed (even if it did, DAX does not handle dirty
3131 * page-cache pages correctly).
3133 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3136 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3138 * If generic_perform_write() returned a synchronous error
3139 * then we want to return the number of bytes which were
3140 * direct-written, or the error code if that was zero. Note
3141 * that this differs from normal direct-io semantics, which
3142 * will return -EFOO even if some bytes were written.
3144 if (unlikely(status < 0)) {
3149 * We need to ensure that the page cache pages are written to
3150 * disk and invalidated to preserve the expected O_DIRECT
3153 endbyte = pos + status - 1;
3154 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3156 iocb->ki_pos = endbyte + 1;
3158 invalidate_mapping_pages(mapping,
3160 endbyte >> PAGE_SHIFT);
3163 * We don't know how much we wrote, so just return
3164 * the number of bytes which were direct-written
3168 written = generic_perform_write(file, from, iocb->ki_pos);
3169 if (likely(written > 0))
3170 iocb->ki_pos += written;
3173 current->backing_dev_info = NULL;
3174 return written ? written : err;
3176 EXPORT_SYMBOL(__generic_file_write_iter);
3179 * generic_file_write_iter - write data to a file
3180 * @iocb: IO state structure
3181 * @from: iov_iter with data to write
3183 * This is a wrapper around __generic_file_write_iter() to be used by most
3184 * filesystems. It takes care of syncing the file in case of O_SYNC file
3185 * and acquires i_mutex as needed.
3187 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3189 struct file *file = iocb->ki_filp;
3190 struct inode *inode = file->f_mapping->host;
3194 ret = generic_write_checks(iocb, from);
3196 ret = __generic_file_write_iter(iocb, from);
3197 inode_unlock(inode);
3200 ret = generic_write_sync(iocb, ret);
3203 EXPORT_SYMBOL(generic_file_write_iter);
3206 * try_to_release_page() - release old fs-specific metadata on a page
3208 * @page: the page which the kernel is trying to free
3209 * @gfp_mask: memory allocation flags (and I/O mode)
3211 * The address_space is to try to release any data against the page
3212 * (presumably at page->private). If the release was successful, return '1'.
3213 * Otherwise return zero.
3215 * This may also be called if PG_fscache is set on a page, indicating that the
3216 * page is known to the local caching routines.
3218 * The @gfp_mask argument specifies whether I/O may be performed to release
3219 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3222 int try_to_release_page(struct page *page, gfp_t gfp_mask)
3224 struct address_space * const mapping = page->mapping;
3226 BUG_ON(!PageLocked(page));
3227 if (PageWriteback(page))
3230 if (mapping && mapping->a_ops->releasepage)
3231 return mapping->a_ops->releasepage(page, gfp_mask);
3232 return try_to_free_buffers(page);
3235 EXPORT_SYMBOL(try_to_release_page);