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));
258 * delete_from_page_cache - delete page from page cache
259 * @page: the page which the kernel is trying to remove from page cache
261 * This must be called only on pages that have been verified to be in the page
262 * cache and locked. It will never put the page into the free list, the caller
263 * has a reference on the page.
265 void delete_from_page_cache(struct page *page)
267 struct address_space *mapping = page_mapping(page);
269 void (*freepage)(struct page *);
271 BUG_ON(!PageLocked(page));
273 freepage = mapping->a_ops->freepage;
275 spin_lock_irqsave(&mapping->tree_lock, flags);
276 __delete_from_page_cache(page, NULL);
277 spin_unlock_irqrestore(&mapping->tree_lock, flags);
282 if (PageTransHuge(page) && !PageHuge(page)) {
283 page_ref_sub(page, HPAGE_PMD_NR);
284 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
289 EXPORT_SYMBOL(delete_from_page_cache);
291 int filemap_check_errors(struct address_space *mapping)
294 /* Check for outstanding write errors */
295 if (test_bit(AS_ENOSPC, &mapping->flags) &&
296 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
298 if (test_bit(AS_EIO, &mapping->flags) &&
299 test_and_clear_bit(AS_EIO, &mapping->flags))
303 EXPORT_SYMBOL(filemap_check_errors);
305 static int filemap_check_and_keep_errors(struct address_space *mapping)
307 /* Check for outstanding write errors */
308 if (test_bit(AS_EIO, &mapping->flags))
310 if (test_bit(AS_ENOSPC, &mapping->flags))
316 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
317 * @mapping: address space structure to write
318 * @start: offset in bytes where the range starts
319 * @end: offset in bytes where the range ends (inclusive)
320 * @sync_mode: enable synchronous operation
322 * Start writeback against all of a mapping's dirty pages that lie
323 * within the byte offsets <start, end> inclusive.
325 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
326 * opposed to a regular memory cleansing writeback. The difference between
327 * these two operations is that if a dirty page/buffer is encountered, it must
328 * be waited upon, and not just skipped over.
330 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
331 loff_t end, int sync_mode)
334 struct writeback_control wbc = {
335 .sync_mode = sync_mode,
336 .nr_to_write = LONG_MAX,
337 .range_start = start,
341 if (!mapping_cap_writeback_dirty(mapping) ||
342 !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
345 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
346 ret = do_writepages(mapping, &wbc);
347 wbc_detach_inode(&wbc);
351 static inline int __filemap_fdatawrite(struct address_space *mapping,
354 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
357 int filemap_fdatawrite(struct address_space *mapping)
359 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
361 EXPORT_SYMBOL(filemap_fdatawrite);
363 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
366 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
368 EXPORT_SYMBOL(filemap_fdatawrite_range);
371 * filemap_flush - mostly a non-blocking flush
372 * @mapping: target address_space
374 * This is a mostly non-blocking flush. Not suitable for data-integrity
375 * purposes - I/O may not be started against all dirty pages.
377 int filemap_flush(struct address_space *mapping)
379 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
381 EXPORT_SYMBOL(filemap_flush);
384 * filemap_range_has_page - check if a page exists in range.
385 * @mapping: address space within which to check
386 * @start_byte: offset in bytes where the range starts
387 * @end_byte: offset in bytes where the range ends (inclusive)
389 * Find at least one page in the range supplied, usually used to check if
390 * direct writing in this range will trigger a writeback.
392 bool filemap_range_has_page(struct address_space *mapping,
393 loff_t start_byte, loff_t end_byte)
395 pgoff_t index = start_byte >> PAGE_SHIFT;
396 pgoff_t end = end_byte >> PAGE_SHIFT;
399 if (end_byte < start_byte)
402 if (mapping->nrpages == 0)
405 if (!find_get_pages_range(mapping, &index, end, 1, &page))
410 EXPORT_SYMBOL(filemap_range_has_page);
412 static void __filemap_fdatawait_range(struct address_space *mapping,
413 loff_t start_byte, loff_t end_byte)
415 pgoff_t index = start_byte >> PAGE_SHIFT;
416 pgoff_t end = end_byte >> PAGE_SHIFT;
420 if (end_byte < start_byte)
423 pagevec_init(&pvec, 0);
424 while ((index <= end) &&
425 (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
426 PAGECACHE_TAG_WRITEBACK,
427 min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
430 for (i = 0; i < nr_pages; i++) {
431 struct page *page = pvec.pages[i];
433 /* until radix tree lookup accepts end_index */
434 if (page->index > end)
437 wait_on_page_writeback(page);
438 ClearPageError(page);
440 pagevec_release(&pvec);
446 * filemap_fdatawait_range - wait for writeback to complete
447 * @mapping: address space structure to wait for
448 * @start_byte: offset in bytes where the range starts
449 * @end_byte: offset in bytes where the range ends (inclusive)
451 * Walk the list of under-writeback pages of the given address space
452 * in the given range and wait for all of them. Check error status of
453 * the address space and return it.
455 * Since the error status of the address space is cleared by this function,
456 * callers are responsible for checking the return value and handling and/or
457 * reporting the error.
459 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
462 __filemap_fdatawait_range(mapping, start_byte, end_byte);
463 return filemap_check_errors(mapping);
465 EXPORT_SYMBOL(filemap_fdatawait_range);
468 * filemap_fdatawait_range_keep_errors - wait for writeback to complete
469 * @mapping: address space structure to wait for
470 * @start_byte: offset in bytes where the range starts
471 * @end_byte: offset in bytes where the range ends (inclusive)
473 * Walk the list of under-writeback pages of the given address space in the
474 * given range and wait for all of them. Unlike filemap_fdatawait_range(),
475 * this function does not clear error status of the address space.
477 * Use this function if callers don't handle errors themselves. Expected
478 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
481 int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
482 loff_t start_byte, loff_t end_byte)
484 __filemap_fdatawait_range(mapping, start_byte, end_byte);
485 return filemap_check_and_keep_errors(mapping);
487 EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
490 * file_fdatawait_range - wait for writeback to complete
491 * @file: file pointing to address space structure to wait for
492 * @start_byte: offset in bytes where the range starts
493 * @end_byte: offset in bytes where the range ends (inclusive)
495 * Walk the list of under-writeback pages of the address space that file
496 * refers to, in the given range and wait for all of them. Check error
497 * status of the address space vs. the file->f_wb_err cursor and return it.
499 * Since the error status of the file is advanced by this function,
500 * callers are responsible for checking the return value and handling and/or
501 * reporting the error.
503 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
505 struct address_space *mapping = file->f_mapping;
507 __filemap_fdatawait_range(mapping, start_byte, end_byte);
508 return file_check_and_advance_wb_err(file);
510 EXPORT_SYMBOL(file_fdatawait_range);
513 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
514 * @mapping: address space structure to wait for
516 * Walk the list of under-writeback pages of the given address space
517 * and wait for all of them. Unlike filemap_fdatawait(), this function
518 * does not clear error status of the address space.
520 * Use this function if callers don't handle errors themselves. Expected
521 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
524 int filemap_fdatawait_keep_errors(struct address_space *mapping)
526 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
527 return filemap_check_and_keep_errors(mapping);
529 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
531 static bool mapping_needs_writeback(struct address_space *mapping)
533 return (!dax_mapping(mapping) && mapping->nrpages) ||
534 (dax_mapping(mapping) && mapping->nrexceptional);
537 int filemap_write_and_wait(struct address_space *mapping)
541 if (mapping_needs_writeback(mapping)) {
542 err = filemap_fdatawrite(mapping);
544 * Even if the above returned error, the pages may be
545 * written partially (e.g. -ENOSPC), so we wait for it.
546 * But the -EIO is special case, it may indicate the worst
547 * thing (e.g. bug) happened, so we avoid waiting for it.
550 int err2 = filemap_fdatawait(mapping);
554 /* Clear any previously stored errors */
555 filemap_check_errors(mapping);
558 err = filemap_check_errors(mapping);
562 EXPORT_SYMBOL(filemap_write_and_wait);
565 * filemap_write_and_wait_range - write out & wait on a file range
566 * @mapping: the address_space for the pages
567 * @lstart: offset in bytes where the range starts
568 * @lend: offset in bytes where the range ends (inclusive)
570 * Write out and wait upon file offsets lstart->lend, inclusive.
572 * Note that @lend is inclusive (describes the last byte to be written) so
573 * that this function can be used to write to the very end-of-file (end = -1).
575 int filemap_write_and_wait_range(struct address_space *mapping,
576 loff_t lstart, loff_t lend)
580 if (mapping_needs_writeback(mapping)) {
581 err = __filemap_fdatawrite_range(mapping, lstart, lend,
583 /* See comment of filemap_write_and_wait() */
585 int err2 = filemap_fdatawait_range(mapping,
590 /* Clear any previously stored errors */
591 filemap_check_errors(mapping);
594 err = filemap_check_errors(mapping);
598 EXPORT_SYMBOL(filemap_write_and_wait_range);
600 void __filemap_set_wb_err(struct address_space *mapping, int err)
602 errseq_t eseq = errseq_set(&mapping->wb_err, err);
604 trace_filemap_set_wb_err(mapping, eseq);
606 EXPORT_SYMBOL(__filemap_set_wb_err);
609 * file_check_and_advance_wb_err - report wb error (if any) that was previously
610 * and advance wb_err to current one
611 * @file: struct file on which the error is being reported
613 * When userland calls fsync (or something like nfsd does the equivalent), we
614 * want to report any writeback errors that occurred since the last fsync (or
615 * since the file was opened if there haven't been any).
617 * Grab the wb_err from the mapping. If it matches what we have in the file,
618 * then just quickly return 0. The file is all caught up.
620 * If it doesn't match, then take the mapping value, set the "seen" flag in
621 * it and try to swap it into place. If it works, or another task beat us
622 * to it with the new value, then update the f_wb_err and return the error
623 * portion. The error at this point must be reported via proper channels
624 * (a'la fsync, or NFS COMMIT operation, etc.).
626 * While we handle mapping->wb_err with atomic operations, the f_wb_err
627 * value is protected by the f_lock since we must ensure that it reflects
628 * the latest value swapped in for this file descriptor.
630 int file_check_and_advance_wb_err(struct file *file)
633 errseq_t old = READ_ONCE(file->f_wb_err);
634 struct address_space *mapping = file->f_mapping;
636 /* Locklessly handle the common case where nothing has changed */
637 if (errseq_check(&mapping->wb_err, old)) {
638 /* Something changed, must use slow path */
639 spin_lock(&file->f_lock);
640 old = file->f_wb_err;
641 err = errseq_check_and_advance(&mapping->wb_err,
643 trace_file_check_and_advance_wb_err(file, old);
644 spin_unlock(&file->f_lock);
648 * We're mostly using this function as a drop in replacement for
649 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
650 * that the legacy code would have had on these flags.
652 clear_bit(AS_EIO, &mapping->flags);
653 clear_bit(AS_ENOSPC, &mapping->flags);
656 EXPORT_SYMBOL(file_check_and_advance_wb_err);
659 * file_write_and_wait_range - write out & wait on a file range
660 * @file: file pointing to address_space with pages
661 * @lstart: offset in bytes where the range starts
662 * @lend: offset in bytes where the range ends (inclusive)
664 * Write out and wait upon file offsets lstart->lend, inclusive.
666 * Note that @lend is inclusive (describes the last byte to be written) so
667 * that this function can be used to write to the very end-of-file (end = -1).
669 * After writing out and waiting on the data, we check and advance the
670 * f_wb_err cursor to the latest value, and return any errors detected there.
672 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
675 struct address_space *mapping = file->f_mapping;
677 if (mapping_needs_writeback(mapping)) {
678 err = __filemap_fdatawrite_range(mapping, lstart, lend,
680 /* See comment of filemap_write_and_wait() */
682 __filemap_fdatawait_range(mapping, lstart, lend);
684 err2 = file_check_and_advance_wb_err(file);
689 EXPORT_SYMBOL(file_write_and_wait_range);
692 * replace_page_cache_page - replace a pagecache page with a new one
693 * @old: page to be replaced
694 * @new: page to replace with
695 * @gfp_mask: allocation mode
697 * This function replaces a page in the pagecache with a new one. On
698 * success it acquires the pagecache reference for the new page and
699 * drops it for the old page. Both the old and new pages must be
700 * locked. This function does not add the new page to the LRU, the
701 * caller must do that.
703 * The remove + add is atomic. The only way this function can fail is
704 * memory allocation failure.
706 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
710 VM_BUG_ON_PAGE(!PageLocked(old), old);
711 VM_BUG_ON_PAGE(!PageLocked(new), new);
712 VM_BUG_ON_PAGE(new->mapping, new);
714 error = radix_tree_preload(gfp_mask & GFP_RECLAIM_MASK);
716 struct address_space *mapping = old->mapping;
717 void (*freepage)(struct page *);
720 pgoff_t offset = old->index;
721 freepage = mapping->a_ops->freepage;
724 new->mapping = mapping;
727 spin_lock_irqsave(&mapping->tree_lock, flags);
728 __delete_from_page_cache(old, NULL);
729 error = page_cache_tree_insert(mapping, new, NULL);
733 * hugetlb pages do not participate in page cache accounting.
736 __inc_node_page_state(new, NR_FILE_PAGES);
737 if (PageSwapBacked(new))
738 __inc_node_page_state(new, NR_SHMEM);
739 spin_unlock_irqrestore(&mapping->tree_lock, flags);
740 mem_cgroup_migrate(old, new);
741 radix_tree_preload_end();
749 EXPORT_SYMBOL_GPL(replace_page_cache_page);
751 static int __add_to_page_cache_locked(struct page *page,
752 struct address_space *mapping,
753 pgoff_t offset, gfp_t gfp_mask,
756 int huge = PageHuge(page);
757 struct mem_cgroup *memcg;
760 VM_BUG_ON_PAGE(!PageLocked(page), page);
761 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
764 error = mem_cgroup_try_charge(page, current->mm,
765 gfp_mask, &memcg, false);
770 error = radix_tree_maybe_preload(gfp_mask & GFP_RECLAIM_MASK);
773 mem_cgroup_cancel_charge(page, memcg, false);
778 page->mapping = mapping;
779 page->index = offset;
781 spin_lock_irq(&mapping->tree_lock);
782 error = page_cache_tree_insert(mapping, page, shadowp);
783 radix_tree_preload_end();
787 /* hugetlb pages do not participate in page cache accounting. */
789 __inc_node_page_state(page, NR_FILE_PAGES);
790 spin_unlock_irq(&mapping->tree_lock);
792 mem_cgroup_commit_charge(page, memcg, false, false);
793 trace_mm_filemap_add_to_page_cache(page);
796 page->mapping = NULL;
797 /* Leave page->index set: truncation relies upon it */
798 spin_unlock_irq(&mapping->tree_lock);
800 mem_cgroup_cancel_charge(page, memcg, false);
806 * add_to_page_cache_locked - add a locked page to the pagecache
808 * @mapping: the page's address_space
809 * @offset: page index
810 * @gfp_mask: page allocation mode
812 * This function is used to add a page to the pagecache. It must be locked.
813 * This function does not add the page to the LRU. The caller must do that.
815 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
816 pgoff_t offset, gfp_t gfp_mask)
818 return __add_to_page_cache_locked(page, mapping, offset,
821 EXPORT_SYMBOL(add_to_page_cache_locked);
823 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
824 pgoff_t offset, gfp_t gfp_mask)
829 __SetPageLocked(page);
830 ret = __add_to_page_cache_locked(page, mapping, offset,
833 __ClearPageLocked(page);
836 * The page might have been evicted from cache only
837 * recently, in which case it should be activated like
838 * any other repeatedly accessed page.
839 * The exception is pages getting rewritten; evicting other
840 * data from the working set, only to cache data that will
841 * get overwritten with something else, is a waste of memory.
843 if (!(gfp_mask & __GFP_WRITE) &&
844 shadow && workingset_refault(shadow)) {
846 workingset_activation(page);
848 ClearPageActive(page);
853 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
856 struct page *__page_cache_alloc(gfp_t gfp)
861 if (cpuset_do_page_mem_spread()) {
862 unsigned int cpuset_mems_cookie;
864 cpuset_mems_cookie = read_mems_allowed_begin();
865 n = cpuset_mem_spread_node();
866 page = __alloc_pages_node(n, gfp, 0);
867 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
871 return alloc_pages(gfp, 0);
873 EXPORT_SYMBOL(__page_cache_alloc);
877 * In order to wait for pages to become available there must be
878 * waitqueues associated with pages. By using a hash table of
879 * waitqueues where the bucket discipline is to maintain all
880 * waiters on the same queue and wake all when any of the pages
881 * become available, and for the woken contexts to check to be
882 * sure the appropriate page became available, this saves space
883 * at a cost of "thundering herd" phenomena during rare hash
886 #define PAGE_WAIT_TABLE_BITS 8
887 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
888 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
890 static wait_queue_head_t *page_waitqueue(struct page *page)
892 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
895 void __init pagecache_init(void)
899 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
900 init_waitqueue_head(&page_wait_table[i]);
902 page_writeback_init();
905 /* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
906 struct wait_page_key {
912 struct wait_page_queue {
915 wait_queue_entry_t wait;
918 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
920 struct wait_page_key *key = arg;
921 struct wait_page_queue *wait_page
922 = container_of(wait, struct wait_page_queue, wait);
924 if (wait_page->page != key->page)
928 if (wait_page->bit_nr != key->bit_nr)
931 /* Stop walking if it's locked */
932 if (test_bit(key->bit_nr, &key->page->flags))
935 return autoremove_wake_function(wait, mode, sync, key);
938 static void wake_up_page_bit(struct page *page, int bit_nr)
940 wait_queue_head_t *q = page_waitqueue(page);
941 struct wait_page_key key;
943 wait_queue_entry_t bookmark;
950 bookmark.private = NULL;
951 bookmark.func = NULL;
952 INIT_LIST_HEAD(&bookmark.entry);
954 spin_lock_irqsave(&q->lock, flags);
955 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
957 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
959 * Take a breather from holding the lock,
960 * allow pages that finish wake up asynchronously
961 * to acquire the lock and remove themselves
964 spin_unlock_irqrestore(&q->lock, flags);
966 spin_lock_irqsave(&q->lock, flags);
967 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
971 * It is possible for other pages to have collided on the waitqueue
972 * hash, so in that case check for a page match. That prevents a long-
975 * It is still possible to miss a case here, when we woke page waiters
976 * and removed them from the waitqueue, but there are still other
979 if (!waitqueue_active(q) || !key.page_match) {
980 ClearPageWaiters(page);
982 * It's possible to miss clearing Waiters here, when we woke
983 * our page waiters, but the hashed waitqueue has waiters for
986 * That's okay, it's a rare case. The next waker will clear it.
989 spin_unlock_irqrestore(&q->lock, flags);
992 static void wake_up_page(struct page *page, int bit)
994 if (!PageWaiters(page))
996 wake_up_page_bit(page, bit);
999 static inline int wait_on_page_bit_common(wait_queue_head_t *q,
1000 struct page *page, int bit_nr, int state, bool lock)
1002 struct wait_page_queue wait_page;
1003 wait_queue_entry_t *wait = &wait_page.wait;
1007 wait->flags = lock ? WQ_FLAG_EXCLUSIVE : 0;
1008 wait->func = wake_page_function;
1009 wait_page.page = page;
1010 wait_page.bit_nr = bit_nr;
1013 spin_lock_irq(&q->lock);
1015 if (likely(list_empty(&wait->entry))) {
1016 __add_wait_queue_entry_tail(q, wait);
1017 SetPageWaiters(page);
1020 set_current_state(state);
1022 spin_unlock_irq(&q->lock);
1024 if (likely(test_bit(bit_nr, &page->flags))) {
1029 if (!test_and_set_bit_lock(bit_nr, &page->flags))
1032 if (!test_bit(bit_nr, &page->flags))
1036 if (unlikely(signal_pending_state(state, current))) {
1042 finish_wait(q, wait);
1045 * A signal could leave PageWaiters set. Clearing it here if
1046 * !waitqueue_active would be possible (by open-coding finish_wait),
1047 * but still fail to catch it in the case of wait hash collision. We
1048 * already can fail to clear wait hash collision cases, so don't
1049 * bother with signals either.
1055 void wait_on_page_bit(struct page *page, int bit_nr)
1057 wait_queue_head_t *q = page_waitqueue(page);
1058 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, false);
1060 EXPORT_SYMBOL(wait_on_page_bit);
1062 int wait_on_page_bit_killable(struct page *page, int bit_nr)
1064 wait_queue_head_t *q = page_waitqueue(page);
1065 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, false);
1069 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1070 * @page: Page defining the wait queue of interest
1071 * @waiter: Waiter to add to the queue
1073 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1075 void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1077 wait_queue_head_t *q = page_waitqueue(page);
1078 unsigned long flags;
1080 spin_lock_irqsave(&q->lock, flags);
1081 __add_wait_queue_entry_tail(q, waiter);
1082 SetPageWaiters(page);
1083 spin_unlock_irqrestore(&q->lock, flags);
1085 EXPORT_SYMBOL_GPL(add_page_wait_queue);
1087 #ifndef clear_bit_unlock_is_negative_byte
1090 * PG_waiters is the high bit in the same byte as PG_lock.
1092 * On x86 (and on many other architectures), we can clear PG_lock and
1093 * test the sign bit at the same time. But if the architecture does
1094 * not support that special operation, we just do this all by hand
1097 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1098 * being cleared, but a memory barrier should be unneccssary since it is
1099 * in the same byte as PG_locked.
1101 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1103 clear_bit_unlock(nr, mem);
1104 /* smp_mb__after_atomic(); */
1105 return test_bit(PG_waiters, mem);
1111 * unlock_page - unlock a locked page
1114 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1115 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1116 * mechanism between PageLocked pages and PageWriteback pages is shared.
1117 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1119 * Note that this depends on PG_waiters being the sign bit in the byte
1120 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1121 * clear the PG_locked bit and test PG_waiters at the same time fairly
1122 * portably (architectures that do LL/SC can test any bit, while x86 can
1123 * test the sign bit).
1125 void unlock_page(struct page *page)
1127 BUILD_BUG_ON(PG_waiters != 7);
1128 page = compound_head(page);
1129 VM_BUG_ON_PAGE(!PageLocked(page), page);
1130 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1131 wake_up_page_bit(page, PG_locked);
1133 EXPORT_SYMBOL(unlock_page);
1136 * end_page_writeback - end writeback against a page
1139 void end_page_writeback(struct page *page)
1142 * TestClearPageReclaim could be used here but it is an atomic
1143 * operation and overkill in this particular case. Failing to
1144 * shuffle a page marked for immediate reclaim is too mild to
1145 * justify taking an atomic operation penalty at the end of
1146 * ever page writeback.
1148 if (PageReclaim(page)) {
1149 ClearPageReclaim(page);
1150 rotate_reclaimable_page(page);
1153 if (!test_clear_page_writeback(page))
1156 smp_mb__after_atomic();
1157 wake_up_page(page, PG_writeback);
1159 EXPORT_SYMBOL(end_page_writeback);
1162 * After completing I/O on a page, call this routine to update the page
1163 * flags appropriately
1165 void page_endio(struct page *page, bool is_write, int err)
1169 SetPageUptodate(page);
1171 ClearPageUptodate(page);
1177 struct address_space *mapping;
1180 mapping = page_mapping(page);
1182 mapping_set_error(mapping, err);
1184 end_page_writeback(page);
1187 EXPORT_SYMBOL_GPL(page_endio);
1190 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1191 * @__page: the page to lock
1193 void __lock_page(struct page *__page)
1195 struct page *page = compound_head(__page);
1196 wait_queue_head_t *q = page_waitqueue(page);
1197 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, true);
1199 EXPORT_SYMBOL(__lock_page);
1201 int __lock_page_killable(struct page *__page)
1203 struct page *page = compound_head(__page);
1204 wait_queue_head_t *q = page_waitqueue(page);
1205 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE, true);
1207 EXPORT_SYMBOL_GPL(__lock_page_killable);
1211 * 1 - page is locked; mmap_sem is still held.
1212 * 0 - page is not locked.
1213 * mmap_sem has been released (up_read()), unless flags had both
1214 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1215 * which case mmap_sem is still held.
1217 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1218 * with the page locked and the mmap_sem unperturbed.
1220 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1223 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1225 * CAUTION! In this case, mmap_sem is not released
1226 * even though return 0.
1228 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1231 up_read(&mm->mmap_sem);
1232 if (flags & FAULT_FLAG_KILLABLE)
1233 wait_on_page_locked_killable(page);
1235 wait_on_page_locked(page);
1238 if (flags & FAULT_FLAG_KILLABLE) {
1241 ret = __lock_page_killable(page);
1243 up_read(&mm->mmap_sem);
1253 * page_cache_next_hole - find the next hole (not-present entry)
1256 * @max_scan: maximum range to search
1258 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
1259 * lowest indexed hole.
1261 * Returns: the index of the hole if found, otherwise returns an index
1262 * outside of the set specified (in which case 'return - index >=
1263 * max_scan' will be true). In rare cases of index wrap-around, 0 will
1266 * page_cache_next_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 5, then subsequently a hole is created at
1270 * index 10, page_cache_next_hole covering both indexes may return 10
1271 * if called under rcu_read_lock.
1273 pgoff_t page_cache_next_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))
1291 EXPORT_SYMBOL(page_cache_next_hole);
1294 * page_cache_prev_hole - find the prev hole (not-present entry)
1297 * @max_scan: maximum range to search
1299 * Search backwards in the range [max(index-max_scan+1, 0), index] for
1302 * Returns: the index of the hole if found, otherwise returns an index
1303 * outside of the set specified (in which case 'index - return >=
1304 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
1307 * page_cache_prev_hole may be called under rcu_read_lock. However,
1308 * like radix_tree_gang_lookup, this will not atomically search a
1309 * snapshot of the tree at a single point in time. For example, if a
1310 * hole is created at index 10, then subsequently a hole is created at
1311 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1312 * called under rcu_read_lock.
1314 pgoff_t page_cache_prev_hole(struct address_space *mapping,
1315 pgoff_t index, unsigned long max_scan)
1319 for (i = 0; i < max_scan; i++) {
1322 page = radix_tree_lookup(&mapping->page_tree, index);
1323 if (!page || radix_tree_exceptional_entry(page))
1326 if (index == ULONG_MAX)
1332 EXPORT_SYMBOL(page_cache_prev_hole);
1335 * find_get_entry - find and get a page cache entry
1336 * @mapping: the address_space to search
1337 * @offset: the page cache index
1339 * Looks up the page cache slot at @mapping & @offset. If there is a
1340 * page cache page, it is returned with an increased refcount.
1342 * If the slot holds a shadow entry of a previously evicted page, or a
1343 * swap entry from shmem/tmpfs, it is returned.
1345 * Otherwise, %NULL is returned.
1347 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1350 struct page *head, *page;
1355 pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
1357 page = radix_tree_deref_slot(pagep);
1358 if (unlikely(!page))
1360 if (radix_tree_exception(page)) {
1361 if (radix_tree_deref_retry(page))
1364 * A shadow entry of a recently evicted page,
1365 * or a swap entry from shmem/tmpfs. Return
1366 * it without attempting to raise page count.
1371 head = compound_head(page);
1372 if (!page_cache_get_speculative(head))
1375 /* The page was split under us? */
1376 if (compound_head(page) != head) {
1382 * Has the page moved?
1383 * This is part of the lockless pagecache protocol. See
1384 * include/linux/pagemap.h for details.
1386 if (unlikely(page != *pagep)) {
1396 EXPORT_SYMBOL(find_get_entry);
1399 * find_lock_entry - locate, pin and lock a page cache entry
1400 * @mapping: the address_space to search
1401 * @offset: the page cache index
1403 * Looks up the page cache slot at @mapping & @offset. If there is a
1404 * page cache page, it is returned locked and with an increased
1407 * If the slot holds a shadow entry of a previously evicted page, or a
1408 * swap entry from shmem/tmpfs, it is returned.
1410 * Otherwise, %NULL is returned.
1412 * find_lock_entry() may sleep.
1414 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1419 page = find_get_entry(mapping, offset);
1420 if (page && !radix_tree_exception(page)) {
1422 /* Has the page been truncated? */
1423 if (unlikely(page_mapping(page) != mapping)) {
1428 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
1432 EXPORT_SYMBOL(find_lock_entry);
1435 * pagecache_get_page - find and get a page reference
1436 * @mapping: the address_space to search
1437 * @offset: the page index
1438 * @fgp_flags: PCG flags
1439 * @gfp_mask: gfp mask to use for the page cache data page allocation
1441 * Looks up the page cache slot at @mapping & @offset.
1443 * PCG flags modify how the page is returned.
1445 * @fgp_flags can be:
1447 * - FGP_ACCESSED: the page will be marked accessed
1448 * - FGP_LOCK: Page is return locked
1449 * - FGP_CREAT: If page is not present then a new page is allocated using
1450 * @gfp_mask and added to the page cache and the VM's LRU
1451 * list. The page is returned locked and with an increased
1452 * refcount. Otherwise, NULL is returned.
1454 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1455 * if the GFP flags specified for FGP_CREAT are atomic.
1457 * If there is a page cache page, it is returned with an increased refcount.
1459 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1460 int fgp_flags, gfp_t gfp_mask)
1465 page = find_get_entry(mapping, offset);
1466 if (radix_tree_exceptional_entry(page))
1471 if (fgp_flags & FGP_LOCK) {
1472 if (fgp_flags & FGP_NOWAIT) {
1473 if (!trylock_page(page)) {
1481 /* Has the page been truncated? */
1482 if (unlikely(page->mapping != mapping)) {
1487 VM_BUG_ON_PAGE(page->index != offset, page);
1490 if (page && (fgp_flags & FGP_ACCESSED))
1491 mark_page_accessed(page);
1494 if (!page && (fgp_flags & FGP_CREAT)) {
1496 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1497 gfp_mask |= __GFP_WRITE;
1498 if (fgp_flags & FGP_NOFS)
1499 gfp_mask &= ~__GFP_FS;
1501 page = __page_cache_alloc(gfp_mask);
1505 if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
1506 fgp_flags |= FGP_LOCK;
1508 /* Init accessed so avoid atomic mark_page_accessed later */
1509 if (fgp_flags & FGP_ACCESSED)
1510 __SetPageReferenced(page);
1512 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
1513 if (unlikely(err)) {
1523 EXPORT_SYMBOL(pagecache_get_page);
1526 * find_get_entries - gang pagecache lookup
1527 * @mapping: The address_space to search
1528 * @start: The starting page cache index
1529 * @nr_entries: The maximum number of entries
1530 * @entries: Where the resulting entries are placed
1531 * @indices: The cache indices corresponding to the entries in @entries
1533 * find_get_entries() will search for and return a group of up to
1534 * @nr_entries entries in the mapping. The entries are placed at
1535 * @entries. find_get_entries() takes a reference against any actual
1538 * The search returns a group of mapping-contiguous page cache entries
1539 * with ascending indexes. There may be holes in the indices due to
1540 * not-present pages.
1542 * Any shadow entries of evicted pages, or swap entries from
1543 * shmem/tmpfs, are included in the returned array.
1545 * find_get_entries() returns the number of pages and shadow entries
1548 unsigned find_get_entries(struct address_space *mapping,
1549 pgoff_t start, unsigned int nr_entries,
1550 struct page **entries, pgoff_t *indices)
1553 unsigned int ret = 0;
1554 struct radix_tree_iter iter;
1560 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, start) {
1561 struct page *head, *page;
1563 page = radix_tree_deref_slot(slot);
1564 if (unlikely(!page))
1566 if (radix_tree_exception(page)) {
1567 if (radix_tree_deref_retry(page)) {
1568 slot = radix_tree_iter_retry(&iter);
1572 * A shadow entry of a recently evicted page, a swap
1573 * entry from shmem/tmpfs or a DAX entry. Return it
1574 * without attempting to raise page count.
1579 head = compound_head(page);
1580 if (!page_cache_get_speculative(head))
1583 /* The page was split under us? */
1584 if (compound_head(page) != head) {
1589 /* Has the page moved? */
1590 if (unlikely(page != *slot)) {
1595 indices[ret] = iter.index;
1596 entries[ret] = page;
1597 if (++ret == nr_entries)
1605 * find_get_pages_range - gang pagecache lookup
1606 * @mapping: The address_space to search
1607 * @start: The starting page index
1608 * @end: The final page index (inclusive)
1609 * @nr_pages: The maximum number of pages
1610 * @pages: Where the resulting pages are placed
1612 * find_get_pages_range() will search for and return a group of up to @nr_pages
1613 * pages in the mapping starting at index @start and up to index @end
1614 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1615 * a reference against the returned pages.
1617 * The search returns a group of mapping-contiguous pages with ascending
1618 * indexes. There may be holes in the indices due to not-present pages.
1619 * We also update @start to index the next page for the traversal.
1621 * find_get_pages_range() returns the number of pages which were found. If this
1622 * number is smaller than @nr_pages, the end of specified range has been
1625 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1626 pgoff_t end, unsigned int nr_pages,
1627 struct page **pages)
1629 struct radix_tree_iter iter;
1633 if (unlikely(!nr_pages))
1637 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter, *start) {
1638 struct page *head, *page;
1640 if (iter.index > end)
1643 page = radix_tree_deref_slot(slot);
1644 if (unlikely(!page))
1647 if (radix_tree_exception(page)) {
1648 if (radix_tree_deref_retry(page)) {
1649 slot = radix_tree_iter_retry(&iter);
1653 * A shadow entry of a recently evicted page,
1654 * or a swap entry from shmem/tmpfs. Skip
1660 head = compound_head(page);
1661 if (!page_cache_get_speculative(head))
1664 /* The page was split under us? */
1665 if (compound_head(page) != head) {
1670 /* Has the page moved? */
1671 if (unlikely(page != *slot)) {
1677 if (++ret == nr_pages) {
1678 *start = pages[ret - 1]->index + 1;
1684 * We come here when there is no page beyond @end. We take care to not
1685 * overflow the index @start as it confuses some of the callers. This
1686 * breaks the iteration when there is page at index -1 but that is
1687 * already broken anyway.
1689 if (end == (pgoff_t)-1)
1690 *start = (pgoff_t)-1;
1700 * find_get_pages_contig - gang contiguous pagecache lookup
1701 * @mapping: The address_space to search
1702 * @index: The starting page index
1703 * @nr_pages: The maximum number of pages
1704 * @pages: Where the resulting pages are placed
1706 * find_get_pages_contig() works exactly like find_get_pages(), except
1707 * that the returned number of pages are guaranteed to be contiguous.
1709 * find_get_pages_contig() returns the number of pages which were found.
1711 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1712 unsigned int nr_pages, struct page **pages)
1714 struct radix_tree_iter iter;
1716 unsigned int ret = 0;
1718 if (unlikely(!nr_pages))
1722 radix_tree_for_each_contig(slot, &mapping->page_tree, &iter, index) {
1723 struct page *head, *page;
1725 page = radix_tree_deref_slot(slot);
1726 /* The hole, there no reason to continue */
1727 if (unlikely(!page))
1730 if (radix_tree_exception(page)) {
1731 if (radix_tree_deref_retry(page)) {
1732 slot = radix_tree_iter_retry(&iter);
1736 * A shadow entry of a recently evicted page,
1737 * or a swap entry from shmem/tmpfs. Stop
1738 * looking for contiguous pages.
1743 head = compound_head(page);
1744 if (!page_cache_get_speculative(head))
1747 /* The page was split under us? */
1748 if (compound_head(page) != head) {
1753 /* Has the page moved? */
1754 if (unlikely(page != *slot)) {
1760 * must check mapping and index after taking the ref.
1761 * otherwise we can get both false positives and false
1762 * negatives, which is just confusing to the caller.
1764 if (page->mapping == NULL || page_to_pgoff(page) != iter.index) {
1770 if (++ret == nr_pages)
1776 EXPORT_SYMBOL(find_get_pages_contig);
1779 * find_get_pages_tag - find and return pages that match @tag
1780 * @mapping: the address_space to search
1781 * @index: the starting page index
1782 * @tag: the tag index
1783 * @nr_pages: the maximum number of pages
1784 * @pages: where the resulting pages are placed
1786 * Like find_get_pages, except we only return pages which are tagged with
1787 * @tag. We update @index to index the next page for the traversal.
1789 unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
1790 int tag, unsigned int nr_pages, struct page **pages)
1792 struct radix_tree_iter iter;
1796 if (unlikely(!nr_pages))
1800 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1801 &iter, *index, tag) {
1802 struct page *head, *page;
1804 page = radix_tree_deref_slot(slot);
1805 if (unlikely(!page))
1808 if (radix_tree_exception(page)) {
1809 if (radix_tree_deref_retry(page)) {
1810 slot = radix_tree_iter_retry(&iter);
1814 * A shadow entry of a recently evicted page.
1816 * Those entries should never be tagged, but
1817 * this tree walk is lockless and the tags are
1818 * looked up in bulk, one radix tree node at a
1819 * time, so there is a sizable window for page
1820 * reclaim to evict a page we saw tagged.
1827 head = compound_head(page);
1828 if (!page_cache_get_speculative(head))
1831 /* The page was split under us? */
1832 if (compound_head(page) != head) {
1837 /* Has the page moved? */
1838 if (unlikely(page != *slot)) {
1844 if (++ret == nr_pages)
1851 *index = pages[ret - 1]->index + 1;
1855 EXPORT_SYMBOL(find_get_pages_tag);
1858 * find_get_entries_tag - find and return entries that match @tag
1859 * @mapping: the address_space to search
1860 * @start: the starting page cache index
1861 * @tag: the tag index
1862 * @nr_entries: the maximum number of entries
1863 * @entries: where the resulting entries are placed
1864 * @indices: the cache indices corresponding to the entries in @entries
1866 * Like find_get_entries, except we only return entries which are tagged with
1869 unsigned find_get_entries_tag(struct address_space *mapping, pgoff_t start,
1870 int tag, unsigned int nr_entries,
1871 struct page **entries, pgoff_t *indices)
1874 unsigned int ret = 0;
1875 struct radix_tree_iter iter;
1881 radix_tree_for_each_tagged(slot, &mapping->page_tree,
1882 &iter, start, tag) {
1883 struct page *head, *page;
1885 page = radix_tree_deref_slot(slot);
1886 if (unlikely(!page))
1888 if (radix_tree_exception(page)) {
1889 if (radix_tree_deref_retry(page)) {
1890 slot = radix_tree_iter_retry(&iter);
1895 * A shadow entry of a recently evicted page, a swap
1896 * entry from shmem/tmpfs or a DAX entry. Return it
1897 * without attempting to raise page count.
1902 head = compound_head(page);
1903 if (!page_cache_get_speculative(head))
1906 /* The page was split under us? */
1907 if (compound_head(page) != head) {
1912 /* Has the page moved? */
1913 if (unlikely(page != *slot)) {
1918 indices[ret] = iter.index;
1919 entries[ret] = page;
1920 if (++ret == nr_entries)
1926 EXPORT_SYMBOL(find_get_entries_tag);
1929 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
1930 * a _large_ part of the i/o request. Imagine the worst scenario:
1932 * ---R__________________________________________B__________
1933 * ^ reading here ^ bad block(assume 4k)
1935 * read(R) => miss => readahead(R...B) => media error => frustrating retries
1936 * => failing the whole request => read(R) => read(R+1) =>
1937 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
1938 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
1939 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
1941 * It is going insane. Fix it by quickly scaling down the readahead size.
1943 static void shrink_readahead_size_eio(struct file *filp,
1944 struct file_ra_state *ra)
1950 * generic_file_buffered_read - generic file read routine
1951 * @iocb: the iocb to read
1952 * @iter: data destination
1953 * @written: already copied
1955 * This is a generic file read routine, and uses the
1956 * mapping->a_ops->readpage() function for the actual low-level stuff.
1958 * This is really ugly. But the goto's actually try to clarify some
1959 * of the logic when it comes to error handling etc.
1961 static ssize_t generic_file_buffered_read(struct kiocb *iocb,
1962 struct iov_iter *iter, ssize_t written)
1964 struct file *filp = iocb->ki_filp;
1965 struct address_space *mapping = filp->f_mapping;
1966 struct inode *inode = mapping->host;
1967 struct file_ra_state *ra = &filp->f_ra;
1968 loff_t *ppos = &iocb->ki_pos;
1972 unsigned long offset; /* offset into pagecache page */
1973 unsigned int prev_offset;
1976 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
1978 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
1980 index = *ppos >> PAGE_SHIFT;
1981 prev_index = ra->prev_pos >> PAGE_SHIFT;
1982 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
1983 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
1984 offset = *ppos & ~PAGE_MASK;
1990 unsigned long nr, ret;
1994 if (fatal_signal_pending(current)) {
1999 page = find_get_page(mapping, index);
2001 if (iocb->ki_flags & IOCB_NOWAIT)
2003 page_cache_sync_readahead(mapping,
2005 index, last_index - index);
2006 page = find_get_page(mapping, index);
2007 if (unlikely(page == NULL))
2008 goto no_cached_page;
2010 if (PageReadahead(page)) {
2011 page_cache_async_readahead(mapping,
2013 index, last_index - index);
2015 if (!PageUptodate(page)) {
2016 if (iocb->ki_flags & IOCB_NOWAIT) {
2022 * See comment in do_read_cache_page on why
2023 * wait_on_page_locked is used to avoid unnecessarily
2024 * serialisations and why it's safe.
2026 error = wait_on_page_locked_killable(page);
2027 if (unlikely(error))
2028 goto readpage_error;
2029 if (PageUptodate(page))
2032 if (inode->i_blkbits == PAGE_SHIFT ||
2033 !mapping->a_ops->is_partially_uptodate)
2034 goto page_not_up_to_date;
2035 /* pipes can't handle partially uptodate pages */
2036 if (unlikely(iter->type & ITER_PIPE))
2037 goto page_not_up_to_date;
2038 if (!trylock_page(page))
2039 goto page_not_up_to_date;
2040 /* Did it get truncated before we got the lock? */
2042 goto page_not_up_to_date_locked;
2043 if (!mapping->a_ops->is_partially_uptodate(page,
2044 offset, iter->count))
2045 goto page_not_up_to_date_locked;
2050 * i_size must be checked after we know the page is Uptodate.
2052 * Checking i_size after the check allows us to calculate
2053 * the correct value for "nr", which means the zero-filled
2054 * part of the page is not copied back to userspace (unless
2055 * another truncate extends the file - this is desired though).
2058 isize = i_size_read(inode);
2059 end_index = (isize - 1) >> PAGE_SHIFT;
2060 if (unlikely(!isize || index > end_index)) {
2065 /* nr is the maximum number of bytes to copy from this page */
2067 if (index == end_index) {
2068 nr = ((isize - 1) & ~PAGE_MASK) + 1;
2076 /* If users can be writing to this page using arbitrary
2077 * virtual addresses, take care about potential aliasing
2078 * before reading the page on the kernel side.
2080 if (mapping_writably_mapped(mapping))
2081 flush_dcache_page(page);
2084 * When a sequential read accesses a page several times,
2085 * only mark it as accessed the first time.
2087 if (prev_index != index || offset != prev_offset)
2088 mark_page_accessed(page);
2092 * Ok, we have the page, and it's up-to-date, so
2093 * now we can copy it to user space...
2096 ret = copy_page_to_iter(page, offset, nr, iter);
2098 index += offset >> PAGE_SHIFT;
2099 offset &= ~PAGE_MASK;
2100 prev_offset = offset;
2104 if (!iov_iter_count(iter))
2112 page_not_up_to_date:
2113 /* Get exclusive access to the page ... */
2114 error = lock_page_killable(page);
2115 if (unlikely(error))
2116 goto readpage_error;
2118 page_not_up_to_date_locked:
2119 /* Did it get truncated before we got the lock? */
2120 if (!page->mapping) {
2126 /* Did somebody else fill it already? */
2127 if (PageUptodate(page)) {
2134 * A previous I/O error may have been due to temporary
2135 * failures, eg. multipath errors.
2136 * PG_error will be set again if readpage fails.
2138 ClearPageError(page);
2139 /* Start the actual read. The read will unlock the page. */
2140 error = mapping->a_ops->readpage(filp, page);
2142 if (unlikely(error)) {
2143 if (error == AOP_TRUNCATED_PAGE) {
2148 goto readpage_error;
2151 if (!PageUptodate(page)) {
2152 error = lock_page_killable(page);
2153 if (unlikely(error))
2154 goto readpage_error;
2155 if (!PageUptodate(page)) {
2156 if (page->mapping == NULL) {
2158 * invalidate_mapping_pages got it
2165 shrink_readahead_size_eio(filp, ra);
2167 goto readpage_error;
2175 /* UHHUH! A synchronous read error occurred. Report it */
2181 * Ok, it wasn't cached, so we need to create a new
2184 page = page_cache_alloc_cold(mapping);
2189 error = add_to_page_cache_lru(page, mapping, index,
2190 mapping_gfp_constraint(mapping, GFP_KERNEL));
2193 if (error == -EEXIST) {
2205 ra->prev_pos = prev_index;
2206 ra->prev_pos <<= PAGE_SHIFT;
2207 ra->prev_pos |= prev_offset;
2209 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
2210 file_accessed(filp);
2211 return written ? written : error;
2215 * generic_file_read_iter - generic filesystem read routine
2216 * @iocb: kernel I/O control block
2217 * @iter: destination for the data read
2219 * This is the "read_iter()" routine for all filesystems
2220 * that can use the page cache directly.
2223 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2225 size_t count = iov_iter_count(iter);
2229 goto out; /* skip atime */
2231 if (iocb->ki_flags & IOCB_DIRECT) {
2232 struct file *file = iocb->ki_filp;
2233 struct address_space *mapping = file->f_mapping;
2234 struct inode *inode = mapping->host;
2237 size = i_size_read(inode);
2238 if (iocb->ki_flags & IOCB_NOWAIT) {
2239 if (filemap_range_has_page(mapping, iocb->ki_pos,
2240 iocb->ki_pos + count - 1))
2243 retval = filemap_write_and_wait_range(mapping,
2245 iocb->ki_pos + count - 1);
2250 file_accessed(file);
2252 retval = mapping->a_ops->direct_IO(iocb, iter);
2254 iocb->ki_pos += retval;
2257 iov_iter_revert(iter, count - iov_iter_count(iter));
2260 * Btrfs can have a short DIO read if we encounter
2261 * compressed extents, so if there was an error, or if
2262 * we've already read everything we wanted to, or if
2263 * there was a short read because we hit EOF, go ahead
2264 * and return. Otherwise fallthrough to buffered io for
2265 * the rest of the read. Buffered reads will not work for
2266 * DAX files, so don't bother trying.
2268 if (retval < 0 || !count || iocb->ki_pos >= size ||
2273 retval = generic_file_buffered_read(iocb, iter, retval);
2277 EXPORT_SYMBOL(generic_file_read_iter);
2281 * page_cache_read - adds requested page to the page cache if not already there
2282 * @file: file to read
2283 * @offset: page index
2284 * @gfp_mask: memory allocation flags
2286 * This adds the requested page to the page cache if it isn't already there,
2287 * and schedules an I/O to read in its contents from disk.
2289 static int page_cache_read(struct file *file, pgoff_t offset, gfp_t gfp_mask)
2291 struct address_space *mapping = file->f_mapping;
2296 page = __page_cache_alloc(gfp_mask|__GFP_COLD);
2300 ret = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
2302 ret = mapping->a_ops->readpage(file, page);
2303 else if (ret == -EEXIST)
2304 ret = 0; /* losing race to add is OK */
2308 } while (ret == AOP_TRUNCATED_PAGE);
2313 #define MMAP_LOTSAMISS (100)
2316 * Synchronous readahead happens when we don't even find
2317 * a page in the page cache at all.
2319 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
2320 struct file_ra_state *ra,
2324 struct address_space *mapping = file->f_mapping;
2326 /* If we don't want any read-ahead, don't bother */
2327 if (vma->vm_flags & VM_RAND_READ)
2332 if (vma->vm_flags & VM_SEQ_READ) {
2333 page_cache_sync_readahead(mapping, ra, file, offset,
2338 /* Avoid banging the cache line if not needed */
2339 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
2343 * Do we miss much more than hit in this file? If so,
2344 * stop bothering with read-ahead. It will only hurt.
2346 if (ra->mmap_miss > MMAP_LOTSAMISS)
2352 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2353 ra->size = ra->ra_pages;
2354 ra->async_size = ra->ra_pages / 4;
2355 ra_submit(ra, mapping, file);
2359 * Asynchronous readahead happens when we find the page and PG_readahead,
2360 * so we want to possibly extend the readahead further..
2362 static void do_async_mmap_readahead(struct vm_area_struct *vma,
2363 struct file_ra_state *ra,
2368 struct address_space *mapping = file->f_mapping;
2370 /* If we don't want any read-ahead, don't bother */
2371 if (vma->vm_flags & VM_RAND_READ)
2373 if (ra->mmap_miss > 0)
2375 if (PageReadahead(page))
2376 page_cache_async_readahead(mapping, ra, file,
2377 page, offset, ra->ra_pages);
2381 * filemap_fault - read in file data for page fault handling
2382 * @vmf: struct vm_fault containing details of the fault
2384 * filemap_fault() is invoked via the vma operations vector for a
2385 * mapped memory region to read in file data during a page fault.
2387 * The goto's are kind of ugly, but this streamlines the normal case of having
2388 * it in the page cache, and handles the special cases reasonably without
2389 * having a lot of duplicated code.
2391 * vma->vm_mm->mmap_sem must be held on entry.
2393 * If our return value has VM_FAULT_RETRY set, it's because
2394 * lock_page_or_retry() returned 0.
2395 * The mmap_sem has usually been released in this case.
2396 * See __lock_page_or_retry() for the exception.
2398 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2399 * has not been released.
2401 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2403 int filemap_fault(struct vm_fault *vmf)
2406 struct file *file = vmf->vma->vm_file;
2407 struct address_space *mapping = file->f_mapping;
2408 struct file_ra_state *ra = &file->f_ra;
2409 struct inode *inode = mapping->host;
2410 pgoff_t offset = vmf->pgoff;
2415 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2416 if (unlikely(offset >= max_off))
2417 return VM_FAULT_SIGBUS;
2420 * Do we have something in the page cache already?
2422 page = find_get_page(mapping, offset);
2423 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
2425 * We found the page, so try async readahead before
2426 * waiting for the lock.
2428 do_async_mmap_readahead(vmf->vma, ra, file, page, offset);
2430 /* No page in the page cache at all */
2431 do_sync_mmap_readahead(vmf->vma, ra, file, offset);
2432 count_vm_event(PGMAJFAULT);
2433 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
2434 ret = VM_FAULT_MAJOR;
2436 page = find_get_page(mapping, offset);
2438 goto no_cached_page;
2441 if (!lock_page_or_retry(page, vmf->vma->vm_mm, vmf->flags)) {
2443 return ret | VM_FAULT_RETRY;
2446 /* Did it get truncated? */
2447 if (unlikely(page->mapping != mapping)) {
2452 VM_BUG_ON_PAGE(page->index != offset, page);
2455 * We have a locked page in the page cache, now we need to check
2456 * that it's up-to-date. If not, it is going to be due to an error.
2458 if (unlikely(!PageUptodate(page)))
2459 goto page_not_uptodate;
2462 * Found the page and have a reference on it.
2463 * We must recheck i_size under page lock.
2465 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2466 if (unlikely(offset >= max_off)) {
2469 return VM_FAULT_SIGBUS;
2473 return ret | VM_FAULT_LOCKED;
2477 * We're only likely to ever get here if MADV_RANDOM is in
2480 error = page_cache_read(file, offset, vmf->gfp_mask);
2483 * The page we want has now been added to the page cache.
2484 * In the unlikely event that someone removed it in the
2485 * meantime, we'll just come back here and read it again.
2491 * An error return from page_cache_read can result if the
2492 * system is low on memory, or a problem occurs while trying
2495 if (error == -ENOMEM)
2496 return VM_FAULT_OOM;
2497 return VM_FAULT_SIGBUS;
2501 * Umm, take care of errors if the page isn't up-to-date.
2502 * Try to re-read it _once_. We do this synchronously,
2503 * because there really aren't any performance issues here
2504 * and we need to check for errors.
2506 ClearPageError(page);
2507 error = mapping->a_ops->readpage(file, page);
2509 wait_on_page_locked(page);
2510 if (!PageUptodate(page))
2515 if (!error || error == AOP_TRUNCATED_PAGE)
2518 /* Things didn't work out. Return zero to tell the mm layer so. */
2519 shrink_readahead_size_eio(file, ra);
2520 return VM_FAULT_SIGBUS;
2522 EXPORT_SYMBOL(filemap_fault);
2524 void filemap_map_pages(struct vm_fault *vmf,
2525 pgoff_t start_pgoff, pgoff_t end_pgoff)
2527 struct radix_tree_iter iter;
2529 struct file *file = vmf->vma->vm_file;
2530 struct address_space *mapping = file->f_mapping;
2531 pgoff_t last_pgoff = start_pgoff;
2532 unsigned long max_idx;
2533 struct page *head, *page;
2536 radix_tree_for_each_slot(slot, &mapping->page_tree, &iter,
2538 if (iter.index > end_pgoff)
2541 page = radix_tree_deref_slot(slot);
2542 if (unlikely(!page))
2544 if (radix_tree_exception(page)) {
2545 if (radix_tree_deref_retry(page)) {
2546 slot = radix_tree_iter_retry(&iter);
2552 head = compound_head(page);
2553 if (!page_cache_get_speculative(head))
2556 /* The page was split under us? */
2557 if (compound_head(page) != head) {
2562 /* Has the page moved? */
2563 if (unlikely(page != *slot)) {
2568 if (!PageUptodate(page) ||
2569 PageReadahead(page) ||
2572 if (!trylock_page(page))
2575 if (page->mapping != mapping || !PageUptodate(page))
2578 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2579 if (page->index >= max_idx)
2582 if (file->f_ra.mmap_miss > 0)
2583 file->f_ra.mmap_miss--;
2585 vmf->address += (iter.index - last_pgoff) << PAGE_SHIFT;
2587 vmf->pte += iter.index - last_pgoff;
2588 last_pgoff = iter.index;
2589 if (alloc_set_pte(vmf, NULL, page))
2598 /* Huge page is mapped? No need to proceed. */
2599 if (pmd_trans_huge(*vmf->pmd))
2601 if (iter.index == end_pgoff)
2606 EXPORT_SYMBOL(filemap_map_pages);
2608 int filemap_page_mkwrite(struct vm_fault *vmf)
2610 struct page *page = vmf->page;
2611 struct inode *inode = file_inode(vmf->vma->vm_file);
2612 int ret = VM_FAULT_LOCKED;
2614 sb_start_pagefault(inode->i_sb);
2615 file_update_time(vmf->vma->vm_file);
2617 if (page->mapping != inode->i_mapping) {
2619 ret = VM_FAULT_NOPAGE;
2623 * We mark the page dirty already here so that when freeze is in
2624 * progress, we are guaranteed that writeback during freezing will
2625 * see the dirty page and writeprotect it again.
2627 set_page_dirty(page);
2628 wait_for_stable_page(page);
2630 sb_end_pagefault(inode->i_sb);
2633 EXPORT_SYMBOL(filemap_page_mkwrite);
2635 const struct vm_operations_struct generic_file_vm_ops = {
2636 .fault = filemap_fault,
2637 .map_pages = filemap_map_pages,
2638 .page_mkwrite = filemap_page_mkwrite,
2641 /* This is used for a general mmap of a disk file */
2643 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2645 struct address_space *mapping = file->f_mapping;
2647 if (!mapping->a_ops->readpage)
2649 file_accessed(file);
2650 vma->vm_ops = &generic_file_vm_ops;
2655 * This is for filesystems which do not implement ->writepage.
2657 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2659 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2661 return generic_file_mmap(file, vma);
2664 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2668 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2672 #endif /* CONFIG_MMU */
2674 EXPORT_SYMBOL(generic_file_mmap);
2675 EXPORT_SYMBOL(generic_file_readonly_mmap);
2677 static struct page *wait_on_page_read(struct page *page)
2679 if (!IS_ERR(page)) {
2680 wait_on_page_locked(page);
2681 if (!PageUptodate(page)) {
2683 page = ERR_PTR(-EIO);
2689 static struct page *do_read_cache_page(struct address_space *mapping,
2691 int (*filler)(void *, struct page *),
2698 page = find_get_page(mapping, index);
2700 page = __page_cache_alloc(gfp | __GFP_COLD);
2702 return ERR_PTR(-ENOMEM);
2703 err = add_to_page_cache_lru(page, mapping, index, gfp);
2704 if (unlikely(err)) {
2708 /* Presumably ENOMEM for radix tree node */
2709 return ERR_PTR(err);
2713 err = filler(data, page);
2716 return ERR_PTR(err);
2719 page = wait_on_page_read(page);
2724 if (PageUptodate(page))
2728 * Page is not up to date and may be locked due one of the following
2729 * case a: Page is being filled and the page lock is held
2730 * case b: Read/write error clearing the page uptodate status
2731 * case c: Truncation in progress (page locked)
2732 * case d: Reclaim in progress
2734 * Case a, the page will be up to date when the page is unlocked.
2735 * There is no need to serialise on the page lock here as the page
2736 * is pinned so the lock gives no additional protection. Even if the
2737 * the page is truncated, the data is still valid if PageUptodate as
2738 * it's a race vs truncate race.
2739 * Case b, the page will not be up to date
2740 * Case c, the page may be truncated but in itself, the data may still
2741 * be valid after IO completes as it's a read vs truncate race. The
2742 * operation must restart if the page is not uptodate on unlock but
2743 * otherwise serialising on page lock to stabilise the mapping gives
2744 * no additional guarantees to the caller as the page lock is
2745 * released before return.
2746 * Case d, similar to truncation. If reclaim holds the page lock, it
2747 * will be a race with remove_mapping that determines if the mapping
2748 * is valid on unlock but otherwise the data is valid and there is
2749 * no need to serialise with page lock.
2751 * As the page lock gives no additional guarantee, we optimistically
2752 * wait on the page to be unlocked and check if it's up to date and
2753 * use the page if it is. Otherwise, the page lock is required to
2754 * distinguish between the different cases. The motivation is that we
2755 * avoid spurious serialisations and wakeups when multiple processes
2756 * wait on the same page for IO to complete.
2758 wait_on_page_locked(page);
2759 if (PageUptodate(page))
2762 /* Distinguish between all the cases under the safety of the lock */
2765 /* Case c or d, restart the operation */
2766 if (!page->mapping) {
2772 /* Someone else locked and filled the page in a very small window */
2773 if (PageUptodate(page)) {
2779 * A previous I/O error may have been due to temporary
2781 * Clear page error before actual read, PG_error will be
2782 * set again if read page fails.
2784 ClearPageError(page);
2788 mark_page_accessed(page);
2793 * read_cache_page - read into page cache, fill it if needed
2794 * @mapping: the page's address_space
2795 * @index: the page index
2796 * @filler: function to perform the read
2797 * @data: first arg to filler(data, page) function, often left as NULL
2799 * Read into the page cache. If a page already exists, and PageUptodate() is
2800 * not set, try to fill the page and wait for it to become unlocked.
2802 * If the page does not get brought uptodate, return -EIO.
2804 struct page *read_cache_page(struct address_space *mapping,
2806 int (*filler)(void *, struct page *),
2809 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2811 EXPORT_SYMBOL(read_cache_page);
2814 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2815 * @mapping: the page's address_space
2816 * @index: the page index
2817 * @gfp: the page allocator flags to use if allocating
2819 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2820 * any new page allocations done using the specified allocation flags.
2822 * If the page does not get brought uptodate, return -EIO.
2824 struct page *read_cache_page_gfp(struct address_space *mapping,
2828 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2830 return do_read_cache_page(mapping, index, filler, NULL, gfp);
2832 EXPORT_SYMBOL(read_cache_page_gfp);
2835 * Performs necessary checks before doing a write
2837 * Can adjust writing position or amount of bytes to write.
2838 * Returns appropriate error code that caller should return or
2839 * zero in case that write should be allowed.
2841 inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
2843 struct file *file = iocb->ki_filp;
2844 struct inode *inode = file->f_mapping->host;
2845 unsigned long limit = rlimit(RLIMIT_FSIZE);
2848 if (!iov_iter_count(from))
2851 /* FIXME: this is for backwards compatibility with 2.4 */
2852 if (iocb->ki_flags & IOCB_APPEND)
2853 iocb->ki_pos = i_size_read(inode);
2857 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2860 if (limit != RLIM_INFINITY) {
2861 if (iocb->ki_pos >= limit) {
2862 send_sig(SIGXFSZ, current, 0);
2865 iov_iter_truncate(from, limit - (unsigned long)pos);
2871 if (unlikely(pos + iov_iter_count(from) > MAX_NON_LFS &&
2872 !(file->f_flags & O_LARGEFILE))) {
2873 if (pos >= MAX_NON_LFS)
2875 iov_iter_truncate(from, MAX_NON_LFS - (unsigned long)pos);
2879 * Are we about to exceed the fs block limit ?
2881 * If we have written data it becomes a short write. If we have
2882 * exceeded without writing data we send a signal and return EFBIG.
2883 * Linus frestrict idea will clean these up nicely..
2885 if (unlikely(pos >= inode->i_sb->s_maxbytes))
2888 iov_iter_truncate(from, inode->i_sb->s_maxbytes - pos);
2889 return iov_iter_count(from);
2891 EXPORT_SYMBOL(generic_write_checks);
2893 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2894 loff_t pos, unsigned len, unsigned flags,
2895 struct page **pagep, void **fsdata)
2897 const struct address_space_operations *aops = mapping->a_ops;
2899 return aops->write_begin(file, mapping, pos, len, flags,
2902 EXPORT_SYMBOL(pagecache_write_begin);
2904 int pagecache_write_end(struct file *file, struct address_space *mapping,
2905 loff_t pos, unsigned len, unsigned copied,
2906 struct page *page, void *fsdata)
2908 const struct address_space_operations *aops = mapping->a_ops;
2910 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
2912 EXPORT_SYMBOL(pagecache_write_end);
2915 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
2917 struct file *file = iocb->ki_filp;
2918 struct address_space *mapping = file->f_mapping;
2919 struct inode *inode = mapping->host;
2920 loff_t pos = iocb->ki_pos;
2925 write_len = iov_iter_count(from);
2926 end = (pos + write_len - 1) >> PAGE_SHIFT;
2928 if (iocb->ki_flags & IOCB_NOWAIT) {
2929 /* If there are pages to writeback, return */
2930 if (filemap_range_has_page(inode->i_mapping, pos,
2931 pos + iov_iter_count(from)))
2934 written = filemap_write_and_wait_range(mapping, pos,
2935 pos + write_len - 1);
2941 * After a write we want buffered reads to be sure to go to disk to get
2942 * the new data. We invalidate clean cached page from the region we're
2943 * about to write. We do this *before* the write so that we can return
2944 * without clobbering -EIOCBQUEUED from ->direct_IO().
2946 written = invalidate_inode_pages2_range(mapping,
2947 pos >> PAGE_SHIFT, end);
2949 * If a page can not be invalidated, return 0 to fall back
2950 * to buffered write.
2953 if (written == -EBUSY)
2958 written = mapping->a_ops->direct_IO(iocb, from);
2961 * Finally, try again to invalidate clean pages which might have been
2962 * cached by non-direct readahead, or faulted in by get_user_pages()
2963 * if the source of the write was an mmap'ed region of the file
2964 * we're writing. Either one is a pretty crazy thing to do,
2965 * so we don't support it 100%. If this invalidation
2966 * fails, tough, the write still worked...
2968 * Most of the time we do not need this since dio_complete() will do
2969 * the invalidation for us. However there are some file systems that
2970 * do not end up with dio_complete() being called, so let's not break
2971 * them by removing it completely
2973 if (mapping->nrpages)
2974 invalidate_inode_pages2_range(mapping,
2975 pos >> PAGE_SHIFT, end);
2979 write_len -= written;
2980 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
2981 i_size_write(inode, pos);
2982 mark_inode_dirty(inode);
2986 iov_iter_revert(from, write_len - iov_iter_count(from));
2990 EXPORT_SYMBOL(generic_file_direct_write);
2993 * Find or create a page at the given pagecache position. Return the locked
2994 * page. This function is specifically for buffered writes.
2996 struct page *grab_cache_page_write_begin(struct address_space *mapping,
2997 pgoff_t index, unsigned flags)
3000 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
3002 if (flags & AOP_FLAG_NOFS)
3003 fgp_flags |= FGP_NOFS;
3005 page = pagecache_get_page(mapping, index, fgp_flags,
3006 mapping_gfp_mask(mapping));
3008 wait_for_stable_page(page);
3012 EXPORT_SYMBOL(grab_cache_page_write_begin);
3014 ssize_t generic_perform_write(struct file *file,
3015 struct iov_iter *i, loff_t pos)
3017 struct address_space *mapping = file->f_mapping;
3018 const struct address_space_operations *a_ops = mapping->a_ops;
3020 ssize_t written = 0;
3021 unsigned int flags = 0;
3025 unsigned long offset; /* Offset into pagecache page */
3026 unsigned long bytes; /* Bytes to write to page */
3027 size_t copied; /* Bytes copied from user */
3030 offset = (pos & (PAGE_SIZE - 1));
3031 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3036 * Bring in the user page that we will copy from _first_.
3037 * Otherwise there's a nasty deadlock on copying from the
3038 * same page as we're writing to, without it being marked
3041 * Not only is this an optimisation, but it is also required
3042 * to check that the address is actually valid, when atomic
3043 * usercopies are used, below.
3045 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3050 if (fatal_signal_pending(current)) {
3055 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3057 if (unlikely(status < 0))
3060 if (mapping_writably_mapped(mapping))
3061 flush_dcache_page(page);
3063 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
3064 flush_dcache_page(page);
3066 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3068 if (unlikely(status < 0))
3074 iov_iter_advance(i, copied);
3075 if (unlikely(copied == 0)) {
3077 * If we were unable to copy any data at all, we must
3078 * fall back to a single segment length write.
3080 * If we didn't fallback here, we could livelock
3081 * because not all segments in the iov can be copied at
3082 * once without a pagefault.
3084 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3085 iov_iter_single_seg_count(i));
3091 balance_dirty_pages_ratelimited(mapping);
3092 } while (iov_iter_count(i));
3094 return written ? written : status;
3096 EXPORT_SYMBOL(generic_perform_write);
3099 * __generic_file_write_iter - write data to a file
3100 * @iocb: IO state structure (file, offset, etc.)
3101 * @from: iov_iter with data to write
3103 * This function does all the work needed for actually writing data to a
3104 * file. It does all basic checks, removes SUID from the file, updates
3105 * modification times and calls proper subroutines depending on whether we
3106 * do direct IO or a standard buffered write.
3108 * It expects i_mutex to be grabbed unless we work on a block device or similar
3109 * object which does not need locking at all.
3111 * This function does *not* take care of syncing data in case of O_SYNC write.
3112 * A caller has to handle it. This is mainly due to the fact that we want to
3113 * avoid syncing under i_mutex.
3115 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3117 struct file *file = iocb->ki_filp;
3118 struct address_space * mapping = file->f_mapping;
3119 struct inode *inode = mapping->host;
3120 ssize_t written = 0;
3124 /* We can write back this queue in page reclaim */
3125 current->backing_dev_info = inode_to_bdi(inode);
3126 err = file_remove_privs(file);
3130 err = file_update_time(file);
3134 if (iocb->ki_flags & IOCB_DIRECT) {
3135 loff_t pos, endbyte;
3137 written = generic_file_direct_write(iocb, from);
3139 * If the write stopped short of completing, fall back to
3140 * buffered writes. Some filesystems do this for writes to
3141 * holes, for example. For DAX files, a buffered write will
3142 * not succeed (even if it did, DAX does not handle dirty
3143 * page-cache pages correctly).
3145 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3148 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3150 * If generic_perform_write() returned a synchronous error
3151 * then we want to return the number of bytes which were
3152 * direct-written, or the error code if that was zero. Note
3153 * that this differs from normal direct-io semantics, which
3154 * will return -EFOO even if some bytes were written.
3156 if (unlikely(status < 0)) {
3161 * We need to ensure that the page cache pages are written to
3162 * disk and invalidated to preserve the expected O_DIRECT
3165 endbyte = pos + status - 1;
3166 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3168 iocb->ki_pos = endbyte + 1;
3170 invalidate_mapping_pages(mapping,
3172 endbyte >> PAGE_SHIFT);
3175 * We don't know how much we wrote, so just return
3176 * the number of bytes which were direct-written
3180 written = generic_perform_write(file, from, iocb->ki_pos);
3181 if (likely(written > 0))
3182 iocb->ki_pos += written;
3185 current->backing_dev_info = NULL;
3186 return written ? written : err;
3188 EXPORT_SYMBOL(__generic_file_write_iter);
3191 * generic_file_write_iter - write data to a file
3192 * @iocb: IO state structure
3193 * @from: iov_iter with data to write
3195 * This is a wrapper around __generic_file_write_iter() to be used by most
3196 * filesystems. It takes care of syncing the file in case of O_SYNC file
3197 * and acquires i_mutex as needed.
3199 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3201 struct file *file = iocb->ki_filp;
3202 struct inode *inode = file->f_mapping->host;
3206 ret = generic_write_checks(iocb, from);
3208 ret = __generic_file_write_iter(iocb, from);
3209 inode_unlock(inode);
3212 ret = generic_write_sync(iocb, ret);
3215 EXPORT_SYMBOL(generic_file_write_iter);
3218 * try_to_release_page() - release old fs-specific metadata on a page
3220 * @page: the page which the kernel is trying to free
3221 * @gfp_mask: memory allocation flags (and I/O mode)
3223 * The address_space is to try to release any data against the page
3224 * (presumably at page->private). If the release was successful, return '1'.
3225 * Otherwise return zero.
3227 * This may also be called if PG_fscache is set on a page, indicating that the
3228 * page is known to the local caching routines.
3230 * The @gfp_mask argument specifies whether I/O may be performed to release
3231 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3234 int try_to_release_page(struct page *page, gfp_t gfp_mask)
3236 struct address_space * const mapping = page->mapping;
3238 BUG_ON(!PageLocked(page));
3239 if (PageWriteback(page))
3242 if (mapping && mapping->a_ops->releasepage)
3243 return mapping->a_ops->releasepage(page, gfp_mask);
3244 return try_to_free_buffers(page);
3247 EXPORT_SYMBOL(try_to_release_page);