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/hugetlb.h>
35 #include <linux/memcontrol.h>
36 #include <linux/cleancache.h>
37 #include <linux/shmem_fs.h>
38 #include <linux/rmap.h>
39 #include <linux/delayacct.h>
42 #define CREATE_TRACE_POINTS
43 #include <trace/events/filemap.h>
46 * FIXME: remove all knowledge of the buffer layer from the core VM
48 #include <linux/buffer_head.h> /* for try_to_free_buffers */
53 * Shared mappings implemented 30.11.1994. It's not fully working yet,
56 * Shared mappings now work. 15.8.1995 Bruno.
58 * finished 'unifying' the page and buffer cache and SMP-threaded the
59 * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
61 * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
67 * ->i_mmap_rwsem (truncate_pagecache)
68 * ->private_lock (__free_pte->__set_page_dirty_buffers)
69 * ->swap_lock (exclusive_swap_page, others)
73 * ->i_mmap_rwsem (truncate->unmap_mapping_range)
77 * ->page_table_lock or pte_lock (various, mainly in memory.c)
78 * ->i_pages lock (arch-dependent flush_dcache_mmap_lock)
81 * ->lock_page (access_process_vm)
83 * ->i_mutex (generic_perform_write)
84 * ->mmap_sem (fault_in_pages_readable->do_page_fault)
87 * sb_lock (fs/fs-writeback.c)
88 * ->i_pages lock (__sync_single_inode)
91 * ->anon_vma.lock (vma_adjust)
94 * ->page_table_lock or pte_lock (anon_vma_prepare and various)
96 * ->page_table_lock or pte_lock
97 * ->swap_lock (try_to_unmap_one)
98 * ->private_lock (try_to_unmap_one)
99 * ->i_pages lock (try_to_unmap_one)
100 * ->zone_lru_lock(zone) (follow_page->mark_page_accessed)
101 * ->zone_lru_lock(zone) (check_pte_range->isolate_lru_page)
102 * ->private_lock (page_remove_rmap->set_page_dirty)
103 * ->i_pages lock (page_remove_rmap->set_page_dirty)
104 * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
105 * ->inode->i_lock (page_remove_rmap->set_page_dirty)
106 * ->memcg->move_lock (page_remove_rmap->lock_page_memcg)
107 * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
108 * ->inode->i_lock (zap_pte_range->set_page_dirty)
109 * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
112 * ->tasklist_lock (memory_failure, collect_procs_ao)
115 static int page_cache_tree_insert(struct address_space *mapping,
116 struct page *page, void **shadowp)
118 struct radix_tree_node *node;
122 error = __radix_tree_create(&mapping->i_pages, page->index, 0,
129 p = radix_tree_deref_slot_protected(slot,
130 &mapping->i_pages.xa_lock);
131 if (!radix_tree_exceptional_entry(p))
134 mapping->nrexceptional--;
138 __radix_tree_replace(&mapping->i_pages, node, slot, page,
139 workingset_lookup_update(mapping));
144 static void page_cache_tree_delete(struct address_space *mapping,
145 struct page *page, void *shadow)
149 /* hugetlb pages are represented by one entry in the radix tree */
150 nr = PageHuge(page) ? 1 : hpage_nr_pages(page);
152 VM_BUG_ON_PAGE(!PageLocked(page), page);
153 VM_BUG_ON_PAGE(PageTail(page), page);
154 VM_BUG_ON_PAGE(nr != 1 && shadow, page);
156 for (i = 0; i < nr; i++) {
157 struct radix_tree_node *node;
160 __radix_tree_lookup(&mapping->i_pages, page->index + i,
163 VM_BUG_ON_PAGE(!node && nr != 1, page);
165 radix_tree_clear_tags(&mapping->i_pages, node, slot);
166 __radix_tree_replace(&mapping->i_pages, node, slot, shadow,
167 workingset_lookup_update(mapping));
170 page->mapping = NULL;
171 /* Leave page->index set: truncation lookup relies upon it */
174 mapping->nrexceptional += nr;
176 * Make sure the nrexceptional update is committed before
177 * the nrpages update so that final truncate racing
178 * with reclaim does not see both counters 0 at the
179 * same time and miss a shadow entry.
183 mapping->nrpages -= nr;
186 static void unaccount_page_cache_page(struct address_space *mapping,
192 * if we're uptodate, flush out into the cleancache, otherwise
193 * invalidate any existing cleancache entries. We can't leave
194 * stale data around in the cleancache once our page is gone
196 if (PageUptodate(page) && PageMappedToDisk(page))
197 cleancache_put_page(page);
199 cleancache_invalidate_page(mapping, page);
201 VM_BUG_ON_PAGE(PageTail(page), page);
202 VM_BUG_ON_PAGE(page_mapped(page), page);
203 if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(page_mapped(page))) {
206 pr_alert("BUG: Bad page cache in process %s pfn:%05lx\n",
207 current->comm, page_to_pfn(page));
208 dump_page(page, "still mapped when deleted");
210 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
212 mapcount = page_mapcount(page);
213 if (mapping_exiting(mapping) &&
214 page_count(page) >= mapcount + 2) {
216 * All vmas have already been torn down, so it's
217 * a good bet that actually the page is unmapped,
218 * and we'd prefer not to leak it: if we're wrong,
219 * some other bad page check should catch it later.
221 page_mapcount_reset(page);
222 page_ref_sub(page, mapcount);
226 /* hugetlb pages do not participate in page cache accounting. */
230 nr = hpage_nr_pages(page);
232 __mod_node_page_state(page_pgdat(page), NR_FILE_PAGES, -nr);
233 if (PageSwapBacked(page)) {
234 __mod_node_page_state(page_pgdat(page), NR_SHMEM, -nr);
235 if (PageTransHuge(page))
236 __dec_node_page_state(page, NR_SHMEM_THPS);
238 VM_BUG_ON_PAGE(PageTransHuge(page), page);
242 * At this point page must be either written or cleaned by
243 * truncate. Dirty page here signals a bug and loss of
246 * This fixes dirty accounting after removing the page entirely
247 * but leaves PageDirty set: it has no effect for truncated
248 * page and anyway will be cleared before returning page into
251 if (WARN_ON_ONCE(PageDirty(page)))
252 account_page_cleaned(page, mapping, inode_to_wb(mapping->host));
256 * Delete a page from the page cache and free it. Caller has to make
257 * sure the page is locked and that nobody else uses it - or that usage
258 * is safe. The caller must hold the i_pages lock.
260 void __delete_from_page_cache(struct page *page, void *shadow)
262 struct address_space *mapping = page->mapping;
264 trace_mm_filemap_delete_from_page_cache(page);
266 unaccount_page_cache_page(mapping, page);
267 page_cache_tree_delete(mapping, page, shadow);
270 static void page_cache_free_page(struct address_space *mapping,
273 void (*freepage)(struct page *);
275 freepage = mapping->a_ops->freepage;
279 if (PageTransHuge(page) && !PageHuge(page)) {
280 page_ref_sub(page, HPAGE_PMD_NR);
281 VM_BUG_ON_PAGE(page_count(page) <= 0, page);
288 * delete_from_page_cache - delete page from page cache
289 * @page: the page which the kernel is trying to remove from page cache
291 * This must be called only on pages that have been verified to be in the page
292 * cache and locked. It will never put the page into the free list, the caller
293 * has a reference on the page.
295 void delete_from_page_cache(struct page *page)
297 struct address_space *mapping = page_mapping(page);
300 BUG_ON(!PageLocked(page));
301 xa_lock_irqsave(&mapping->i_pages, flags);
302 __delete_from_page_cache(page, NULL);
303 xa_unlock_irqrestore(&mapping->i_pages, flags);
305 page_cache_free_page(mapping, page);
307 EXPORT_SYMBOL(delete_from_page_cache);
310 * page_cache_tree_delete_batch - delete several pages from page cache
311 * @mapping: the mapping to which pages belong
312 * @pvec: pagevec with pages to delete
314 * The function walks over mapping->i_pages and removes pages passed in @pvec
315 * from the mapping. The function expects @pvec to be sorted by page index.
316 * It tolerates holes in @pvec (mapping entries at those indices are not
317 * modified). The function expects only THP head pages to be present in the
318 * @pvec and takes care to delete all corresponding tail pages from the
321 * The function expects the i_pages lock to be held.
324 page_cache_tree_delete_batch(struct address_space *mapping,
325 struct pagevec *pvec)
327 struct radix_tree_iter iter;
330 int i = 0, tail_pages = 0;
334 start = pvec->pages[0]->index;
335 radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
336 if (i >= pagevec_count(pvec) && !tail_pages)
338 page = radix_tree_deref_slot_protected(slot,
339 &mapping->i_pages.xa_lock);
340 if (radix_tree_exceptional_entry(page))
344 * Some page got inserted in our range? Skip it. We
345 * have our pages locked so they are protected from
348 if (page != pvec->pages[i])
350 WARN_ON_ONCE(!PageLocked(page));
351 if (PageTransHuge(page) && !PageHuge(page))
352 tail_pages = HPAGE_PMD_NR - 1;
353 page->mapping = NULL;
355 * Leave page->index set: truncation lookup relies
362 radix_tree_clear_tags(&mapping->i_pages, iter.node, slot);
363 __radix_tree_replace(&mapping->i_pages, iter.node, slot, NULL,
364 workingset_lookup_update(mapping));
367 mapping->nrpages -= total_pages;
370 void delete_from_page_cache_batch(struct address_space *mapping,
371 struct pagevec *pvec)
376 if (!pagevec_count(pvec))
379 xa_lock_irqsave(&mapping->i_pages, flags);
380 for (i = 0; i < pagevec_count(pvec); i++) {
381 trace_mm_filemap_delete_from_page_cache(pvec->pages[i]);
383 unaccount_page_cache_page(mapping, pvec->pages[i]);
385 page_cache_tree_delete_batch(mapping, pvec);
386 xa_unlock_irqrestore(&mapping->i_pages, flags);
388 for (i = 0; i < pagevec_count(pvec); i++)
389 page_cache_free_page(mapping, pvec->pages[i]);
392 int filemap_check_errors(struct address_space *mapping)
395 /* Check for outstanding write errors */
396 if (test_bit(AS_ENOSPC, &mapping->flags) &&
397 test_and_clear_bit(AS_ENOSPC, &mapping->flags))
399 if (test_bit(AS_EIO, &mapping->flags) &&
400 test_and_clear_bit(AS_EIO, &mapping->flags))
404 EXPORT_SYMBOL(filemap_check_errors);
406 static int filemap_check_and_keep_errors(struct address_space *mapping)
408 /* Check for outstanding write errors */
409 if (test_bit(AS_EIO, &mapping->flags))
411 if (test_bit(AS_ENOSPC, &mapping->flags))
417 * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
418 * @mapping: address space structure to write
419 * @start: offset in bytes where the range starts
420 * @end: offset in bytes where the range ends (inclusive)
421 * @sync_mode: enable synchronous operation
423 * Start writeback against all of a mapping's dirty pages that lie
424 * within the byte offsets <start, end> inclusive.
426 * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
427 * opposed to a regular memory cleansing writeback. The difference between
428 * these two operations is that if a dirty page/buffer is encountered, it must
429 * be waited upon, and not just skipped over.
431 int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
432 loff_t end, int sync_mode)
435 struct writeback_control wbc = {
436 .sync_mode = sync_mode,
437 .nr_to_write = LONG_MAX,
438 .range_start = start,
442 if (!mapping_cap_writeback_dirty(mapping))
445 wbc_attach_fdatawrite_inode(&wbc, mapping->host);
446 ret = do_writepages(mapping, &wbc);
447 wbc_detach_inode(&wbc);
451 static inline int __filemap_fdatawrite(struct address_space *mapping,
454 return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
457 int filemap_fdatawrite(struct address_space *mapping)
459 return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
461 EXPORT_SYMBOL(filemap_fdatawrite);
463 int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
466 return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
468 EXPORT_SYMBOL(filemap_fdatawrite_range);
471 * filemap_flush - mostly a non-blocking flush
472 * @mapping: target address_space
474 * This is a mostly non-blocking flush. Not suitable for data-integrity
475 * purposes - I/O may not be started against all dirty pages.
477 int filemap_flush(struct address_space *mapping)
479 return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
481 EXPORT_SYMBOL(filemap_flush);
484 * filemap_range_has_page - check if a page exists in range.
485 * @mapping: address space within which to check
486 * @start_byte: offset in bytes where the range starts
487 * @end_byte: offset in bytes where the range ends (inclusive)
489 * Find at least one page in the range supplied, usually used to check if
490 * direct writing in this range will trigger a writeback.
492 bool filemap_range_has_page(struct address_space *mapping,
493 loff_t start_byte, loff_t end_byte)
495 pgoff_t index = start_byte >> PAGE_SHIFT;
496 pgoff_t end = end_byte >> PAGE_SHIFT;
499 if (end_byte < start_byte)
502 if (mapping->nrpages == 0)
505 if (!find_get_pages_range(mapping, &index, end, 1, &page))
510 EXPORT_SYMBOL(filemap_range_has_page);
512 static void __filemap_fdatawait_range(struct address_space *mapping,
513 loff_t start_byte, loff_t end_byte)
515 pgoff_t index = start_byte >> PAGE_SHIFT;
516 pgoff_t end = end_byte >> PAGE_SHIFT;
520 if (end_byte < start_byte)
524 while (index <= end) {
527 nr_pages = pagevec_lookup_range_tag(&pvec, mapping, &index,
528 end, PAGECACHE_TAG_WRITEBACK);
532 for (i = 0; i < nr_pages; i++) {
533 struct page *page = pvec.pages[i];
535 wait_on_page_writeback(page);
536 ClearPageError(page);
538 pagevec_release(&pvec);
544 * filemap_fdatawait_range - wait for writeback to complete
545 * @mapping: address space structure to wait for
546 * @start_byte: offset in bytes where the range starts
547 * @end_byte: offset in bytes where the range ends (inclusive)
549 * Walk the list of under-writeback pages of the given address space
550 * in the given range and wait for all of them. Check error status of
551 * the address space and return it.
553 * Since the error status of the address space is cleared by this function,
554 * callers are responsible for checking the return value and handling and/or
555 * reporting the error.
557 int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
560 __filemap_fdatawait_range(mapping, start_byte, end_byte);
561 return filemap_check_errors(mapping);
563 EXPORT_SYMBOL(filemap_fdatawait_range);
566 * file_fdatawait_range - wait for writeback to complete
567 * @file: file pointing to address space structure to wait for
568 * @start_byte: offset in bytes where the range starts
569 * @end_byte: offset in bytes where the range ends (inclusive)
571 * Walk the list of under-writeback pages of the address space that file
572 * refers to, in the given range and wait for all of them. Check error
573 * status of the address space vs. the file->f_wb_err cursor and return it.
575 * Since the error status of the file is advanced by this function,
576 * callers are responsible for checking the return value and handling and/or
577 * reporting the error.
579 int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
581 struct address_space *mapping = file->f_mapping;
583 __filemap_fdatawait_range(mapping, start_byte, end_byte);
584 return file_check_and_advance_wb_err(file);
586 EXPORT_SYMBOL(file_fdatawait_range);
589 * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
590 * @mapping: address space structure to wait for
592 * Walk the list of under-writeback pages of the given address space
593 * and wait for all of them. Unlike filemap_fdatawait(), this function
594 * does not clear error status of the address space.
596 * Use this function if callers don't handle errors themselves. Expected
597 * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
600 int filemap_fdatawait_keep_errors(struct address_space *mapping)
602 __filemap_fdatawait_range(mapping, 0, LLONG_MAX);
603 return filemap_check_and_keep_errors(mapping);
605 EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
607 static bool mapping_needs_writeback(struct address_space *mapping)
609 return (!dax_mapping(mapping) && mapping->nrpages) ||
610 (dax_mapping(mapping) && mapping->nrexceptional);
613 int filemap_write_and_wait(struct address_space *mapping)
617 if (mapping_needs_writeback(mapping)) {
618 err = filemap_fdatawrite(mapping);
620 * Even if the above returned error, the pages may be
621 * written partially (e.g. -ENOSPC), so we wait for it.
622 * But the -EIO is special case, it may indicate the worst
623 * thing (e.g. bug) happened, so we avoid waiting for it.
626 int err2 = filemap_fdatawait(mapping);
630 /* Clear any previously stored errors */
631 filemap_check_errors(mapping);
634 err = filemap_check_errors(mapping);
638 EXPORT_SYMBOL(filemap_write_and_wait);
641 * filemap_write_and_wait_range - write out & wait on a file range
642 * @mapping: the address_space for the pages
643 * @lstart: offset in bytes where the range starts
644 * @lend: offset in bytes where the range ends (inclusive)
646 * Write out and wait upon file offsets lstart->lend, inclusive.
648 * Note that @lend is inclusive (describes the last byte to be written) so
649 * that this function can be used to write to the very end-of-file (end = -1).
651 int filemap_write_and_wait_range(struct address_space *mapping,
652 loff_t lstart, loff_t lend)
656 if (mapping_needs_writeback(mapping)) {
657 err = __filemap_fdatawrite_range(mapping, lstart, lend,
659 /* See comment of filemap_write_and_wait() */
661 int err2 = filemap_fdatawait_range(mapping,
666 /* Clear any previously stored errors */
667 filemap_check_errors(mapping);
670 err = filemap_check_errors(mapping);
674 EXPORT_SYMBOL(filemap_write_and_wait_range);
676 void __filemap_set_wb_err(struct address_space *mapping, int err)
678 errseq_t eseq = errseq_set(&mapping->wb_err, err);
680 trace_filemap_set_wb_err(mapping, eseq);
682 EXPORT_SYMBOL(__filemap_set_wb_err);
685 * file_check_and_advance_wb_err - report wb error (if any) that was previously
686 * and advance wb_err to current one
687 * @file: struct file on which the error is being reported
689 * When userland calls fsync (or something like nfsd does the equivalent), we
690 * want to report any writeback errors that occurred since the last fsync (or
691 * since the file was opened if there haven't been any).
693 * Grab the wb_err from the mapping. If it matches what we have in the file,
694 * then just quickly return 0. The file is all caught up.
696 * If it doesn't match, then take the mapping value, set the "seen" flag in
697 * it and try to swap it into place. If it works, or another task beat us
698 * to it with the new value, then update the f_wb_err and return the error
699 * portion. The error at this point must be reported via proper channels
700 * (a'la fsync, or NFS COMMIT operation, etc.).
702 * While we handle mapping->wb_err with atomic operations, the f_wb_err
703 * value is protected by the f_lock since we must ensure that it reflects
704 * the latest value swapped in for this file descriptor.
706 int file_check_and_advance_wb_err(struct file *file)
709 errseq_t old = READ_ONCE(file->f_wb_err);
710 struct address_space *mapping = file->f_mapping;
712 /* Locklessly handle the common case where nothing has changed */
713 if (errseq_check(&mapping->wb_err, old)) {
714 /* Something changed, must use slow path */
715 spin_lock(&file->f_lock);
716 old = file->f_wb_err;
717 err = errseq_check_and_advance(&mapping->wb_err,
719 trace_file_check_and_advance_wb_err(file, old);
720 spin_unlock(&file->f_lock);
724 * We're mostly using this function as a drop in replacement for
725 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
726 * that the legacy code would have had on these flags.
728 clear_bit(AS_EIO, &mapping->flags);
729 clear_bit(AS_ENOSPC, &mapping->flags);
732 EXPORT_SYMBOL(file_check_and_advance_wb_err);
735 * file_write_and_wait_range - write out & wait on a file range
736 * @file: file pointing to address_space with pages
737 * @lstart: offset in bytes where the range starts
738 * @lend: offset in bytes where the range ends (inclusive)
740 * Write out and wait upon file offsets lstart->lend, inclusive.
742 * Note that @lend is inclusive (describes the last byte to be written) so
743 * that this function can be used to write to the very end-of-file (end = -1).
745 * After writing out and waiting on the data, we check and advance the
746 * f_wb_err cursor to the latest value, and return any errors detected there.
748 int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
751 struct address_space *mapping = file->f_mapping;
753 if (mapping_needs_writeback(mapping)) {
754 err = __filemap_fdatawrite_range(mapping, lstart, lend,
756 /* See comment of filemap_write_and_wait() */
758 __filemap_fdatawait_range(mapping, lstart, lend);
760 err2 = file_check_and_advance_wb_err(file);
765 EXPORT_SYMBOL(file_write_and_wait_range);
768 * replace_page_cache_page - replace a pagecache page with a new one
769 * @old: page to be replaced
770 * @new: page to replace with
771 * @gfp_mask: allocation mode
773 * This function replaces a page in the pagecache with a new one. On
774 * success it acquires the pagecache reference for the new page and
775 * drops it for the old page. Both the old and new pages must be
776 * locked. This function does not add the new page to the LRU, the
777 * caller must do that.
779 * The remove + add is atomic. The only way this function can fail is
780 * memory allocation failure.
782 int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
786 VM_BUG_ON_PAGE(!PageLocked(old), old);
787 VM_BUG_ON_PAGE(!PageLocked(new), new);
788 VM_BUG_ON_PAGE(new->mapping, new);
790 error = radix_tree_preload(gfp_mask & GFP_RECLAIM_MASK);
792 struct address_space *mapping = old->mapping;
793 void (*freepage)(struct page *);
796 pgoff_t offset = old->index;
797 freepage = mapping->a_ops->freepage;
800 new->mapping = mapping;
803 xa_lock_irqsave(&mapping->i_pages, flags);
804 __delete_from_page_cache(old, NULL);
805 error = page_cache_tree_insert(mapping, new, NULL);
809 * hugetlb pages do not participate in page cache accounting.
812 __inc_node_page_state(new, NR_FILE_PAGES);
813 if (PageSwapBacked(new))
814 __inc_node_page_state(new, NR_SHMEM);
815 xa_unlock_irqrestore(&mapping->i_pages, flags);
816 mem_cgroup_migrate(old, new);
817 radix_tree_preload_end();
825 EXPORT_SYMBOL_GPL(replace_page_cache_page);
827 static int __add_to_page_cache_locked(struct page *page,
828 struct address_space *mapping,
829 pgoff_t offset, gfp_t gfp_mask,
832 int huge = PageHuge(page);
833 struct mem_cgroup *memcg;
836 VM_BUG_ON_PAGE(!PageLocked(page), page);
837 VM_BUG_ON_PAGE(PageSwapBacked(page), page);
840 error = mem_cgroup_try_charge(page, current->mm,
841 gfp_mask, &memcg, false);
846 error = radix_tree_maybe_preload(gfp_mask & GFP_RECLAIM_MASK);
849 mem_cgroup_cancel_charge(page, memcg, false);
854 page->mapping = mapping;
855 page->index = offset;
857 xa_lock_irq(&mapping->i_pages);
858 error = page_cache_tree_insert(mapping, page, shadowp);
859 radix_tree_preload_end();
863 /* hugetlb pages do not participate in page cache accounting. */
865 __inc_node_page_state(page, NR_FILE_PAGES);
866 xa_unlock_irq(&mapping->i_pages);
868 mem_cgroup_commit_charge(page, memcg, false, false);
869 trace_mm_filemap_add_to_page_cache(page);
872 page->mapping = NULL;
873 /* Leave page->index set: truncation relies upon it */
874 xa_unlock_irq(&mapping->i_pages);
876 mem_cgroup_cancel_charge(page, memcg, false);
882 * add_to_page_cache_locked - add a locked page to the pagecache
884 * @mapping: the page's address_space
885 * @offset: page index
886 * @gfp_mask: page allocation mode
888 * This function is used to add a page to the pagecache. It must be locked.
889 * This function does not add the page to the LRU. The caller must do that.
891 int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
892 pgoff_t offset, gfp_t gfp_mask)
894 return __add_to_page_cache_locked(page, mapping, offset,
897 EXPORT_SYMBOL(add_to_page_cache_locked);
899 int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
900 pgoff_t offset, gfp_t gfp_mask)
905 __SetPageLocked(page);
906 ret = __add_to_page_cache_locked(page, mapping, offset,
909 __ClearPageLocked(page);
912 * The page might have been evicted from cache only
913 * recently, in which case it should be activated like
914 * any other repeatedly accessed page.
915 * The exception is pages getting rewritten; evicting other
916 * data from the working set, only to cache data that will
917 * get overwritten with something else, is a waste of memory.
919 WARN_ON_ONCE(PageActive(page));
920 if (!(gfp_mask & __GFP_WRITE) && shadow)
921 workingset_refault(page, shadow);
926 EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
929 struct page *__page_cache_alloc(gfp_t gfp)
934 if (cpuset_do_page_mem_spread()) {
935 unsigned int cpuset_mems_cookie;
937 cpuset_mems_cookie = read_mems_allowed_begin();
938 n = cpuset_mem_spread_node();
939 page = __alloc_pages_node(n, gfp, 0);
940 } while (!page && read_mems_allowed_retry(cpuset_mems_cookie));
944 return alloc_pages(gfp, 0);
946 EXPORT_SYMBOL(__page_cache_alloc);
950 * In order to wait for pages to become available there must be
951 * waitqueues associated with pages. By using a hash table of
952 * waitqueues where the bucket discipline is to maintain all
953 * waiters on the same queue and wake all when any of the pages
954 * become available, and for the woken contexts to check to be
955 * sure the appropriate page became available, this saves space
956 * at a cost of "thundering herd" phenomena during rare hash
959 #define PAGE_WAIT_TABLE_BITS 8
960 #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
961 static wait_queue_head_t page_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
963 static wait_queue_head_t *page_waitqueue(struct page *page)
965 return &page_wait_table[hash_ptr(page, PAGE_WAIT_TABLE_BITS)];
968 void __init pagecache_init(void)
972 for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
973 init_waitqueue_head(&page_wait_table[i]);
975 page_writeback_init();
978 /* This has the same layout as wait_bit_key - see fs/cachefiles/rdwr.c */
979 struct wait_page_key {
985 struct wait_page_queue {
988 wait_queue_entry_t wait;
991 static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
993 struct wait_page_key *key = arg;
994 struct wait_page_queue *wait_page
995 = container_of(wait, struct wait_page_queue, wait);
997 if (wait_page->page != key->page)
1001 if (wait_page->bit_nr != key->bit_nr)
1004 /* Stop walking if it's locked */
1005 if (test_bit(key->bit_nr, &key->page->flags))
1008 return autoremove_wake_function(wait, mode, sync, key);
1011 static void wake_up_page_bit(struct page *page, int bit_nr)
1013 wait_queue_head_t *q = page_waitqueue(page);
1014 struct wait_page_key key;
1015 unsigned long flags;
1016 wait_queue_entry_t bookmark;
1019 key.bit_nr = bit_nr;
1023 bookmark.private = NULL;
1024 bookmark.func = NULL;
1025 INIT_LIST_HEAD(&bookmark.entry);
1027 spin_lock_irqsave(&q->lock, flags);
1028 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1030 while (bookmark.flags & WQ_FLAG_BOOKMARK) {
1032 * Take a breather from holding the lock,
1033 * allow pages that finish wake up asynchronously
1034 * to acquire the lock and remove themselves
1037 spin_unlock_irqrestore(&q->lock, flags);
1039 spin_lock_irqsave(&q->lock, flags);
1040 __wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
1044 * It is possible for other pages to have collided on the waitqueue
1045 * hash, so in that case check for a page match. That prevents a long-
1048 * It is still possible to miss a case here, when we woke page waiters
1049 * and removed them from the waitqueue, but there are still other
1052 if (!waitqueue_active(q) || !key.page_match) {
1053 ClearPageWaiters(page);
1055 * It's possible to miss clearing Waiters here, when we woke
1056 * our page waiters, but the hashed waitqueue has waiters for
1057 * other pages on it.
1059 * That's okay, it's a rare case. The next waker will clear it.
1062 spin_unlock_irqrestore(&q->lock, flags);
1065 static void wake_up_page(struct page *page, int bit)
1067 if (!PageWaiters(page))
1069 wake_up_page_bit(page, bit);
1072 static inline int wait_on_page_bit_common(wait_queue_head_t *q,
1073 struct page *page, int bit_nr, int state, bool lock)
1075 struct wait_page_queue wait_page;
1076 wait_queue_entry_t *wait = &wait_page.wait;
1077 bool thrashing = false;
1080 if (bit_nr == PG_locked && !PageSwapBacked(page) &&
1081 !PageUptodate(page) && PageWorkingset(page)) {
1082 delayacct_thrashing_start();
1087 wait->flags = lock ? WQ_FLAG_EXCLUSIVE : 0;
1088 wait->func = wake_page_function;
1089 wait_page.page = page;
1090 wait_page.bit_nr = bit_nr;
1093 spin_lock_irq(&q->lock);
1095 if (likely(list_empty(&wait->entry))) {
1096 __add_wait_queue_entry_tail(q, wait);
1097 SetPageWaiters(page);
1100 set_current_state(state);
1102 spin_unlock_irq(&q->lock);
1104 if (likely(test_bit(bit_nr, &page->flags))) {
1109 if (!test_and_set_bit_lock(bit_nr, &page->flags))
1112 if (!test_bit(bit_nr, &page->flags))
1116 if (unlikely(signal_pending_state(state, current))) {
1122 finish_wait(q, wait);
1125 delayacct_thrashing_end();
1128 * A signal could leave PageWaiters set. Clearing it here if
1129 * !waitqueue_active would be possible (by open-coding finish_wait),
1130 * but still fail to catch it in the case of wait hash collision. We
1131 * already can fail to clear wait hash collision cases, so don't
1132 * bother with signals either.
1138 void wait_on_page_bit(struct page *page, int bit_nr)
1140 wait_queue_head_t *q = page_waitqueue(page);
1141 wait_on_page_bit_common(q, page, bit_nr, TASK_UNINTERRUPTIBLE, false);
1143 EXPORT_SYMBOL(wait_on_page_bit);
1145 int wait_on_page_bit_killable(struct page *page, int bit_nr)
1147 wait_queue_head_t *q = page_waitqueue(page);
1148 return wait_on_page_bit_common(q, page, bit_nr, TASK_KILLABLE, false);
1150 EXPORT_SYMBOL(wait_on_page_bit_killable);
1153 * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
1154 * @page: Page defining the wait queue of interest
1155 * @waiter: Waiter to add to the queue
1157 * Add an arbitrary @waiter to the wait queue for the nominated @page.
1159 void add_page_wait_queue(struct page *page, wait_queue_entry_t *waiter)
1161 wait_queue_head_t *q = page_waitqueue(page);
1162 unsigned long flags;
1164 spin_lock_irqsave(&q->lock, flags);
1165 __add_wait_queue_entry_tail(q, waiter);
1166 SetPageWaiters(page);
1167 spin_unlock_irqrestore(&q->lock, flags);
1169 EXPORT_SYMBOL_GPL(add_page_wait_queue);
1171 #ifndef clear_bit_unlock_is_negative_byte
1174 * PG_waiters is the high bit in the same byte as PG_lock.
1176 * On x86 (and on many other architectures), we can clear PG_lock and
1177 * test the sign bit at the same time. But if the architecture does
1178 * not support that special operation, we just do this all by hand
1181 * The read of PG_waiters has to be after (or concurrently with) PG_locked
1182 * being cleared, but a memory barrier should be unneccssary since it is
1183 * in the same byte as PG_locked.
1185 static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1187 clear_bit_unlock(nr, mem);
1188 /* smp_mb__after_atomic(); */
1189 return test_bit(PG_waiters, mem);
1195 * unlock_page - unlock a locked page
1198 * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
1199 * Also wakes sleepers in wait_on_page_writeback() because the wakeup
1200 * mechanism between PageLocked pages and PageWriteback pages is shared.
1201 * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
1203 * Note that this depends on PG_waiters being the sign bit in the byte
1204 * that contains PG_locked - thus the BUILD_BUG_ON(). That allows us to
1205 * clear the PG_locked bit and test PG_waiters at the same time fairly
1206 * portably (architectures that do LL/SC can test any bit, while x86 can
1207 * test the sign bit).
1209 void unlock_page(struct page *page)
1211 BUILD_BUG_ON(PG_waiters != 7);
1212 page = compound_head(page);
1213 VM_BUG_ON_PAGE(!PageLocked(page), page);
1214 if (clear_bit_unlock_is_negative_byte(PG_locked, &page->flags))
1215 wake_up_page_bit(page, PG_locked);
1217 EXPORT_SYMBOL(unlock_page);
1220 * end_page_writeback - end writeback against a page
1223 void end_page_writeback(struct page *page)
1226 * TestClearPageReclaim could be used here but it is an atomic
1227 * operation and overkill in this particular case. Failing to
1228 * shuffle a page marked for immediate reclaim is too mild to
1229 * justify taking an atomic operation penalty at the end of
1230 * ever page writeback.
1232 if (PageReclaim(page)) {
1233 ClearPageReclaim(page);
1234 rotate_reclaimable_page(page);
1237 if (!test_clear_page_writeback(page))
1240 smp_mb__after_atomic();
1241 wake_up_page(page, PG_writeback);
1243 EXPORT_SYMBOL(end_page_writeback);
1246 * After completing I/O on a page, call this routine to update the page
1247 * flags appropriately
1249 void page_endio(struct page *page, bool is_write, int err)
1253 SetPageUptodate(page);
1255 ClearPageUptodate(page);
1261 struct address_space *mapping;
1264 mapping = page_mapping(page);
1266 mapping_set_error(mapping, err);
1268 end_page_writeback(page);
1271 EXPORT_SYMBOL_GPL(page_endio);
1274 * __lock_page - get a lock on the page, assuming we need to sleep to get it
1275 * @__page: the page to lock
1277 void __lock_page(struct page *__page)
1279 struct page *page = compound_head(__page);
1280 wait_queue_head_t *q = page_waitqueue(page);
1281 wait_on_page_bit_common(q, page, PG_locked, TASK_UNINTERRUPTIBLE, true);
1283 EXPORT_SYMBOL(__lock_page);
1285 int __lock_page_killable(struct page *__page)
1287 struct page *page = compound_head(__page);
1288 wait_queue_head_t *q = page_waitqueue(page);
1289 return wait_on_page_bit_common(q, page, PG_locked, TASK_KILLABLE, true);
1291 EXPORT_SYMBOL_GPL(__lock_page_killable);
1295 * 1 - page is locked; mmap_sem is still held.
1296 * 0 - page is not locked.
1297 * mmap_sem has been released (up_read()), unless flags had both
1298 * FAULT_FLAG_ALLOW_RETRY and FAULT_FLAG_RETRY_NOWAIT set, in
1299 * which case mmap_sem is still held.
1301 * If neither ALLOW_RETRY nor KILLABLE are set, will always return 1
1302 * with the page locked and the mmap_sem unperturbed.
1304 int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
1307 if (flags & FAULT_FLAG_ALLOW_RETRY) {
1309 * CAUTION! In this case, mmap_sem is not released
1310 * even though return 0.
1312 if (flags & FAULT_FLAG_RETRY_NOWAIT)
1315 up_read(&mm->mmap_sem);
1316 if (flags & FAULT_FLAG_KILLABLE)
1317 wait_on_page_locked_killable(page);
1319 wait_on_page_locked(page);
1322 if (flags & FAULT_FLAG_KILLABLE) {
1325 ret = __lock_page_killable(page);
1327 up_read(&mm->mmap_sem);
1337 * page_cache_next_hole - find the next hole (not-present entry)
1340 * @max_scan: maximum range to search
1342 * Search the set [index, min(index+max_scan-1, MAX_INDEX)] for the
1343 * lowest indexed hole.
1345 * Returns: the index of the hole if found, otherwise returns an index
1346 * outside of the set specified (in which case 'return - index >=
1347 * max_scan' will be true). In rare cases of index wrap-around, 0 will
1350 * page_cache_next_hole may be called under rcu_read_lock. However,
1351 * like radix_tree_gang_lookup, this will not atomically search a
1352 * snapshot of the tree at a single point in time. For example, if a
1353 * hole is created at index 5, then subsequently a hole is created at
1354 * index 10, page_cache_next_hole covering both indexes may return 10
1355 * if called under rcu_read_lock.
1357 pgoff_t page_cache_next_hole(struct address_space *mapping,
1358 pgoff_t index, unsigned long max_scan)
1362 for (i = 0; i < max_scan; i++) {
1365 page = radix_tree_lookup(&mapping->i_pages, index);
1366 if (!page || radix_tree_exceptional_entry(page))
1375 EXPORT_SYMBOL(page_cache_next_hole);
1378 * page_cache_prev_hole - find the prev hole (not-present entry)
1381 * @max_scan: maximum range to search
1383 * Search backwards in the range [max(index-max_scan+1, 0), index] for
1386 * Returns: the index of the hole if found, otherwise returns an index
1387 * outside of the set specified (in which case 'index - return >=
1388 * max_scan' will be true). In rare cases of wrap-around, ULONG_MAX
1391 * page_cache_prev_hole may be called under rcu_read_lock. However,
1392 * like radix_tree_gang_lookup, this will not atomically search a
1393 * snapshot of the tree at a single point in time. For example, if a
1394 * hole is created at index 10, then subsequently a hole is created at
1395 * index 5, page_cache_prev_hole covering both indexes may return 5 if
1396 * called under rcu_read_lock.
1398 pgoff_t page_cache_prev_hole(struct address_space *mapping,
1399 pgoff_t index, unsigned long max_scan)
1403 for (i = 0; i < max_scan; i++) {
1406 page = radix_tree_lookup(&mapping->i_pages, index);
1407 if (!page || radix_tree_exceptional_entry(page))
1410 if (index == ULONG_MAX)
1416 EXPORT_SYMBOL(page_cache_prev_hole);
1419 * find_get_entry - find and get a page cache entry
1420 * @mapping: the address_space to search
1421 * @offset: the page cache index
1423 * Looks up the page cache slot at @mapping & @offset. If there is a
1424 * page cache page, it is returned with an increased refcount.
1426 * If the slot holds a shadow entry of a previously evicted page, or a
1427 * swap entry from shmem/tmpfs, it is returned.
1429 * Otherwise, %NULL is returned.
1431 struct page *find_get_entry(struct address_space *mapping, pgoff_t offset)
1434 struct page *head, *page;
1439 pagep = radix_tree_lookup_slot(&mapping->i_pages, offset);
1441 page = radix_tree_deref_slot(pagep);
1442 if (unlikely(!page))
1444 if (radix_tree_exception(page)) {
1445 if (radix_tree_deref_retry(page))
1448 * A shadow entry of a recently evicted page,
1449 * or a swap entry from shmem/tmpfs. Return
1450 * it without attempting to raise page count.
1455 head = compound_head(page);
1456 if (!page_cache_get_speculative(head))
1459 /* The page was split under us? */
1460 if (compound_head(page) != head) {
1466 * Has the page moved?
1467 * This is part of the lockless pagecache protocol. See
1468 * include/linux/pagemap.h for details.
1470 if (unlikely(page != *pagep)) {
1480 EXPORT_SYMBOL(find_get_entry);
1483 * find_lock_entry - locate, pin and lock a page cache entry
1484 * @mapping: the address_space to search
1485 * @offset: the page cache index
1487 * Looks up the page cache slot at @mapping & @offset. If there is a
1488 * page cache page, it is returned locked and with an increased
1491 * If the slot holds a shadow entry of a previously evicted page, or a
1492 * swap entry from shmem/tmpfs, it is returned.
1494 * Otherwise, %NULL is returned.
1496 * find_lock_entry() may sleep.
1498 struct page *find_lock_entry(struct address_space *mapping, pgoff_t offset)
1503 page = find_get_entry(mapping, offset);
1504 if (page && !radix_tree_exception(page)) {
1506 /* Has the page been truncated? */
1507 if (unlikely(page_mapping(page) != mapping)) {
1512 VM_BUG_ON_PAGE(page_to_pgoff(page) != offset, page);
1516 EXPORT_SYMBOL(find_lock_entry);
1519 * pagecache_get_page - find and get a page reference
1520 * @mapping: the address_space to search
1521 * @offset: the page index
1522 * @fgp_flags: PCG flags
1523 * @gfp_mask: gfp mask to use for the page cache data page allocation
1525 * Looks up the page cache slot at @mapping & @offset.
1527 * PCG flags modify how the page is returned.
1529 * @fgp_flags can be:
1531 * - FGP_ACCESSED: the page will be marked accessed
1532 * - FGP_LOCK: Page is return locked
1533 * - FGP_CREAT: If page is not present then a new page is allocated using
1534 * @gfp_mask and added to the page cache and the VM's LRU
1535 * list. The page is returned locked and with an increased
1536 * refcount. Otherwise, NULL is returned.
1538 * If FGP_LOCK or FGP_CREAT are specified then the function may sleep even
1539 * if the GFP flags specified for FGP_CREAT are atomic.
1541 * If there is a page cache page, it is returned with an increased refcount.
1543 struct page *pagecache_get_page(struct address_space *mapping, pgoff_t offset,
1544 int fgp_flags, gfp_t gfp_mask)
1549 page = find_get_entry(mapping, offset);
1550 if (radix_tree_exceptional_entry(page))
1555 if (fgp_flags & FGP_LOCK) {
1556 if (fgp_flags & FGP_NOWAIT) {
1557 if (!trylock_page(page)) {
1565 /* Has the page been truncated? */
1566 if (unlikely(page->mapping != mapping)) {
1571 VM_BUG_ON_PAGE(page->index != offset, page);
1574 if (page && (fgp_flags & FGP_ACCESSED))
1575 mark_page_accessed(page);
1578 if (!page && (fgp_flags & FGP_CREAT)) {
1580 if ((fgp_flags & FGP_WRITE) && mapping_cap_account_dirty(mapping))
1581 gfp_mask |= __GFP_WRITE;
1582 if (fgp_flags & FGP_NOFS)
1583 gfp_mask &= ~__GFP_FS;
1585 page = __page_cache_alloc(gfp_mask);
1589 if (WARN_ON_ONCE(!(fgp_flags & FGP_LOCK)))
1590 fgp_flags |= FGP_LOCK;
1592 /* Init accessed so avoid atomic mark_page_accessed later */
1593 if (fgp_flags & FGP_ACCESSED)
1594 __SetPageReferenced(page);
1596 err = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
1597 if (unlikely(err)) {
1607 EXPORT_SYMBOL(pagecache_get_page);
1610 * find_get_entries - gang pagecache lookup
1611 * @mapping: The address_space to search
1612 * @start: The starting page cache index
1613 * @nr_entries: The maximum number of entries
1614 * @entries: Where the resulting entries are placed
1615 * @indices: The cache indices corresponding to the entries in @entries
1617 * find_get_entries() will search for and return a group of up to
1618 * @nr_entries entries in the mapping. The entries are placed at
1619 * @entries. find_get_entries() takes a reference against any actual
1622 * The search returns a group of mapping-contiguous page cache entries
1623 * with ascending indexes. There may be holes in the indices due to
1624 * not-present pages.
1626 * Any shadow entries of evicted pages, or swap entries from
1627 * shmem/tmpfs, are included in the returned array.
1629 * find_get_entries() returns the number of pages and shadow entries
1632 unsigned find_get_entries(struct address_space *mapping,
1633 pgoff_t start, unsigned int nr_entries,
1634 struct page **entries, pgoff_t *indices)
1637 unsigned int ret = 0;
1638 struct radix_tree_iter iter;
1644 radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start) {
1645 struct page *head, *page;
1647 page = radix_tree_deref_slot(slot);
1648 if (unlikely(!page))
1650 if (radix_tree_exception(page)) {
1651 if (radix_tree_deref_retry(page)) {
1652 slot = radix_tree_iter_retry(&iter);
1656 * A shadow entry of a recently evicted page, a swap
1657 * entry from shmem/tmpfs or a DAX entry. Return it
1658 * without attempting to raise page count.
1663 head = compound_head(page);
1664 if (!page_cache_get_speculative(head))
1667 /* The page was split under us? */
1668 if (compound_head(page) != head) {
1673 /* Has the page moved? */
1674 if (unlikely(page != *slot)) {
1679 indices[ret] = iter.index;
1680 entries[ret] = page;
1681 if (++ret == nr_entries)
1689 * find_get_pages_range - gang pagecache lookup
1690 * @mapping: The address_space to search
1691 * @start: The starting page index
1692 * @end: The final page index (inclusive)
1693 * @nr_pages: The maximum number of pages
1694 * @pages: Where the resulting pages are placed
1696 * find_get_pages_range() will search for and return a group of up to @nr_pages
1697 * pages in the mapping starting at index @start and up to index @end
1698 * (inclusive). The pages are placed at @pages. find_get_pages_range() takes
1699 * a reference against the returned pages.
1701 * The search returns a group of mapping-contiguous pages with ascending
1702 * indexes. There may be holes in the indices due to not-present pages.
1703 * We also update @start to index the next page for the traversal.
1705 * find_get_pages_range() returns the number of pages which were found. If this
1706 * number is smaller than @nr_pages, the end of specified range has been
1709 unsigned find_get_pages_range(struct address_space *mapping, pgoff_t *start,
1710 pgoff_t end, unsigned int nr_pages,
1711 struct page **pages)
1713 struct radix_tree_iter iter;
1717 if (unlikely(!nr_pages))
1721 radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, *start) {
1722 struct page *head, *page;
1724 if (iter.index > end)
1727 page = radix_tree_deref_slot(slot);
1728 if (unlikely(!page))
1731 if (radix_tree_exception(page)) {
1732 if (radix_tree_deref_retry(page)) {
1733 slot = radix_tree_iter_retry(&iter);
1737 * A shadow entry of a recently evicted page,
1738 * or a swap entry from shmem/tmpfs. Skip
1744 head = compound_head(page);
1745 if (!page_cache_get_speculative(head))
1748 /* The page was split under us? */
1749 if (compound_head(page) != head) {
1754 /* Has the page moved? */
1755 if (unlikely(page != *slot)) {
1761 if (++ret == nr_pages) {
1762 *start = pages[ret - 1]->index + 1;
1768 * We come here when there is no page beyond @end. We take care to not
1769 * overflow the index @start as it confuses some of the callers. This
1770 * breaks the iteration when there is page at index -1 but that is
1771 * already broken anyway.
1773 if (end == (pgoff_t)-1)
1774 *start = (pgoff_t)-1;
1784 * find_get_pages_contig - gang contiguous pagecache lookup
1785 * @mapping: The address_space to search
1786 * @index: The starting page index
1787 * @nr_pages: The maximum number of pages
1788 * @pages: Where the resulting pages are placed
1790 * find_get_pages_contig() works exactly like find_get_pages(), except
1791 * that the returned number of pages are guaranteed to be contiguous.
1793 * find_get_pages_contig() returns the number of pages which were found.
1795 unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
1796 unsigned int nr_pages, struct page **pages)
1798 struct radix_tree_iter iter;
1800 unsigned int ret = 0;
1802 if (unlikely(!nr_pages))
1806 radix_tree_for_each_contig(slot, &mapping->i_pages, &iter, index) {
1807 struct page *head, *page;
1809 page = radix_tree_deref_slot(slot);
1810 /* The hole, there no reason to continue */
1811 if (unlikely(!page))
1814 if (radix_tree_exception(page)) {
1815 if (radix_tree_deref_retry(page)) {
1816 slot = radix_tree_iter_retry(&iter);
1820 * A shadow entry of a recently evicted page,
1821 * or a swap entry from shmem/tmpfs. Stop
1822 * looking for contiguous pages.
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 * must check mapping and index after taking the ref.
1845 * otherwise we can get both false positives and false
1846 * negatives, which is just confusing to the caller.
1848 if (page->mapping == NULL || page_to_pgoff(page) != iter.index) {
1854 if (++ret == nr_pages)
1860 EXPORT_SYMBOL(find_get_pages_contig);
1863 * find_get_pages_range_tag - find and return pages in given range matching @tag
1864 * @mapping: the address_space to search
1865 * @index: the starting page index
1866 * @end: The final page index (inclusive)
1867 * @tag: the tag index
1868 * @nr_pages: the maximum number of pages
1869 * @pages: where the resulting pages are placed
1871 * Like find_get_pages, except we only return pages which are tagged with
1872 * @tag. We update @index to index the next page for the traversal.
1874 unsigned find_get_pages_range_tag(struct address_space *mapping, pgoff_t *index,
1875 pgoff_t end, int tag, unsigned int nr_pages,
1876 struct page **pages)
1878 struct radix_tree_iter iter;
1882 if (unlikely(!nr_pages))
1886 radix_tree_for_each_tagged(slot, &mapping->i_pages, &iter, *index, tag) {
1887 struct page *head, *page;
1889 if (iter.index > end)
1892 page = radix_tree_deref_slot(slot);
1893 if (unlikely(!page))
1896 if (radix_tree_exception(page)) {
1897 if (radix_tree_deref_retry(page)) {
1898 slot = radix_tree_iter_retry(&iter);
1902 * A shadow entry of a recently evicted page.
1904 * Those entries should never be tagged, but
1905 * this tree walk is lockless and the tags are
1906 * looked up in bulk, one radix tree node at a
1907 * time, so there is a sizable window for page
1908 * reclaim to evict a page we saw tagged.
1915 head = compound_head(page);
1916 if (!page_cache_get_speculative(head))
1919 /* The page was split under us? */
1920 if (compound_head(page) != head) {
1925 /* Has the page moved? */
1926 if (unlikely(page != *slot)) {
1932 if (++ret == nr_pages) {
1933 *index = pages[ret - 1]->index + 1;
1939 * We come here when we got at @end. We take care to not overflow the
1940 * index @index as it confuses some of the callers. This breaks the
1941 * iteration when there is page at index -1 but that is already broken
1944 if (end == (pgoff_t)-1)
1945 *index = (pgoff_t)-1;
1953 EXPORT_SYMBOL(find_get_pages_range_tag);
1956 * find_get_entries_tag - find and return entries that match @tag
1957 * @mapping: the address_space to search
1958 * @start: the starting page cache index
1959 * @tag: the tag index
1960 * @nr_entries: the maximum number of entries
1961 * @entries: where the resulting entries are placed
1962 * @indices: the cache indices corresponding to the entries in @entries
1964 * Like find_get_entries, except we only return entries which are tagged with
1967 unsigned find_get_entries_tag(struct address_space *mapping, pgoff_t start,
1968 int tag, unsigned int nr_entries,
1969 struct page **entries, pgoff_t *indices)
1972 unsigned int ret = 0;
1973 struct radix_tree_iter iter;
1979 radix_tree_for_each_tagged(slot, &mapping->i_pages, &iter, start, tag) {
1980 struct page *head, *page;
1982 page = radix_tree_deref_slot(slot);
1983 if (unlikely(!page))
1985 if (radix_tree_exception(page)) {
1986 if (radix_tree_deref_retry(page)) {
1987 slot = radix_tree_iter_retry(&iter);
1992 * A shadow entry of a recently evicted page, a swap
1993 * entry from shmem/tmpfs or a DAX entry. Return it
1994 * without attempting to raise page count.
1999 head = compound_head(page);
2000 if (!page_cache_get_speculative(head))
2003 /* The page was split under us? */
2004 if (compound_head(page) != head) {
2009 /* Has the page moved? */
2010 if (unlikely(page != *slot)) {
2015 indices[ret] = iter.index;
2016 entries[ret] = page;
2017 if (++ret == nr_entries)
2023 EXPORT_SYMBOL(find_get_entries_tag);
2026 * CD/DVDs are error prone. When a medium error occurs, the driver may fail
2027 * a _large_ part of the i/o request. Imagine the worst scenario:
2029 * ---R__________________________________________B__________
2030 * ^ reading here ^ bad block(assume 4k)
2032 * read(R) => miss => readahead(R...B) => media error => frustrating retries
2033 * => failing the whole request => read(R) => read(R+1) =>
2034 * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
2035 * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
2036 * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
2038 * It is going insane. Fix it by quickly scaling down the readahead size.
2040 static void shrink_readahead_size_eio(struct file *filp,
2041 struct file_ra_state *ra)
2047 * generic_file_buffered_read - generic file read routine
2048 * @iocb: the iocb to read
2049 * @iter: data destination
2050 * @written: already copied
2052 * This is a generic file read routine, and uses the
2053 * mapping->a_ops->readpage() function for the actual low-level stuff.
2055 * This is really ugly. But the goto's actually try to clarify some
2056 * of the logic when it comes to error handling etc.
2058 static ssize_t generic_file_buffered_read(struct kiocb *iocb,
2059 struct iov_iter *iter, ssize_t written)
2061 struct file *filp = iocb->ki_filp;
2062 struct address_space *mapping = filp->f_mapping;
2063 struct inode *inode = mapping->host;
2064 struct file_ra_state *ra = &filp->f_ra;
2065 loff_t *ppos = &iocb->ki_pos;
2069 unsigned long offset; /* offset into pagecache page */
2070 unsigned int prev_offset;
2073 if (unlikely(*ppos >= inode->i_sb->s_maxbytes))
2075 iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
2077 index = *ppos >> PAGE_SHIFT;
2078 prev_index = ra->prev_pos >> PAGE_SHIFT;
2079 prev_offset = ra->prev_pos & (PAGE_SIZE-1);
2080 last_index = (*ppos + iter->count + PAGE_SIZE-1) >> PAGE_SHIFT;
2081 offset = *ppos & ~PAGE_MASK;
2087 unsigned long nr, ret;
2091 if (fatal_signal_pending(current)) {
2096 page = find_get_page(mapping, index);
2098 if (iocb->ki_flags & IOCB_NOWAIT)
2100 page_cache_sync_readahead(mapping,
2102 index, last_index - index);
2103 page = find_get_page(mapping, index);
2104 if (unlikely(page == NULL))
2105 goto no_cached_page;
2107 if (PageReadahead(page)) {
2108 page_cache_async_readahead(mapping,
2110 index, last_index - index);
2112 if (!PageUptodate(page)) {
2113 if (iocb->ki_flags & IOCB_NOWAIT) {
2119 * See comment in do_read_cache_page on why
2120 * wait_on_page_locked is used to avoid unnecessarily
2121 * serialisations and why it's safe.
2123 error = wait_on_page_locked_killable(page);
2124 if (unlikely(error))
2125 goto readpage_error;
2126 if (PageUptodate(page))
2129 if (inode->i_blkbits == PAGE_SHIFT ||
2130 !mapping->a_ops->is_partially_uptodate)
2131 goto page_not_up_to_date;
2132 /* pipes can't handle partially uptodate pages */
2133 if (unlikely(iter->type & ITER_PIPE))
2134 goto page_not_up_to_date;
2135 if (!trylock_page(page))
2136 goto page_not_up_to_date;
2137 /* Did it get truncated before we got the lock? */
2139 goto page_not_up_to_date_locked;
2140 if (!mapping->a_ops->is_partially_uptodate(page,
2141 offset, iter->count))
2142 goto page_not_up_to_date_locked;
2147 * i_size must be checked after we know the page is Uptodate.
2149 * Checking i_size after the check allows us to calculate
2150 * the correct value for "nr", which means the zero-filled
2151 * part of the page is not copied back to userspace (unless
2152 * another truncate extends the file - this is desired though).
2155 isize = i_size_read(inode);
2156 end_index = (isize - 1) >> PAGE_SHIFT;
2157 if (unlikely(!isize || index > end_index)) {
2162 /* nr is the maximum number of bytes to copy from this page */
2164 if (index == end_index) {
2165 nr = ((isize - 1) & ~PAGE_MASK) + 1;
2173 /* If users can be writing to this page using arbitrary
2174 * virtual addresses, take care about potential aliasing
2175 * before reading the page on the kernel side.
2177 if (mapping_writably_mapped(mapping))
2178 flush_dcache_page(page);
2181 * When a sequential read accesses a page several times,
2182 * only mark it as accessed the first time.
2184 if (prev_index != index || offset != prev_offset)
2185 mark_page_accessed(page);
2189 * Ok, we have the page, and it's up-to-date, so
2190 * now we can copy it to user space...
2193 ret = copy_page_to_iter(page, offset, nr, iter);
2195 index += offset >> PAGE_SHIFT;
2196 offset &= ~PAGE_MASK;
2197 prev_offset = offset;
2201 if (!iov_iter_count(iter))
2209 page_not_up_to_date:
2210 /* Get exclusive access to the page ... */
2211 error = lock_page_killable(page);
2212 if (unlikely(error))
2213 goto readpage_error;
2215 page_not_up_to_date_locked:
2216 /* Did it get truncated before we got the lock? */
2217 if (!page->mapping) {
2223 /* Did somebody else fill it already? */
2224 if (PageUptodate(page)) {
2231 * A previous I/O error may have been due to temporary
2232 * failures, eg. multipath errors.
2233 * PG_error will be set again if readpage fails.
2235 ClearPageError(page);
2236 /* Start the actual read. The read will unlock the page. */
2237 error = mapping->a_ops->readpage(filp, page);
2239 if (unlikely(error)) {
2240 if (error == AOP_TRUNCATED_PAGE) {
2245 goto readpage_error;
2248 if (!PageUptodate(page)) {
2249 error = lock_page_killable(page);
2250 if (unlikely(error))
2251 goto readpage_error;
2252 if (!PageUptodate(page)) {
2253 if (page->mapping == NULL) {
2255 * invalidate_mapping_pages got it
2262 shrink_readahead_size_eio(filp, ra);
2264 goto readpage_error;
2272 /* UHHUH! A synchronous read error occurred. Report it */
2278 * Ok, it wasn't cached, so we need to create a new
2281 page = page_cache_alloc(mapping);
2286 error = add_to_page_cache_lru(page, mapping, index,
2287 mapping_gfp_constraint(mapping, GFP_KERNEL));
2290 if (error == -EEXIST) {
2302 ra->prev_pos = prev_index;
2303 ra->prev_pos <<= PAGE_SHIFT;
2304 ra->prev_pos |= prev_offset;
2306 *ppos = ((loff_t)index << PAGE_SHIFT) + offset;
2307 file_accessed(filp);
2308 return written ? written : error;
2312 * generic_file_read_iter - generic filesystem read routine
2313 * @iocb: kernel I/O control block
2314 * @iter: destination for the data read
2316 * This is the "read_iter()" routine for all filesystems
2317 * that can use the page cache directly.
2320 generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
2322 size_t count = iov_iter_count(iter);
2326 goto out; /* skip atime */
2328 if (iocb->ki_flags & IOCB_DIRECT) {
2329 struct file *file = iocb->ki_filp;
2330 struct address_space *mapping = file->f_mapping;
2331 struct inode *inode = mapping->host;
2334 size = i_size_read(inode);
2335 if (iocb->ki_flags & IOCB_NOWAIT) {
2336 if (filemap_range_has_page(mapping, iocb->ki_pos,
2337 iocb->ki_pos + count - 1))
2340 retval = filemap_write_and_wait_range(mapping,
2342 iocb->ki_pos + count - 1);
2347 file_accessed(file);
2349 retval = mapping->a_ops->direct_IO(iocb, iter);
2351 iocb->ki_pos += retval;
2354 iov_iter_revert(iter, count - iov_iter_count(iter));
2357 * Btrfs can have a short DIO read if we encounter
2358 * compressed extents, so if there was an error, or if
2359 * we've already read everything we wanted to, or if
2360 * there was a short read because we hit EOF, go ahead
2361 * and return. Otherwise fallthrough to buffered io for
2362 * the rest of the read. Buffered reads will not work for
2363 * DAX files, so don't bother trying.
2365 if (retval < 0 || !count || iocb->ki_pos >= size ||
2370 retval = generic_file_buffered_read(iocb, iter, retval);
2374 EXPORT_SYMBOL(generic_file_read_iter);
2378 * page_cache_read - adds requested page to the page cache if not already there
2379 * @file: file to read
2380 * @offset: page index
2381 * @gfp_mask: memory allocation flags
2383 * This adds the requested page to the page cache if it isn't already there,
2384 * and schedules an I/O to read in its contents from disk.
2386 static int page_cache_read(struct file *file, pgoff_t offset, gfp_t gfp_mask)
2388 struct address_space *mapping = file->f_mapping;
2393 page = __page_cache_alloc(gfp_mask);
2397 ret = add_to_page_cache_lru(page, mapping, offset, gfp_mask);
2399 ret = mapping->a_ops->readpage(file, page);
2400 else if (ret == -EEXIST)
2401 ret = 0; /* losing race to add is OK */
2405 } while (ret == AOP_TRUNCATED_PAGE);
2410 #define MMAP_LOTSAMISS (100)
2413 * Synchronous readahead happens when we don't even find
2414 * a page in the page cache at all.
2416 static void do_sync_mmap_readahead(struct vm_area_struct *vma,
2417 struct file_ra_state *ra,
2421 struct address_space *mapping = file->f_mapping;
2423 /* If we don't want any read-ahead, don't bother */
2424 if (vma->vm_flags & VM_RAND_READ)
2429 if (vma->vm_flags & VM_SEQ_READ) {
2430 page_cache_sync_readahead(mapping, ra, file, offset,
2435 /* Avoid banging the cache line if not needed */
2436 if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
2440 * Do we miss much more than hit in this file? If so,
2441 * stop bothering with read-ahead. It will only hurt.
2443 if (ra->mmap_miss > MMAP_LOTSAMISS)
2449 ra->start = max_t(long, 0, offset - ra->ra_pages / 2);
2450 ra->size = ra->ra_pages;
2451 ra->async_size = ra->ra_pages / 4;
2452 ra_submit(ra, mapping, file);
2456 * Asynchronous readahead happens when we find the page and PG_readahead,
2457 * so we want to possibly extend the readahead further..
2459 static void do_async_mmap_readahead(struct vm_area_struct *vma,
2460 struct file_ra_state *ra,
2465 struct address_space *mapping = file->f_mapping;
2467 /* If we don't want any read-ahead, don't bother */
2468 if (vma->vm_flags & VM_RAND_READ)
2470 if (ra->mmap_miss > 0)
2472 if (PageReadahead(page))
2473 page_cache_async_readahead(mapping, ra, file,
2474 page, offset, ra->ra_pages);
2478 * filemap_fault - read in file data for page fault handling
2479 * @vmf: struct vm_fault containing details of the fault
2481 * filemap_fault() is invoked via the vma operations vector for a
2482 * mapped memory region to read in file data during a page fault.
2484 * The goto's are kind of ugly, but this streamlines the normal case of having
2485 * it in the page cache, and handles the special cases reasonably without
2486 * having a lot of duplicated code.
2488 * vma->vm_mm->mmap_sem must be held on entry.
2490 * If our return value has VM_FAULT_RETRY set, it's because
2491 * lock_page_or_retry() returned 0.
2492 * The mmap_sem has usually been released in this case.
2493 * See __lock_page_or_retry() for the exception.
2495 * If our return value does not have VM_FAULT_RETRY set, the mmap_sem
2496 * has not been released.
2498 * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
2500 vm_fault_t filemap_fault(struct vm_fault *vmf)
2503 struct file *file = vmf->vma->vm_file;
2504 struct address_space *mapping = file->f_mapping;
2505 struct file_ra_state *ra = &file->f_ra;
2506 struct inode *inode = mapping->host;
2507 pgoff_t offset = vmf->pgoff;
2512 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2513 if (unlikely(offset >= max_off))
2514 return VM_FAULT_SIGBUS;
2517 * Do we have something in the page cache already?
2519 page = find_get_page(mapping, offset);
2520 if (likely(page) && !(vmf->flags & FAULT_FLAG_TRIED)) {
2522 * We found the page, so try async readahead before
2523 * waiting for the lock.
2525 do_async_mmap_readahead(vmf->vma, ra, file, page, offset);
2527 /* No page in the page cache at all */
2528 do_sync_mmap_readahead(vmf->vma, ra, file, offset);
2529 count_vm_event(PGMAJFAULT);
2530 count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
2531 ret = VM_FAULT_MAJOR;
2533 page = find_get_page(mapping, offset);
2535 goto no_cached_page;
2538 if (!lock_page_or_retry(page, vmf->vma->vm_mm, vmf->flags)) {
2540 return ret | VM_FAULT_RETRY;
2543 /* Did it get truncated? */
2544 if (unlikely(page->mapping != mapping)) {
2549 VM_BUG_ON_PAGE(page->index != offset, page);
2552 * We have a locked page in the page cache, now we need to check
2553 * that it's up-to-date. If not, it is going to be due to an error.
2555 if (unlikely(!PageUptodate(page)))
2556 goto page_not_uptodate;
2559 * Found the page and have a reference on it.
2560 * We must recheck i_size under page lock.
2562 max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
2563 if (unlikely(offset >= max_off)) {
2566 return VM_FAULT_SIGBUS;
2570 return ret | VM_FAULT_LOCKED;
2574 * We're only likely to ever get here if MADV_RANDOM is in
2577 error = page_cache_read(file, offset, vmf->gfp_mask);
2580 * The page we want has now been added to the page cache.
2581 * In the unlikely event that someone removed it in the
2582 * meantime, we'll just come back here and read it again.
2588 * An error return from page_cache_read can result if the
2589 * system is low on memory, or a problem occurs while trying
2592 if (error == -ENOMEM)
2593 return VM_FAULT_OOM;
2594 return VM_FAULT_SIGBUS;
2598 * Umm, take care of errors if the page isn't up-to-date.
2599 * Try to re-read it _once_. We do this synchronously,
2600 * because there really aren't any performance issues here
2601 * and we need to check for errors.
2603 ClearPageError(page);
2604 error = mapping->a_ops->readpage(file, page);
2606 wait_on_page_locked(page);
2607 if (!PageUptodate(page))
2612 if (!error || error == AOP_TRUNCATED_PAGE)
2615 /* Things didn't work out. Return zero to tell the mm layer so. */
2616 shrink_readahead_size_eio(file, ra);
2617 return VM_FAULT_SIGBUS;
2619 EXPORT_SYMBOL(filemap_fault);
2621 void filemap_map_pages(struct vm_fault *vmf,
2622 pgoff_t start_pgoff, pgoff_t end_pgoff)
2624 struct radix_tree_iter iter;
2626 struct file *file = vmf->vma->vm_file;
2627 struct address_space *mapping = file->f_mapping;
2628 pgoff_t last_pgoff = start_pgoff;
2629 unsigned long max_idx;
2630 struct page *head, *page;
2633 radix_tree_for_each_slot(slot, &mapping->i_pages, &iter, start_pgoff) {
2634 if (iter.index > end_pgoff)
2637 page = radix_tree_deref_slot(slot);
2638 if (unlikely(!page))
2640 if (radix_tree_exception(page)) {
2641 if (radix_tree_deref_retry(page)) {
2642 slot = radix_tree_iter_retry(&iter);
2648 head = compound_head(page);
2649 if (!page_cache_get_speculative(head))
2652 /* The page was split under us? */
2653 if (compound_head(page) != head) {
2658 /* Has the page moved? */
2659 if (unlikely(page != *slot)) {
2664 if (!PageUptodate(page) ||
2665 PageReadahead(page) ||
2668 if (!trylock_page(page))
2671 if (page->mapping != mapping || !PageUptodate(page))
2674 max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
2675 if (page->index >= max_idx)
2678 if (file->f_ra.mmap_miss > 0)
2679 file->f_ra.mmap_miss--;
2681 vmf->address += (iter.index - last_pgoff) << PAGE_SHIFT;
2683 vmf->pte += iter.index - last_pgoff;
2684 last_pgoff = iter.index;
2685 if (alloc_set_pte(vmf, NULL, page))
2694 /* Huge page is mapped? No need to proceed. */
2695 if (pmd_trans_huge(*vmf->pmd))
2697 if (iter.index == end_pgoff)
2702 EXPORT_SYMBOL(filemap_map_pages);
2704 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
2706 struct page *page = vmf->page;
2707 struct inode *inode = file_inode(vmf->vma->vm_file);
2708 vm_fault_t ret = VM_FAULT_LOCKED;
2710 sb_start_pagefault(inode->i_sb);
2711 file_update_time(vmf->vma->vm_file);
2713 if (page->mapping != inode->i_mapping) {
2715 ret = VM_FAULT_NOPAGE;
2719 * We mark the page dirty already here so that when freeze is in
2720 * progress, we are guaranteed that writeback during freezing will
2721 * see the dirty page and writeprotect it again.
2723 set_page_dirty(page);
2724 wait_for_stable_page(page);
2726 sb_end_pagefault(inode->i_sb);
2730 const struct vm_operations_struct generic_file_vm_ops = {
2731 .fault = filemap_fault,
2732 .map_pages = filemap_map_pages,
2733 .page_mkwrite = filemap_page_mkwrite,
2736 /* This is used for a general mmap of a disk file */
2738 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2740 struct address_space *mapping = file->f_mapping;
2742 if (!mapping->a_ops->readpage)
2744 file_accessed(file);
2745 vma->vm_ops = &generic_file_vm_ops;
2750 * This is for filesystems which do not implement ->writepage.
2752 int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
2754 if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
2756 return generic_file_mmap(file, vma);
2759 vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
2761 return VM_FAULT_SIGBUS;
2763 int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
2767 int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
2771 #endif /* CONFIG_MMU */
2773 EXPORT_SYMBOL(filemap_page_mkwrite);
2774 EXPORT_SYMBOL(generic_file_mmap);
2775 EXPORT_SYMBOL(generic_file_readonly_mmap);
2777 static struct page *wait_on_page_read(struct page *page)
2779 if (!IS_ERR(page)) {
2780 wait_on_page_locked(page);
2781 if (!PageUptodate(page)) {
2783 page = ERR_PTR(-EIO);
2789 static struct page *do_read_cache_page(struct address_space *mapping,
2791 int (*filler)(void *, struct page *),
2798 page = find_get_page(mapping, index);
2800 page = __page_cache_alloc(gfp);
2802 return ERR_PTR(-ENOMEM);
2803 err = add_to_page_cache_lru(page, mapping, index, gfp);
2804 if (unlikely(err)) {
2808 /* Presumably ENOMEM for radix tree node */
2809 return ERR_PTR(err);
2813 err = filler(data, page);
2816 return ERR_PTR(err);
2819 page = wait_on_page_read(page);
2824 if (PageUptodate(page))
2828 * Page is not up to date and may be locked due one of the following
2829 * case a: Page is being filled and the page lock is held
2830 * case b: Read/write error clearing the page uptodate status
2831 * case c: Truncation in progress (page locked)
2832 * case d: Reclaim in progress
2834 * Case a, the page will be up to date when the page is unlocked.
2835 * There is no need to serialise on the page lock here as the page
2836 * is pinned so the lock gives no additional protection. Even if the
2837 * the page is truncated, the data is still valid if PageUptodate as
2838 * it's a race vs truncate race.
2839 * Case b, the page will not be up to date
2840 * Case c, the page may be truncated but in itself, the data may still
2841 * be valid after IO completes as it's a read vs truncate race. The
2842 * operation must restart if the page is not uptodate on unlock but
2843 * otherwise serialising on page lock to stabilise the mapping gives
2844 * no additional guarantees to the caller as the page lock is
2845 * released before return.
2846 * Case d, similar to truncation. If reclaim holds the page lock, it
2847 * will be a race with remove_mapping that determines if the mapping
2848 * is valid on unlock but otherwise the data is valid and there is
2849 * no need to serialise with page lock.
2851 * As the page lock gives no additional guarantee, we optimistically
2852 * wait on the page to be unlocked and check if it's up to date and
2853 * use the page if it is. Otherwise, the page lock is required to
2854 * distinguish between the different cases. The motivation is that we
2855 * avoid spurious serialisations and wakeups when multiple processes
2856 * wait on the same page for IO to complete.
2858 wait_on_page_locked(page);
2859 if (PageUptodate(page))
2862 /* Distinguish between all the cases under the safety of the lock */
2865 /* Case c or d, restart the operation */
2866 if (!page->mapping) {
2872 /* Someone else locked and filled the page in a very small window */
2873 if (PageUptodate(page)) {
2880 mark_page_accessed(page);
2885 * read_cache_page - read into page cache, fill it if needed
2886 * @mapping: the page's address_space
2887 * @index: the page index
2888 * @filler: function to perform the read
2889 * @data: first arg to filler(data, page) function, often left as NULL
2891 * Read into the page cache. If a page already exists, and PageUptodate() is
2892 * not set, try to fill the page and wait for it to become unlocked.
2894 * If the page does not get brought uptodate, return -EIO.
2896 struct page *read_cache_page(struct address_space *mapping,
2898 int (*filler)(void *, struct page *),
2901 return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
2903 EXPORT_SYMBOL(read_cache_page);
2906 * read_cache_page_gfp - read into page cache, using specified page allocation flags.
2907 * @mapping: the page's address_space
2908 * @index: the page index
2909 * @gfp: the page allocator flags to use if allocating
2911 * This is the same as "read_mapping_page(mapping, index, NULL)", but with
2912 * any new page allocations done using the specified allocation flags.
2914 * If the page does not get brought uptodate, return -EIO.
2916 struct page *read_cache_page_gfp(struct address_space *mapping,
2920 filler_t *filler = (filler_t *)mapping->a_ops->readpage;
2922 return do_read_cache_page(mapping, index, filler, NULL, gfp);
2924 EXPORT_SYMBOL(read_cache_page_gfp);
2927 * Performs necessary checks before doing a write
2929 * Can adjust writing position or amount of bytes to write.
2930 * Returns appropriate error code that caller should return or
2931 * zero in case that write should be allowed.
2933 inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
2935 struct file *file = iocb->ki_filp;
2936 struct inode *inode = file->f_mapping->host;
2937 unsigned long limit = rlimit(RLIMIT_FSIZE);
2940 if (!iov_iter_count(from))
2943 /* FIXME: this is for backwards compatibility with 2.4 */
2944 if (iocb->ki_flags & IOCB_APPEND)
2945 iocb->ki_pos = i_size_read(inode);
2949 if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2952 if (limit != RLIM_INFINITY) {
2953 if (iocb->ki_pos >= limit) {
2954 send_sig(SIGXFSZ, current, 0);
2957 iov_iter_truncate(from, limit - (unsigned long)pos);
2963 if (unlikely(pos + iov_iter_count(from) > MAX_NON_LFS &&
2964 !(file->f_flags & O_LARGEFILE))) {
2965 if (pos >= MAX_NON_LFS)
2967 iov_iter_truncate(from, MAX_NON_LFS - (unsigned long)pos);
2971 * Are we about to exceed the fs block limit ?
2973 * If we have written data it becomes a short write. If we have
2974 * exceeded without writing data we send a signal and return EFBIG.
2975 * Linus frestrict idea will clean these up nicely..
2977 if (unlikely(pos >= inode->i_sb->s_maxbytes))
2980 iov_iter_truncate(from, inode->i_sb->s_maxbytes - pos);
2981 return iov_iter_count(from);
2983 EXPORT_SYMBOL(generic_write_checks);
2985 int pagecache_write_begin(struct file *file, struct address_space *mapping,
2986 loff_t pos, unsigned len, unsigned flags,
2987 struct page **pagep, void **fsdata)
2989 const struct address_space_operations *aops = mapping->a_ops;
2991 return aops->write_begin(file, mapping, pos, len, flags,
2994 EXPORT_SYMBOL(pagecache_write_begin);
2996 int pagecache_write_end(struct file *file, struct address_space *mapping,
2997 loff_t pos, unsigned len, unsigned copied,
2998 struct page *page, void *fsdata)
3000 const struct address_space_operations *aops = mapping->a_ops;
3002 return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
3004 EXPORT_SYMBOL(pagecache_write_end);
3007 generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
3009 struct file *file = iocb->ki_filp;
3010 struct address_space *mapping = file->f_mapping;
3011 struct inode *inode = mapping->host;
3012 loff_t pos = iocb->ki_pos;
3017 write_len = iov_iter_count(from);
3018 end = (pos + write_len - 1) >> PAGE_SHIFT;
3020 if (iocb->ki_flags & IOCB_NOWAIT) {
3021 /* If there are pages to writeback, return */
3022 if (filemap_range_has_page(inode->i_mapping, pos,
3023 pos + iov_iter_count(from)))
3026 written = filemap_write_and_wait_range(mapping, pos,
3027 pos + write_len - 1);
3033 * After a write we want buffered reads to be sure to go to disk to get
3034 * the new data. We invalidate clean cached page from the region we're
3035 * about to write. We do this *before* the write so that we can return
3036 * without clobbering -EIOCBQUEUED from ->direct_IO().
3038 written = invalidate_inode_pages2_range(mapping,
3039 pos >> PAGE_SHIFT, end);
3041 * If a page can not be invalidated, return 0 to fall back
3042 * to buffered write.
3045 if (written == -EBUSY)
3050 written = mapping->a_ops->direct_IO(iocb, from);
3053 * Finally, try again to invalidate clean pages which might have been
3054 * cached by non-direct readahead, or faulted in by get_user_pages()
3055 * if the source of the write was an mmap'ed region of the file
3056 * we're writing. Either one is a pretty crazy thing to do,
3057 * so we don't support it 100%. If this invalidation
3058 * fails, tough, the write still worked...
3060 * Most of the time we do not need this since dio_complete() will do
3061 * the invalidation for us. However there are some file systems that
3062 * do not end up with dio_complete() being called, so let's not break
3063 * them by removing it completely
3065 if (mapping->nrpages)
3066 invalidate_inode_pages2_range(mapping,
3067 pos >> PAGE_SHIFT, end);
3071 write_len -= written;
3072 if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
3073 i_size_write(inode, pos);
3074 mark_inode_dirty(inode);
3078 iov_iter_revert(from, write_len - iov_iter_count(from));
3082 EXPORT_SYMBOL(generic_file_direct_write);
3085 * Find or create a page at the given pagecache position. Return the locked
3086 * page. This function is specifically for buffered writes.
3088 struct page *grab_cache_page_write_begin(struct address_space *mapping,
3089 pgoff_t index, unsigned flags)
3092 int fgp_flags = FGP_LOCK|FGP_WRITE|FGP_CREAT;
3094 if (flags & AOP_FLAG_NOFS)
3095 fgp_flags |= FGP_NOFS;
3097 page = pagecache_get_page(mapping, index, fgp_flags,
3098 mapping_gfp_mask(mapping));
3100 wait_for_stable_page(page);
3104 EXPORT_SYMBOL(grab_cache_page_write_begin);
3106 ssize_t generic_perform_write(struct file *file,
3107 struct iov_iter *i, loff_t pos)
3109 struct address_space *mapping = file->f_mapping;
3110 const struct address_space_operations *a_ops = mapping->a_ops;
3112 ssize_t written = 0;
3113 unsigned int flags = 0;
3117 unsigned long offset; /* Offset into pagecache page */
3118 unsigned long bytes; /* Bytes to write to page */
3119 size_t copied; /* Bytes copied from user */
3122 offset = (pos & (PAGE_SIZE - 1));
3123 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3128 * Bring in the user page that we will copy from _first_.
3129 * Otherwise there's a nasty deadlock on copying from the
3130 * same page as we're writing to, without it being marked
3133 * Not only is this an optimisation, but it is also required
3134 * to check that the address is actually valid, when atomic
3135 * usercopies are used, below.
3137 if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
3142 if (fatal_signal_pending(current)) {
3147 status = a_ops->write_begin(file, mapping, pos, bytes, flags,
3149 if (unlikely(status < 0))
3152 if (mapping_writably_mapped(mapping))
3153 flush_dcache_page(page);
3155 copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
3156 flush_dcache_page(page);
3158 status = a_ops->write_end(file, mapping, pos, bytes, copied,
3160 if (unlikely(status < 0))
3166 iov_iter_advance(i, copied);
3167 if (unlikely(copied == 0)) {
3169 * If we were unable to copy any data at all, we must
3170 * fall back to a single segment length write.
3172 * If we didn't fallback here, we could livelock
3173 * because not all segments in the iov can be copied at
3174 * once without a pagefault.
3176 bytes = min_t(unsigned long, PAGE_SIZE - offset,
3177 iov_iter_single_seg_count(i));
3183 balance_dirty_pages_ratelimited(mapping);
3184 } while (iov_iter_count(i));
3186 return written ? written : status;
3188 EXPORT_SYMBOL(generic_perform_write);
3191 * __generic_file_write_iter - write data to a file
3192 * @iocb: IO state structure (file, offset, etc.)
3193 * @from: iov_iter with data to write
3195 * This function does all the work needed for actually writing data to a
3196 * file. It does all basic checks, removes SUID from the file, updates
3197 * modification times and calls proper subroutines depending on whether we
3198 * do direct IO or a standard buffered write.
3200 * It expects i_mutex to be grabbed unless we work on a block device or similar
3201 * object which does not need locking at all.
3203 * This function does *not* take care of syncing data in case of O_SYNC write.
3204 * A caller has to handle it. This is mainly due to the fact that we want to
3205 * avoid syncing under i_mutex.
3207 ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3209 struct file *file = iocb->ki_filp;
3210 struct address_space * mapping = file->f_mapping;
3211 struct inode *inode = mapping->host;
3212 ssize_t written = 0;
3216 /* We can write back this queue in page reclaim */
3217 current->backing_dev_info = inode_to_bdi(inode);
3218 err = file_remove_privs(file);
3222 err = file_update_time(file);
3226 if (iocb->ki_flags & IOCB_DIRECT) {
3227 loff_t pos, endbyte;
3229 written = generic_file_direct_write(iocb, from);
3231 * If the write stopped short of completing, fall back to
3232 * buffered writes. Some filesystems do this for writes to
3233 * holes, for example. For DAX files, a buffered write will
3234 * not succeed (even if it did, DAX does not handle dirty
3235 * page-cache pages correctly).
3237 if (written < 0 || !iov_iter_count(from) || IS_DAX(inode))
3240 status = generic_perform_write(file, from, pos = iocb->ki_pos);
3242 * If generic_perform_write() returned a synchronous error
3243 * then we want to return the number of bytes which were
3244 * direct-written, or the error code if that was zero. Note
3245 * that this differs from normal direct-io semantics, which
3246 * will return -EFOO even if some bytes were written.
3248 if (unlikely(status < 0)) {
3253 * We need to ensure that the page cache pages are written to
3254 * disk and invalidated to preserve the expected O_DIRECT
3257 endbyte = pos + status - 1;
3258 err = filemap_write_and_wait_range(mapping, pos, endbyte);
3260 iocb->ki_pos = endbyte + 1;
3262 invalidate_mapping_pages(mapping,
3264 endbyte >> PAGE_SHIFT);
3267 * We don't know how much we wrote, so just return
3268 * the number of bytes which were direct-written
3272 written = generic_perform_write(file, from, iocb->ki_pos);
3273 if (likely(written > 0))
3274 iocb->ki_pos += written;
3277 current->backing_dev_info = NULL;
3278 return written ? written : err;
3280 EXPORT_SYMBOL(__generic_file_write_iter);
3283 * generic_file_write_iter - write data to a file
3284 * @iocb: IO state structure
3285 * @from: iov_iter with data to write
3287 * This is a wrapper around __generic_file_write_iter() to be used by most
3288 * filesystems. It takes care of syncing the file in case of O_SYNC file
3289 * and acquires i_mutex as needed.
3291 ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
3293 struct file *file = iocb->ki_filp;
3294 struct inode *inode = file->f_mapping->host;
3298 ret = generic_write_checks(iocb, from);
3300 ret = __generic_file_write_iter(iocb, from);
3301 inode_unlock(inode);
3304 ret = generic_write_sync(iocb, ret);
3307 EXPORT_SYMBOL(generic_file_write_iter);
3310 * try_to_release_page() - release old fs-specific metadata on a page
3312 * @page: the page which the kernel is trying to free
3313 * @gfp_mask: memory allocation flags (and I/O mode)
3315 * The address_space is to try to release any data against the page
3316 * (presumably at page->private). If the release was successful, return '1'.
3317 * Otherwise return zero.
3319 * This may also be called if PG_fscache is set on a page, indicating that the
3320 * page is known to the local caching routines.
3322 * The @gfp_mask argument specifies whether I/O may be performed to release
3323 * this page (__GFP_IO), and whether the call may block (__GFP_RECLAIM & __GFP_FS).
3326 int try_to_release_page(struct page *page, gfp_t gfp_mask)
3328 struct address_space * const mapping = page->mapping;
3330 BUG_ON(!PageLocked(page));
3331 if (PageWriteback(page))
3334 if (mapping && mapping->a_ops->releasepage)
3335 return mapping->a_ops->releasepage(page, gfp_mask);
3336 return try_to_free_buffers(page);
3339 EXPORT_SYMBOL(try_to_release_page);