xref: /openbmc/linux/mm/filemap.c (revision b79f9e1f)
1457c8996SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *	linux/mm/filemap.c
41da177e4SLinus Torvalds  *
51da177e4SLinus Torvalds  * Copyright (C) 1994-1999  Linus Torvalds
61da177e4SLinus Torvalds  */
71da177e4SLinus Torvalds 
81da177e4SLinus Torvalds /*
91da177e4SLinus Torvalds  * This file handles the generic file mmap semantics used by
101da177e4SLinus Torvalds  * most "normal" filesystems (but you don't /have/ to use this:
111da177e4SLinus Torvalds  * the NFS filesystem used to do this differently, for example)
121da177e4SLinus Torvalds  */
13b95f1b31SPaul Gortmaker #include <linux/export.h>
141da177e4SLinus Torvalds #include <linux/compiler.h>
15f9fe48beSRoss Zwisler #include <linux/dax.h>
161da177e4SLinus Torvalds #include <linux/fs.h>
173f07c014SIngo Molnar #include <linux/sched/signal.h>
18c22ce143SHiro Yoshioka #include <linux/uaccess.h>
19c59ede7bSRandy.Dunlap #include <linux/capability.h>
201da177e4SLinus Torvalds #include <linux/kernel_stat.h>
215a0e3ad6STejun Heo #include <linux/gfp.h>
221da177e4SLinus Torvalds #include <linux/mm.h>
231da177e4SLinus Torvalds #include <linux/swap.h>
24ffa65753SAlistair Popple #include <linux/swapops.h>
25cf264e13SNhat Pham #include <linux/syscalls.h>
261da177e4SLinus Torvalds #include <linux/mman.h>
271da177e4SLinus Torvalds #include <linux/pagemap.h>
281da177e4SLinus Torvalds #include <linux/file.h>
291da177e4SLinus Torvalds #include <linux/uio.h>
30cfcbfb13SJosef Bacik #include <linux/error-injection.h>
311da177e4SLinus Torvalds #include <linux/hash.h>
321da177e4SLinus Torvalds #include <linux/writeback.h>
3353253383SLinus Torvalds #include <linux/backing-dev.h>
341da177e4SLinus Torvalds #include <linux/pagevec.h>
351da177e4SLinus Torvalds #include <linux/security.h>
3644110fe3SPaul Jackson #include <linux/cpuset.h>
3700501b53SJohannes Weiner #include <linux/hugetlb.h>
388a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
39c7df8ad2SMel Gorman #include <linux/shmem_fs.h>
40f1820361SKirill A. Shutemov #include <linux/rmap.h>
41b1d29ba8SJohannes Weiner #include <linux/delayacct.h>
42eb414681SJohannes Weiner #include <linux/psi.h>
43d0e6a582SBen Dooks #include <linux/ramfs.h>
44b9306a79SYang Shi #include <linux/page_idle.h>
45ffa65753SAlistair Popple #include <linux/migrate.h>
4607073eb0SDavid Howells #include <linux/pipe_fs_i.h>
4707073eb0SDavid Howells #include <linux/splice.h>
48f9ce0be7SKirill A. Shutemov #include <asm/pgalloc.h>
49de591a82SWill Deacon #include <asm/tlbflush.h>
500f8053a5SNick Piggin #include "internal.h"
510f8053a5SNick Piggin 
52fe0bfaafSRobert Jarzmik #define CREATE_TRACE_POINTS
53fe0bfaafSRobert Jarzmik #include <trace/events/filemap.h>
54fe0bfaafSRobert Jarzmik 
551da177e4SLinus Torvalds /*
561da177e4SLinus Torvalds  * FIXME: remove all knowledge of the buffer layer from the core VM
571da177e4SLinus Torvalds  */
58148f948bSJan Kara #include <linux/buffer_head.h> /* for try_to_free_buffers */
591da177e4SLinus Torvalds 
601da177e4SLinus Torvalds #include <asm/mman.h>
611da177e4SLinus Torvalds 
62cf264e13SNhat Pham #include "swap.h"
63cf264e13SNhat Pham 
641da177e4SLinus Torvalds /*
651da177e4SLinus Torvalds  * Shared mappings implemented 30.11.1994. It's not fully working yet,
661da177e4SLinus Torvalds  * though.
671da177e4SLinus Torvalds  *
681da177e4SLinus Torvalds  * Shared mappings now work. 15.8.1995  Bruno.
691da177e4SLinus Torvalds  *
701da177e4SLinus Torvalds  * finished 'unifying' the page and buffer cache and SMP-threaded the
711da177e4SLinus Torvalds  * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
721da177e4SLinus Torvalds  *
731da177e4SLinus Torvalds  * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
741da177e4SLinus Torvalds  */
751da177e4SLinus Torvalds 
761da177e4SLinus Torvalds /*
771da177e4SLinus Torvalds  * Lock ordering:
781da177e4SLinus Torvalds  *
79c8c06efaSDavidlohr Bueso  *  ->i_mmap_rwsem		(truncate_pagecache)
80e621900aSMatthew Wilcox (Oracle)  *    ->private_lock		(__free_pte->block_dirty_folio)
815d337b91SHugh Dickins  *      ->swap_lock		(exclusive_swap_page, others)
82b93b0163SMatthew Wilcox  *        ->i_pages lock
831da177e4SLinus Torvalds  *
849608703eSJan Kara  *  ->i_rwsem
85730633f0SJan Kara  *    ->invalidate_lock		(acquired by fs in truncate path)
86c8c06efaSDavidlohr Bueso  *      ->i_mmap_rwsem		(truncate->unmap_mapping_range)
871da177e4SLinus Torvalds  *
88c1e8d7c6SMichel Lespinasse  *  ->mmap_lock
89c8c06efaSDavidlohr Bueso  *    ->i_mmap_rwsem
90b8072f09SHugh Dickins  *      ->page_table_lock or pte_lock	(various, mainly in memory.c)
91b93b0163SMatthew Wilcox  *        ->i_pages lock	(arch-dependent flush_dcache_mmap_lock)
921da177e4SLinus Torvalds  *
93c1e8d7c6SMichel Lespinasse  *  ->mmap_lock
94730633f0SJan Kara  *    ->invalidate_lock		(filemap_fault)
95730633f0SJan Kara  *      ->lock_page		(filemap_fault, access_process_vm)
961da177e4SLinus Torvalds  *
979608703eSJan Kara  *  ->i_rwsem			(generic_perform_write)
98bb523b40SAndreas Gruenbacher  *    ->mmap_lock		(fault_in_readable->do_page_fault)
991da177e4SLinus Torvalds  *
100f758eeabSChristoph Hellwig  *  bdi->wb.list_lock
101a66979abSDave Chinner  *    sb_lock			(fs/fs-writeback.c)
102b93b0163SMatthew Wilcox  *    ->i_pages lock		(__sync_single_inode)
1031da177e4SLinus Torvalds  *
104c8c06efaSDavidlohr Bueso  *  ->i_mmap_rwsem
1050503ea8fSLiam R. Howlett  *    ->anon_vma.lock		(vma_merge)
1061da177e4SLinus Torvalds  *
1071da177e4SLinus Torvalds  *  ->anon_vma.lock
108b8072f09SHugh Dickins  *    ->page_table_lock or pte_lock	(anon_vma_prepare and various)
1091da177e4SLinus Torvalds  *
110b8072f09SHugh Dickins  *  ->page_table_lock or pte_lock
1115d337b91SHugh Dickins  *    ->swap_lock		(try_to_unmap_one)
1121da177e4SLinus Torvalds  *    ->private_lock		(try_to_unmap_one)
113b93b0163SMatthew Wilcox  *    ->i_pages lock		(try_to_unmap_one)
11415b44736SHugh Dickins  *    ->lruvec->lru_lock	(follow_page->mark_page_accessed)
11515b44736SHugh Dickins  *    ->lruvec->lru_lock	(check_pte_range->isolate_lru_page)
1161da177e4SLinus Torvalds  *    ->private_lock		(page_remove_rmap->set_page_dirty)
117b93b0163SMatthew Wilcox  *    ->i_pages lock		(page_remove_rmap->set_page_dirty)
118f758eeabSChristoph Hellwig  *    bdi.wb->list_lock		(page_remove_rmap->set_page_dirty)
119250df6edSDave Chinner  *    ->inode->i_lock		(page_remove_rmap->set_page_dirty)
1206c77b607SKefeng Wang  *    ->memcg->move_lock	(page_remove_rmap->folio_memcg_lock)
121f758eeabSChristoph Hellwig  *    bdi.wb->list_lock		(zap_pte_range->set_page_dirty)
122250df6edSDave Chinner  *    ->inode->i_lock		(zap_pte_range->set_page_dirty)
123e621900aSMatthew Wilcox (Oracle)  *    ->private_lock		(zap_pte_range->block_dirty_folio)
1241da177e4SLinus Torvalds  */
1251da177e4SLinus Torvalds 
page_cache_delete(struct address_space * mapping,struct folio * folio,void * shadow)1265c024e6aSMatthew Wilcox static void page_cache_delete(struct address_space *mapping,
127a548b615SMatthew Wilcox (Oracle) 				   struct folio *folio, void *shadow)
12891b0abe3SJohannes Weiner {
129a548b615SMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, folio->index);
130a548b615SMatthew Wilcox (Oracle) 	long nr = 1;
131c70b647dSKirill A. Shutemov 
1325c024e6aSMatthew Wilcox 	mapping_set_update(&xas, mapping);
1335c024e6aSMatthew Wilcox 
1345c024e6aSMatthew Wilcox 	/* hugetlb pages are represented by a single entry in the xarray */
135a548b615SMatthew Wilcox (Oracle) 	if (!folio_test_hugetlb(folio)) {
136a548b615SMatthew Wilcox (Oracle) 		xas_set_order(&xas, folio->index, folio_order(folio));
137a548b615SMatthew Wilcox (Oracle) 		nr = folio_nr_pages(folio);
1385c024e6aSMatthew Wilcox 	}
13991b0abe3SJohannes Weiner 
140a548b615SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
141449dd698SJohannes Weiner 
1425c024e6aSMatthew Wilcox 	xas_store(&xas, shadow);
1435c024e6aSMatthew Wilcox 	xas_init_marks(&xas);
144d3798ae8SJohannes Weiner 
145a548b615SMatthew Wilcox (Oracle) 	folio->mapping = NULL;
1462300638bSJan Kara 	/* Leave page->index set: truncation lookup relies upon it */
147d3798ae8SJohannes Weiner 	mapping->nrpages -= nr;
14891b0abe3SJohannes Weiner }
14991b0abe3SJohannes Weiner 
filemap_unaccount_folio(struct address_space * mapping,struct folio * folio)150621db488SMatthew Wilcox (Oracle) static void filemap_unaccount_folio(struct address_space *mapping,
151621db488SMatthew Wilcox (Oracle) 		struct folio *folio)
1521da177e4SLinus Torvalds {
153621db488SMatthew Wilcox (Oracle) 	long nr;
1541da177e4SLinus Torvalds 
155621db488SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(folio_mapped(folio), folio);
156621db488SMatthew Wilcox (Oracle) 	if (!IS_ENABLED(CONFIG_DEBUG_VM) && unlikely(folio_mapped(folio))) {
15706b241f3SHugh Dickins 		pr_alert("BUG: Bad page cache in process %s  pfn:%05lx\n",
158621db488SMatthew Wilcox (Oracle) 			 current->comm, folio_pfn(folio));
159621db488SMatthew Wilcox (Oracle) 		dump_page(&folio->page, "still mapped when deleted");
16006b241f3SHugh Dickins 		dump_stack();
16106b241f3SHugh Dickins 		add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
16206b241f3SHugh Dickins 
16385207ad8SHugh Dickins 		if (mapping_exiting(mapping) && !folio_test_large(folio)) {
16485207ad8SHugh Dickins 			int mapcount = page_mapcount(&folio->page);
16585207ad8SHugh Dickins 
16685207ad8SHugh Dickins 			if (folio_ref_count(folio) >= mapcount + 2) {
16706b241f3SHugh Dickins 				/*
16806b241f3SHugh Dickins 				 * All vmas have already been torn down, so it's
16985207ad8SHugh Dickins 				 * a good bet that actually the page is unmapped
17085207ad8SHugh Dickins 				 * and we'd rather not leak it: if we're wrong,
17185207ad8SHugh Dickins 				 * another bad page check should catch it later.
17206b241f3SHugh Dickins 				 */
173621db488SMatthew Wilcox (Oracle) 				page_mapcount_reset(&folio->page);
174621db488SMatthew Wilcox (Oracle) 				folio_ref_sub(folio, mapcount);
17506b241f3SHugh Dickins 			}
17606b241f3SHugh Dickins 		}
17785207ad8SHugh Dickins 	}
17806b241f3SHugh Dickins 
179621db488SMatthew Wilcox (Oracle) 	/* hugetlb folios do not participate in page cache accounting. */
180621db488SMatthew Wilcox (Oracle) 	if (folio_test_hugetlb(folio))
1815ecc4d85SJan Kara 		return;
1825ecc4d85SJan Kara 
183621db488SMatthew Wilcox (Oracle) 	nr = folio_nr_pages(folio);
1845ecc4d85SJan Kara 
185621db488SMatthew Wilcox (Oracle) 	__lruvec_stat_mod_folio(folio, NR_FILE_PAGES, -nr);
186621db488SMatthew Wilcox (Oracle) 	if (folio_test_swapbacked(folio)) {
187621db488SMatthew Wilcox (Oracle) 		__lruvec_stat_mod_folio(folio, NR_SHMEM, -nr);
188621db488SMatthew Wilcox (Oracle) 		if (folio_test_pmd_mappable(folio))
189621db488SMatthew Wilcox (Oracle) 			__lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, -nr);
190621db488SMatthew Wilcox (Oracle) 	} else if (folio_test_pmd_mappable(folio)) {
191621db488SMatthew Wilcox (Oracle) 		__lruvec_stat_mod_folio(folio, NR_FILE_THPS, -nr);
19209d91cdaSSong Liu 		filemap_nr_thps_dec(mapping);
193800d8c63SKirill A. Shutemov 	}
1943a692790SLinus Torvalds 
1953a692790SLinus Torvalds 	/*
196621db488SMatthew Wilcox (Oracle) 	 * At this point folio must be either written or cleaned by
197621db488SMatthew Wilcox (Oracle) 	 * truncate.  Dirty folio here signals a bug and loss of
198566d3362SHugh Dickins 	 * unwritten data - on ordinary filesystems.
1993a692790SLinus Torvalds 	 *
200566d3362SHugh Dickins 	 * But it's harmless on in-memory filesystems like tmpfs; and can
201566d3362SHugh Dickins 	 * occur when a driver which did get_user_pages() sets page dirty
202566d3362SHugh Dickins 	 * before putting it, while the inode is being finally evicted.
203566d3362SHugh Dickins 	 *
204566d3362SHugh Dickins 	 * Below fixes dirty accounting after removing the folio entirely
205621db488SMatthew Wilcox (Oracle) 	 * but leaves the dirty flag set: it has no effect for truncated
206621db488SMatthew Wilcox (Oracle) 	 * folio and anyway will be cleared before returning folio to
20776253fbcSJan Kara 	 * buddy allocator.
2083a692790SLinus Torvalds 	 */
209566d3362SHugh Dickins 	if (WARN_ON_ONCE(folio_test_dirty(folio) &&
210566d3362SHugh Dickins 			 mapping_can_writeback(mapping)))
211566d3362SHugh Dickins 		folio_account_cleaned(folio, inode_to_wb(mapping->host));
21276253fbcSJan Kara }
2135ecc4d85SJan Kara 
2145ecc4d85SJan Kara /*
2155ecc4d85SJan Kara  * Delete a page from the page cache and free it. Caller has to make
2165ecc4d85SJan Kara  * sure the page is locked and that nobody else uses it - or that usage
217b93b0163SMatthew Wilcox  * is safe.  The caller must hold the i_pages lock.
2185ecc4d85SJan Kara  */
__filemap_remove_folio(struct folio * folio,void * shadow)219452e9e69SMatthew Wilcox (Oracle) void __filemap_remove_folio(struct folio *folio, void *shadow)
2205ecc4d85SJan Kara {
221452e9e69SMatthew Wilcox (Oracle) 	struct address_space *mapping = folio->mapping;
2225ecc4d85SJan Kara 
223a0580c6fSMatthew Wilcox (Oracle) 	trace_mm_filemap_delete_from_page_cache(folio);
224621db488SMatthew Wilcox (Oracle) 	filemap_unaccount_folio(mapping, folio);
225a548b615SMatthew Wilcox (Oracle) 	page_cache_delete(mapping, folio, shadow);
2261da177e4SLinus Torvalds }
2271da177e4SLinus Torvalds 
filemap_free_folio(struct address_space * mapping,struct folio * folio)22878f42660SMatthew Wilcox (Oracle) void filemap_free_folio(struct address_space *mapping, struct folio *folio)
22959c66c5fSJan Kara {
230d2329aa0SMatthew Wilcox (Oracle) 	void (*free_folio)(struct folio *);
2313abb28e2SMatthew Wilcox (Oracle) 	int refs = 1;
23259c66c5fSJan Kara 
233d2329aa0SMatthew Wilcox (Oracle) 	free_folio = mapping->a_ops->free_folio;
234d2329aa0SMatthew Wilcox (Oracle) 	if (free_folio)
235d2329aa0SMatthew Wilcox (Oracle) 		free_folio(folio);
23659c66c5fSJan Kara 
2373abb28e2SMatthew Wilcox (Oracle) 	if (folio_test_large(folio) && !folio_test_hugetlb(folio))
2383abb28e2SMatthew Wilcox (Oracle) 		refs = folio_nr_pages(folio);
2393abb28e2SMatthew Wilcox (Oracle) 	folio_put_refs(folio, refs);
24059c66c5fSJan Kara }
24159c66c5fSJan Kara 
242702cfbf9SMinchan Kim /**
243452e9e69SMatthew Wilcox (Oracle)  * filemap_remove_folio - Remove folio from page cache.
244452e9e69SMatthew Wilcox (Oracle)  * @folio: The folio.
245702cfbf9SMinchan Kim  *
246452e9e69SMatthew Wilcox (Oracle)  * This must be called only on folios that are locked and have been
247452e9e69SMatthew Wilcox (Oracle)  * verified to be in the page cache.  It will never put the folio into
248452e9e69SMatthew Wilcox (Oracle)  * the free list because the caller has a reference on the page.
249702cfbf9SMinchan Kim  */
filemap_remove_folio(struct folio * folio)250452e9e69SMatthew Wilcox (Oracle) void filemap_remove_folio(struct folio *folio)
2511da177e4SLinus Torvalds {
252452e9e69SMatthew Wilcox (Oracle) 	struct address_space *mapping = folio->mapping;
2531da177e4SLinus Torvalds 
254452e9e69SMatthew Wilcox (Oracle) 	BUG_ON(!folio_test_locked(folio));
25551b8c1feSJohannes Weiner 	spin_lock(&mapping->host->i_lock);
25630472509SJohannes Weiner 	xa_lock_irq(&mapping->i_pages);
257452e9e69SMatthew Wilcox (Oracle) 	__filemap_remove_folio(folio, NULL);
25830472509SJohannes Weiner 	xa_unlock_irq(&mapping->i_pages);
25951b8c1feSJohannes Weiner 	if (mapping_shrinkable(mapping))
26051b8c1feSJohannes Weiner 		inode_add_lru(mapping->host);
26151b8c1feSJohannes Weiner 	spin_unlock(&mapping->host->i_lock);
2626072d13cSLinus Torvalds 
263452e9e69SMatthew Wilcox (Oracle) 	filemap_free_folio(mapping, folio);
26483929372SKirill A. Shutemov }
26597cecb5aSMinchan Kim 
266aa65c29cSJan Kara /*
26751dcbdacSMatthew Wilcox (Oracle)  * page_cache_delete_batch - delete several folios from page cache
26851dcbdacSMatthew Wilcox (Oracle)  * @mapping: the mapping to which folios belong
26951dcbdacSMatthew Wilcox (Oracle)  * @fbatch: batch of folios to delete
270aa65c29cSJan Kara  *
27151dcbdacSMatthew Wilcox (Oracle)  * The function walks over mapping->i_pages and removes folios passed in
27251dcbdacSMatthew Wilcox (Oracle)  * @fbatch from the mapping. The function expects @fbatch to be sorted
27351dcbdacSMatthew Wilcox (Oracle)  * by page index and is optimised for it to be dense.
27451dcbdacSMatthew Wilcox (Oracle)  * It tolerates holes in @fbatch (mapping entries at those indices are not
27551dcbdacSMatthew Wilcox (Oracle)  * modified).
276aa65c29cSJan Kara  *
277b93b0163SMatthew Wilcox  * The function expects the i_pages lock to be held.
278aa65c29cSJan Kara  */
page_cache_delete_batch(struct address_space * mapping,struct folio_batch * fbatch)279ef8e5717SMatthew Wilcox static void page_cache_delete_batch(struct address_space *mapping,
28051dcbdacSMatthew Wilcox (Oracle) 			     struct folio_batch *fbatch)
281aa65c29cSJan Kara {
28251dcbdacSMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, fbatch->folios[0]->index);
2836b24ca4aSMatthew Wilcox (Oracle) 	long total_pages = 0;
2844101196bSMatthew Wilcox (Oracle) 	int i = 0;
2851afd7ae5SMatthew Wilcox (Oracle) 	struct folio *folio;
286aa65c29cSJan Kara 
287ef8e5717SMatthew Wilcox 	mapping_set_update(&xas, mapping);
2881afd7ae5SMatthew Wilcox (Oracle) 	xas_for_each(&xas, folio, ULONG_MAX) {
28951dcbdacSMatthew Wilcox (Oracle) 		if (i >= folio_batch_count(fbatch))
290aa65c29cSJan Kara 			break;
2914101196bSMatthew Wilcox (Oracle) 
2924101196bSMatthew Wilcox (Oracle) 		/* A swap/dax/shadow entry got inserted? Skip it. */
2931afd7ae5SMatthew Wilcox (Oracle) 		if (xa_is_value(folio))
294aa65c29cSJan Kara 			continue;
295aa65c29cSJan Kara 		/*
2964101196bSMatthew Wilcox (Oracle) 		 * A page got inserted in our range? Skip it. We have our
2974101196bSMatthew Wilcox (Oracle) 		 * pages locked so they are protected from being removed.
2984101196bSMatthew Wilcox (Oracle) 		 * If we see a page whose index is higher than ours, it
2994101196bSMatthew Wilcox (Oracle) 		 * means our page has been removed, which shouldn't be
3004101196bSMatthew Wilcox (Oracle) 		 * possible because we're holding the PageLock.
301aa65c29cSJan Kara 		 */
30251dcbdacSMatthew Wilcox (Oracle) 		if (folio != fbatch->folios[i]) {
3031afd7ae5SMatthew Wilcox (Oracle) 			VM_BUG_ON_FOLIO(folio->index >
30451dcbdacSMatthew Wilcox (Oracle) 					fbatch->folios[i]->index, folio);
305aa65c29cSJan Kara 			continue;
306ef8e5717SMatthew Wilcox 		}
3074101196bSMatthew Wilcox (Oracle) 
3081afd7ae5SMatthew Wilcox (Oracle) 		WARN_ON_ONCE(!folio_test_locked(folio));
3094101196bSMatthew Wilcox (Oracle) 
3101afd7ae5SMatthew Wilcox (Oracle) 		folio->mapping = NULL;
31151dcbdacSMatthew Wilcox (Oracle) 		/* Leave folio->index set: truncation lookup relies on it */
3124101196bSMatthew Wilcox (Oracle) 
313aa65c29cSJan Kara 		i++;
314ef8e5717SMatthew Wilcox 		xas_store(&xas, NULL);
3156b24ca4aSMatthew Wilcox (Oracle) 		total_pages += folio_nr_pages(folio);
316aa65c29cSJan Kara 	}
317aa65c29cSJan Kara 	mapping->nrpages -= total_pages;
318aa65c29cSJan Kara }
319aa65c29cSJan Kara 
delete_from_page_cache_batch(struct address_space * mapping,struct folio_batch * fbatch)320aa65c29cSJan Kara void delete_from_page_cache_batch(struct address_space *mapping,
32151dcbdacSMatthew Wilcox (Oracle) 				  struct folio_batch *fbatch)
322aa65c29cSJan Kara {
323aa65c29cSJan Kara 	int i;
324aa65c29cSJan Kara 
32551dcbdacSMatthew Wilcox (Oracle) 	if (!folio_batch_count(fbatch))
326aa65c29cSJan Kara 		return;
327aa65c29cSJan Kara 
32851b8c1feSJohannes Weiner 	spin_lock(&mapping->host->i_lock);
32930472509SJohannes Weiner 	xa_lock_irq(&mapping->i_pages);
33051dcbdacSMatthew Wilcox (Oracle) 	for (i = 0; i < folio_batch_count(fbatch); i++) {
33151dcbdacSMatthew Wilcox (Oracle) 		struct folio *folio = fbatch->folios[i];
332aa65c29cSJan Kara 
333a0580c6fSMatthew Wilcox (Oracle) 		trace_mm_filemap_delete_from_page_cache(folio);
334a0580c6fSMatthew Wilcox (Oracle) 		filemap_unaccount_folio(mapping, folio);
335aa65c29cSJan Kara 	}
33651dcbdacSMatthew Wilcox (Oracle) 	page_cache_delete_batch(mapping, fbatch);
33730472509SJohannes Weiner 	xa_unlock_irq(&mapping->i_pages);
33851b8c1feSJohannes Weiner 	if (mapping_shrinkable(mapping))
33951b8c1feSJohannes Weiner 		inode_add_lru(mapping->host);
34051b8c1feSJohannes Weiner 	spin_unlock(&mapping->host->i_lock);
341aa65c29cSJan Kara 
34251dcbdacSMatthew Wilcox (Oracle) 	for (i = 0; i < folio_batch_count(fbatch); i++)
34351dcbdacSMatthew Wilcox (Oracle) 		filemap_free_folio(mapping, fbatch->folios[i]);
344aa65c29cSJan Kara }
345aa65c29cSJan Kara 
filemap_check_errors(struct address_space * mapping)346d72d9e2aSMiklos Szeredi int filemap_check_errors(struct address_space *mapping)
347865ffef3SDmitry Monakhov {
348865ffef3SDmitry Monakhov 	int ret = 0;
349865ffef3SDmitry Monakhov 	/* Check for outstanding write errors */
3507fcbbaf1SJens Axboe 	if (test_bit(AS_ENOSPC, &mapping->flags) &&
3517fcbbaf1SJens Axboe 	    test_and_clear_bit(AS_ENOSPC, &mapping->flags))
352865ffef3SDmitry Monakhov 		ret = -ENOSPC;
3537fcbbaf1SJens Axboe 	if (test_bit(AS_EIO, &mapping->flags) &&
3547fcbbaf1SJens Axboe 	    test_and_clear_bit(AS_EIO, &mapping->flags))
355865ffef3SDmitry Monakhov 		ret = -EIO;
356865ffef3SDmitry Monakhov 	return ret;
357865ffef3SDmitry Monakhov }
358d72d9e2aSMiklos Szeredi EXPORT_SYMBOL(filemap_check_errors);
359865ffef3SDmitry Monakhov 
filemap_check_and_keep_errors(struct address_space * mapping)36076341cabSJeff Layton static int filemap_check_and_keep_errors(struct address_space *mapping)
36176341cabSJeff Layton {
36276341cabSJeff Layton 	/* Check for outstanding write errors */
36376341cabSJeff Layton 	if (test_bit(AS_EIO, &mapping->flags))
36476341cabSJeff Layton 		return -EIO;
36576341cabSJeff Layton 	if (test_bit(AS_ENOSPC, &mapping->flags))
36676341cabSJeff Layton 		return -ENOSPC;
36776341cabSJeff Layton 	return 0;
36876341cabSJeff Layton }
36976341cabSJeff Layton 
3701da177e4SLinus Torvalds /**
3715a798493SJosef Bacik  * filemap_fdatawrite_wbc - start writeback on mapping dirty pages in range
3725a798493SJosef Bacik  * @mapping:	address space structure to write
3735a798493SJosef Bacik  * @wbc:	the writeback_control controlling the writeout
3745a798493SJosef Bacik  *
3755a798493SJosef Bacik  * Call writepages on the mapping using the provided wbc to control the
3765a798493SJosef Bacik  * writeout.
3775a798493SJosef Bacik  *
3785a798493SJosef Bacik  * Return: %0 on success, negative error code otherwise.
3795a798493SJosef Bacik  */
filemap_fdatawrite_wbc(struct address_space * mapping,struct writeback_control * wbc)3805a798493SJosef Bacik int filemap_fdatawrite_wbc(struct address_space *mapping,
3815a798493SJosef Bacik 			   struct writeback_control *wbc)
3825a798493SJosef Bacik {
3835a798493SJosef Bacik 	int ret;
3845a798493SJosef Bacik 
3855a798493SJosef Bacik 	if (!mapping_can_writeback(mapping) ||
3865a798493SJosef Bacik 	    !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
3875a798493SJosef Bacik 		return 0;
3885a798493SJosef Bacik 
3895a798493SJosef Bacik 	wbc_attach_fdatawrite_inode(wbc, mapping->host);
3905a798493SJosef Bacik 	ret = do_writepages(mapping, wbc);
3915a798493SJosef Bacik 	wbc_detach_inode(wbc);
3925a798493SJosef Bacik 	return ret;
3935a798493SJosef Bacik }
3945a798493SJosef Bacik EXPORT_SYMBOL(filemap_fdatawrite_wbc);
3955a798493SJosef Bacik 
3965a798493SJosef Bacik /**
397485bb99bSRandy Dunlap  * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
3981da177e4SLinus Torvalds  * @mapping:	address space structure to write
3991da177e4SLinus Torvalds  * @start:	offset in bytes where the range starts
400469eb4d0SAndrew Morton  * @end:	offset in bytes where the range ends (inclusive)
40167be2dd1SMartin Waitz  * @sync_mode:	enable synchronous operation
4021da177e4SLinus Torvalds  *
403485bb99bSRandy Dunlap  * Start writeback against all of a mapping's dirty pages that lie
404485bb99bSRandy Dunlap  * within the byte offsets <start, end> inclusive.
405485bb99bSRandy Dunlap  *
4061da177e4SLinus Torvalds  * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
407485bb99bSRandy Dunlap  * opposed to a regular memory cleansing writeback.  The difference between
4081da177e4SLinus Torvalds  * these two operations is that if a dirty page/buffer is encountered, it must
4091da177e4SLinus Torvalds  * be waited upon, and not just skipped over.
410a862f68aSMike Rapoport  *
411a862f68aSMike Rapoport  * Return: %0 on success, negative error code otherwise.
4121da177e4SLinus Torvalds  */
__filemap_fdatawrite_range(struct address_space * mapping,loff_t start,loff_t end,int sync_mode)413ebcf28e1SAndrew Morton int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
414ebcf28e1SAndrew Morton 				loff_t end, int sync_mode)
4151da177e4SLinus Torvalds {
4161da177e4SLinus Torvalds 	struct writeback_control wbc = {
4171da177e4SLinus Torvalds 		.sync_mode = sync_mode,
41805fe478dSNick Piggin 		.nr_to_write = LONG_MAX,
419111ebb6eSOGAWA Hirofumi 		.range_start = start,
420111ebb6eSOGAWA Hirofumi 		.range_end = end,
4211da177e4SLinus Torvalds 	};
4221da177e4SLinus Torvalds 
4235a798493SJosef Bacik 	return filemap_fdatawrite_wbc(mapping, &wbc);
4241da177e4SLinus Torvalds }
4251da177e4SLinus Torvalds 
__filemap_fdatawrite(struct address_space * mapping,int sync_mode)4261da177e4SLinus Torvalds static inline int __filemap_fdatawrite(struct address_space *mapping,
4271da177e4SLinus Torvalds 	int sync_mode)
4281da177e4SLinus Torvalds {
429111ebb6eSOGAWA Hirofumi 	return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
4301da177e4SLinus Torvalds }
4311da177e4SLinus Torvalds 
filemap_fdatawrite(struct address_space * mapping)4321da177e4SLinus Torvalds int filemap_fdatawrite(struct address_space *mapping)
4331da177e4SLinus Torvalds {
4341da177e4SLinus Torvalds 	return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
4351da177e4SLinus Torvalds }
4361da177e4SLinus Torvalds EXPORT_SYMBOL(filemap_fdatawrite);
4371da177e4SLinus Torvalds 
filemap_fdatawrite_range(struct address_space * mapping,loff_t start,loff_t end)438f4c0a0fdSJan Kara int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
439ebcf28e1SAndrew Morton 				loff_t end)
4401da177e4SLinus Torvalds {
4411da177e4SLinus Torvalds 	return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
4421da177e4SLinus Torvalds }
443f4c0a0fdSJan Kara EXPORT_SYMBOL(filemap_fdatawrite_range);
4441da177e4SLinus Torvalds 
445485bb99bSRandy Dunlap /**
446485bb99bSRandy Dunlap  * filemap_flush - mostly a non-blocking flush
447485bb99bSRandy Dunlap  * @mapping:	target address_space
448485bb99bSRandy Dunlap  *
4491da177e4SLinus Torvalds  * This is a mostly non-blocking flush.  Not suitable for data-integrity
4501da177e4SLinus Torvalds  * purposes - I/O may not be started against all dirty pages.
451a862f68aSMike Rapoport  *
452a862f68aSMike Rapoport  * Return: %0 on success, negative error code otherwise.
4531da177e4SLinus Torvalds  */
filemap_flush(struct address_space * mapping)4541da177e4SLinus Torvalds int filemap_flush(struct address_space *mapping)
4551da177e4SLinus Torvalds {
4561da177e4SLinus Torvalds 	return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
4571da177e4SLinus Torvalds }
4581da177e4SLinus Torvalds EXPORT_SYMBOL(filemap_flush);
4591da177e4SLinus Torvalds 
4607fc9e472SGoldwyn Rodrigues /**
4617fc9e472SGoldwyn Rodrigues  * filemap_range_has_page - check if a page exists in range.
4627fc9e472SGoldwyn Rodrigues  * @mapping:           address space within which to check
4637fc9e472SGoldwyn Rodrigues  * @start_byte:        offset in bytes where the range starts
4647fc9e472SGoldwyn Rodrigues  * @end_byte:          offset in bytes where the range ends (inclusive)
4657fc9e472SGoldwyn Rodrigues  *
4667fc9e472SGoldwyn Rodrigues  * Find at least one page in the range supplied, usually used to check if
4677fc9e472SGoldwyn Rodrigues  * direct writing in this range will trigger a writeback.
468a862f68aSMike Rapoport  *
469a862f68aSMike Rapoport  * Return: %true if at least one page exists in the specified range,
470a862f68aSMike Rapoport  * %false otherwise.
4717fc9e472SGoldwyn Rodrigues  */
filemap_range_has_page(struct address_space * mapping,loff_t start_byte,loff_t end_byte)4727fc9e472SGoldwyn Rodrigues bool filemap_range_has_page(struct address_space *mapping,
4737fc9e472SGoldwyn Rodrigues 			   loff_t start_byte, loff_t end_byte)
4747fc9e472SGoldwyn Rodrigues {
475eff3b364SMatthew Wilcox (Oracle) 	struct folio *folio;
4768fa8e538SMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
4778fa8e538SMatthew Wilcox 	pgoff_t max = end_byte >> PAGE_SHIFT;
4787fc9e472SGoldwyn Rodrigues 
4797fc9e472SGoldwyn Rodrigues 	if (end_byte < start_byte)
4807fc9e472SGoldwyn Rodrigues 		return false;
4817fc9e472SGoldwyn Rodrigues 
4828fa8e538SMatthew Wilcox 	rcu_read_lock();
4838fa8e538SMatthew Wilcox 	for (;;) {
484eff3b364SMatthew Wilcox (Oracle) 		folio = xas_find(&xas, max);
485eff3b364SMatthew Wilcox (Oracle) 		if (xas_retry(&xas, folio))
4868fa8e538SMatthew Wilcox 			continue;
4878fa8e538SMatthew Wilcox 		/* Shadow entries don't count */
488eff3b364SMatthew Wilcox (Oracle) 		if (xa_is_value(folio))
4898fa8e538SMatthew Wilcox 			continue;
4908fa8e538SMatthew Wilcox 		/*
4918fa8e538SMatthew Wilcox 		 * We don't need to try to pin this page; we're about to
4928fa8e538SMatthew Wilcox 		 * release the RCU lock anyway.  It is enough to know that
4938fa8e538SMatthew Wilcox 		 * there was a page here recently.
4948fa8e538SMatthew Wilcox 		 */
4958fa8e538SMatthew Wilcox 		break;
4968fa8e538SMatthew Wilcox 	}
4978fa8e538SMatthew Wilcox 	rcu_read_unlock();
4987fc9e472SGoldwyn Rodrigues 
499eff3b364SMatthew Wilcox (Oracle) 	return folio != NULL;
5007fc9e472SGoldwyn Rodrigues }
5017fc9e472SGoldwyn Rodrigues EXPORT_SYMBOL(filemap_range_has_page);
5027fc9e472SGoldwyn Rodrigues 
__filemap_fdatawait_range(struct address_space * mapping,loff_t start_byte,loff_t end_byte)5035e8fcc1aSJeff Layton static void __filemap_fdatawait_range(struct address_space *mapping,
504aa750fd7SJunichi Nomura 				     loff_t start_byte, loff_t end_byte)
5051da177e4SLinus Torvalds {
50609cbfeafSKirill A. Shutemov 	pgoff_t index = start_byte >> PAGE_SHIFT;
50709cbfeafSKirill A. Shutemov 	pgoff_t end = end_byte >> PAGE_SHIFT;
5086817ef51SVishal Moola (Oracle) 	struct folio_batch fbatch;
5096817ef51SVishal Moola (Oracle) 	unsigned nr_folios;
5101da177e4SLinus Torvalds 
5116817ef51SVishal Moola (Oracle) 	folio_batch_init(&fbatch);
5126817ef51SVishal Moola (Oracle) 
513312e9d2fSJan Kara 	while (index <= end) {
5141da177e4SLinus Torvalds 		unsigned i;
5151da177e4SLinus Torvalds 
5166817ef51SVishal Moola (Oracle) 		nr_folios = filemap_get_folios_tag(mapping, &index, end,
5176817ef51SVishal Moola (Oracle) 				PAGECACHE_TAG_WRITEBACK, &fbatch);
5186817ef51SVishal Moola (Oracle) 
5196817ef51SVishal Moola (Oracle) 		if (!nr_folios)
520312e9d2fSJan Kara 			break;
521312e9d2fSJan Kara 
5226817ef51SVishal Moola (Oracle) 		for (i = 0; i < nr_folios; i++) {
5236817ef51SVishal Moola (Oracle) 			struct folio *folio = fbatch.folios[i];
5241da177e4SLinus Torvalds 
5256817ef51SVishal Moola (Oracle) 			folio_wait_writeback(folio);
5266817ef51SVishal Moola (Oracle) 			folio_clear_error(folio);
5271da177e4SLinus Torvalds 		}
5286817ef51SVishal Moola (Oracle) 		folio_batch_release(&fbatch);
5291da177e4SLinus Torvalds 		cond_resched();
5301da177e4SLinus Torvalds 	}
531aa750fd7SJunichi Nomura }
532aa750fd7SJunichi Nomura 
533aa750fd7SJunichi Nomura /**
534aa750fd7SJunichi Nomura  * filemap_fdatawait_range - wait for writeback to complete
535aa750fd7SJunichi Nomura  * @mapping:		address space structure to wait for
536aa750fd7SJunichi Nomura  * @start_byte:		offset in bytes where the range starts
537aa750fd7SJunichi Nomura  * @end_byte:		offset in bytes where the range ends (inclusive)
538aa750fd7SJunichi Nomura  *
539aa750fd7SJunichi Nomura  * Walk the list of under-writeback pages of the given address space
540aa750fd7SJunichi Nomura  * in the given range and wait for all of them.  Check error status of
541aa750fd7SJunichi Nomura  * the address space and return it.
542aa750fd7SJunichi Nomura  *
543aa750fd7SJunichi Nomura  * Since the error status of the address space is cleared by this function,
544aa750fd7SJunichi Nomura  * callers are responsible for checking the return value and handling and/or
545aa750fd7SJunichi Nomura  * reporting the error.
546a862f68aSMike Rapoport  *
547a862f68aSMike Rapoport  * Return: error status of the address space.
548aa750fd7SJunichi Nomura  */
filemap_fdatawait_range(struct address_space * mapping,loff_t start_byte,loff_t end_byte)549aa750fd7SJunichi Nomura int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
550aa750fd7SJunichi Nomura 			    loff_t end_byte)
551aa750fd7SJunichi Nomura {
5525e8fcc1aSJeff Layton 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
5535e8fcc1aSJeff Layton 	return filemap_check_errors(mapping);
5541da177e4SLinus Torvalds }
555d3bccb6fSJan Kara EXPORT_SYMBOL(filemap_fdatawait_range);
556d3bccb6fSJan Kara 
557d3bccb6fSJan Kara /**
558aa0bfcd9SRoss Zwisler  * filemap_fdatawait_range_keep_errors - wait for writeback to complete
559aa0bfcd9SRoss Zwisler  * @mapping:		address space structure to wait for
560aa0bfcd9SRoss Zwisler  * @start_byte:		offset in bytes where the range starts
561aa0bfcd9SRoss Zwisler  * @end_byte:		offset in bytes where the range ends (inclusive)
562aa0bfcd9SRoss Zwisler  *
563aa0bfcd9SRoss Zwisler  * Walk the list of under-writeback pages of the given address space in the
564aa0bfcd9SRoss Zwisler  * given range and wait for all of them.  Unlike filemap_fdatawait_range(),
565aa0bfcd9SRoss Zwisler  * this function does not clear error status of the address space.
566aa0bfcd9SRoss Zwisler  *
567aa0bfcd9SRoss Zwisler  * Use this function if callers don't handle errors themselves.  Expected
568aa0bfcd9SRoss Zwisler  * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
569aa0bfcd9SRoss Zwisler  * fsfreeze(8)
570aa0bfcd9SRoss Zwisler  */
filemap_fdatawait_range_keep_errors(struct address_space * mapping,loff_t start_byte,loff_t end_byte)571aa0bfcd9SRoss Zwisler int filemap_fdatawait_range_keep_errors(struct address_space *mapping,
572aa0bfcd9SRoss Zwisler 		loff_t start_byte, loff_t end_byte)
573aa0bfcd9SRoss Zwisler {
574aa0bfcd9SRoss Zwisler 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
575aa0bfcd9SRoss Zwisler 	return filemap_check_and_keep_errors(mapping);
576aa0bfcd9SRoss Zwisler }
577aa0bfcd9SRoss Zwisler EXPORT_SYMBOL(filemap_fdatawait_range_keep_errors);
578aa0bfcd9SRoss Zwisler 
579aa0bfcd9SRoss Zwisler /**
580a823e458SJeff Layton  * file_fdatawait_range - wait for writeback to complete
581a823e458SJeff Layton  * @file:		file pointing to address space structure to wait for
582a823e458SJeff Layton  * @start_byte:		offset in bytes where the range starts
583a823e458SJeff Layton  * @end_byte:		offset in bytes where the range ends (inclusive)
584a823e458SJeff Layton  *
585a823e458SJeff Layton  * Walk the list of under-writeback pages of the address space that file
586a823e458SJeff Layton  * refers to, in the given range and wait for all of them.  Check error
587a823e458SJeff Layton  * status of the address space vs. the file->f_wb_err cursor and return it.
588a823e458SJeff Layton  *
589a823e458SJeff Layton  * Since the error status of the file is advanced by this function,
590a823e458SJeff Layton  * callers are responsible for checking the return value and handling and/or
591a823e458SJeff Layton  * reporting the error.
592a862f68aSMike Rapoport  *
593a862f68aSMike Rapoport  * Return: error status of the address space vs. the file->f_wb_err cursor.
594a823e458SJeff Layton  */
file_fdatawait_range(struct file * file,loff_t start_byte,loff_t end_byte)595a823e458SJeff Layton int file_fdatawait_range(struct file *file, loff_t start_byte, loff_t end_byte)
596a823e458SJeff Layton {
597a823e458SJeff Layton 	struct address_space *mapping = file->f_mapping;
598a823e458SJeff Layton 
599a823e458SJeff Layton 	__filemap_fdatawait_range(mapping, start_byte, end_byte);
600a823e458SJeff Layton 	return file_check_and_advance_wb_err(file);
601a823e458SJeff Layton }
602a823e458SJeff Layton EXPORT_SYMBOL(file_fdatawait_range);
603a823e458SJeff Layton 
604a823e458SJeff Layton /**
605aa750fd7SJunichi Nomura  * filemap_fdatawait_keep_errors - wait for writeback without clearing errors
606aa750fd7SJunichi Nomura  * @mapping: address space structure to wait for
607aa750fd7SJunichi Nomura  *
608aa750fd7SJunichi Nomura  * Walk the list of under-writeback pages of the given address space
609aa750fd7SJunichi Nomura  * and wait for all of them.  Unlike filemap_fdatawait(), this function
610aa750fd7SJunichi Nomura  * does not clear error status of the address space.
611aa750fd7SJunichi Nomura  *
612aa750fd7SJunichi Nomura  * Use this function if callers don't handle errors themselves.  Expected
613aa750fd7SJunichi Nomura  * call sites are system-wide / filesystem-wide data flushers: e.g. sync(2),
614aa750fd7SJunichi Nomura  * fsfreeze(8)
615a862f68aSMike Rapoport  *
616a862f68aSMike Rapoport  * Return: error status of the address space.
617aa750fd7SJunichi Nomura  */
filemap_fdatawait_keep_errors(struct address_space * mapping)61876341cabSJeff Layton int filemap_fdatawait_keep_errors(struct address_space *mapping)
619aa750fd7SJunichi Nomura {
620ffb959bbSJeff Layton 	__filemap_fdatawait_range(mapping, 0, LLONG_MAX);
62176341cabSJeff Layton 	return filemap_check_and_keep_errors(mapping);
622aa750fd7SJunichi Nomura }
62376341cabSJeff Layton EXPORT_SYMBOL(filemap_fdatawait_keep_errors);
624aa750fd7SJunichi Nomura 
625875d91b1SKonstantin Khlebnikov /* Returns true if writeback might be needed or already in progress. */
mapping_needs_writeback(struct address_space * mapping)6269326c9b2SJeff Layton static bool mapping_needs_writeback(struct address_space *mapping)
6271da177e4SLinus Torvalds {
628875d91b1SKonstantin Khlebnikov 	return mapping->nrpages;
6291da177e4SLinus Torvalds }
6301da177e4SLinus Torvalds 
filemap_range_has_writeback(struct address_space * mapping,loff_t start_byte,loff_t end_byte)6314bdcd1ddSJens Axboe bool filemap_range_has_writeback(struct address_space *mapping,
632f8ee8909SJens Axboe 				 loff_t start_byte, loff_t end_byte)
633f8ee8909SJens Axboe {
634f8ee8909SJens Axboe 	XA_STATE(xas, &mapping->i_pages, start_byte >> PAGE_SHIFT);
635f8ee8909SJens Axboe 	pgoff_t max = end_byte >> PAGE_SHIFT;
636b05f41a1SVishal Moola (Oracle) 	struct folio *folio;
637f8ee8909SJens Axboe 
638f8ee8909SJens Axboe 	if (end_byte < start_byte)
639f8ee8909SJens Axboe 		return false;
640f8ee8909SJens Axboe 
641f8ee8909SJens Axboe 	rcu_read_lock();
642b05f41a1SVishal Moola (Oracle) 	xas_for_each(&xas, folio, max) {
643b05f41a1SVishal Moola (Oracle) 		if (xas_retry(&xas, folio))
644f8ee8909SJens Axboe 			continue;
645b05f41a1SVishal Moola (Oracle) 		if (xa_is_value(folio))
646f8ee8909SJens Axboe 			continue;
647b05f41a1SVishal Moola (Oracle) 		if (folio_test_dirty(folio) || folio_test_locked(folio) ||
648b05f41a1SVishal Moola (Oracle) 				folio_test_writeback(folio))
649f8ee8909SJens Axboe 			break;
650f8ee8909SJens Axboe 	}
651f8ee8909SJens Axboe 	rcu_read_unlock();
652b05f41a1SVishal Moola (Oracle) 	return folio != NULL;
653f8ee8909SJens Axboe }
6544bdcd1ddSJens Axboe EXPORT_SYMBOL_GPL(filemap_range_has_writeback);
65563135aa3SJens Axboe 
65663135aa3SJens Axboe /**
657485bb99bSRandy Dunlap  * filemap_write_and_wait_range - write out & wait on a file range
658485bb99bSRandy Dunlap  * @mapping:	the address_space for the pages
659485bb99bSRandy Dunlap  * @lstart:	offset in bytes where the range starts
660485bb99bSRandy Dunlap  * @lend:	offset in bytes where the range ends (inclusive)
661485bb99bSRandy Dunlap  *
662469eb4d0SAndrew Morton  * Write out and wait upon file offsets lstart->lend, inclusive.
663469eb4d0SAndrew Morton  *
6640e056eb5Smchehab@s-opensource.com  * Note that @lend is inclusive (describes the last byte to be written) so
665469eb4d0SAndrew Morton  * that this function can be used to write to the very end-of-file (end = -1).
666a862f68aSMike Rapoport  *
667a862f68aSMike Rapoport  * Return: error status of the address space.
668469eb4d0SAndrew Morton  */
filemap_write_and_wait_range(struct address_space * mapping,loff_t lstart,loff_t lend)6691da177e4SLinus Torvalds int filemap_write_and_wait_range(struct address_space *mapping,
6701da177e4SLinus Torvalds 				 loff_t lstart, loff_t lend)
6711da177e4SLinus Torvalds {
672ccac11daSMiaohe Lin 	int err = 0, err2;
6731da177e4SLinus Torvalds 
674feeb9b26SBrian Foster 	if (lend < lstart)
675feeb9b26SBrian Foster 		return 0;
676feeb9b26SBrian Foster 
6779326c9b2SJeff Layton 	if (mapping_needs_writeback(mapping)) {
67828fd1298SOGAWA Hirofumi 		err = __filemap_fdatawrite_range(mapping, lstart, lend,
6791da177e4SLinus Torvalds 						 WB_SYNC_ALL);
680ddf8f376SIra Weiny 		/*
681ddf8f376SIra Weiny 		 * Even if the above returned error, the pages may be
682ddf8f376SIra Weiny 		 * written partially (e.g. -ENOSPC), so we wait for it.
683ddf8f376SIra Weiny 		 * But the -EIO is special case, it may indicate the worst
684ddf8f376SIra Weiny 		 * thing (e.g. bug) happened, so we avoid waiting for it.
685ddf8f376SIra Weiny 		 */
686ccac11daSMiaohe Lin 		if (err != -EIO)
687ccac11daSMiaohe Lin 			__filemap_fdatawait_range(mapping, lstart, lend);
688ccac11daSMiaohe Lin 	}
689ccac11daSMiaohe Lin 	err2 = filemap_check_errors(mapping);
69028fd1298SOGAWA Hirofumi 	if (!err)
69128fd1298SOGAWA Hirofumi 		err = err2;
69228fd1298SOGAWA Hirofumi 	return err;
6931da177e4SLinus Torvalds }
694f6995585SChris Mason EXPORT_SYMBOL(filemap_write_and_wait_range);
6951da177e4SLinus Torvalds 
__filemap_set_wb_err(struct address_space * mapping,int err)6965660e13dSJeff Layton void __filemap_set_wb_err(struct address_space *mapping, int err)
6975660e13dSJeff Layton {
6983acdfd28SJeff Layton 	errseq_t eseq = errseq_set(&mapping->wb_err, err);
6995660e13dSJeff Layton 
7005660e13dSJeff Layton 	trace_filemap_set_wb_err(mapping, eseq);
7015660e13dSJeff Layton }
7025660e13dSJeff Layton EXPORT_SYMBOL(__filemap_set_wb_err);
7035660e13dSJeff Layton 
7045660e13dSJeff Layton /**
7055660e13dSJeff Layton  * file_check_and_advance_wb_err - report wb error (if any) that was previously
7065660e13dSJeff Layton  * 				   and advance wb_err to current one
7075660e13dSJeff Layton  * @file: struct file on which the error is being reported
7085660e13dSJeff Layton  *
7095660e13dSJeff Layton  * When userland calls fsync (or something like nfsd does the equivalent), we
7105660e13dSJeff Layton  * want to report any writeback errors that occurred since the last fsync (or
7115660e13dSJeff Layton  * since the file was opened if there haven't been any).
7125660e13dSJeff Layton  *
7135660e13dSJeff Layton  * Grab the wb_err from the mapping. If it matches what we have in the file,
7145660e13dSJeff Layton  * then just quickly return 0. The file is all caught up.
7155660e13dSJeff Layton  *
7165660e13dSJeff Layton  * If it doesn't match, then take the mapping value, set the "seen" flag in
7175660e13dSJeff Layton  * it and try to swap it into place. If it works, or another task beat us
7185660e13dSJeff Layton  * to it with the new value, then update the f_wb_err and return the error
7195660e13dSJeff Layton  * portion. The error at this point must be reported via proper channels
7205660e13dSJeff Layton  * (a'la fsync, or NFS COMMIT operation, etc.).
7215660e13dSJeff Layton  *
7225660e13dSJeff Layton  * While we handle mapping->wb_err with atomic operations, the f_wb_err
7235660e13dSJeff Layton  * value is protected by the f_lock since we must ensure that it reflects
7245660e13dSJeff Layton  * the latest value swapped in for this file descriptor.
725a862f68aSMike Rapoport  *
726a862f68aSMike Rapoport  * Return: %0 on success, negative error code otherwise.
7275660e13dSJeff Layton  */
file_check_and_advance_wb_err(struct file * file)7285660e13dSJeff Layton int file_check_and_advance_wb_err(struct file *file)
7295660e13dSJeff Layton {
7305660e13dSJeff Layton 	int err = 0;
7315660e13dSJeff Layton 	errseq_t old = READ_ONCE(file->f_wb_err);
7325660e13dSJeff Layton 	struct address_space *mapping = file->f_mapping;
7335660e13dSJeff Layton 
7345660e13dSJeff Layton 	/* Locklessly handle the common case where nothing has changed */
7355660e13dSJeff Layton 	if (errseq_check(&mapping->wb_err, old)) {
7365660e13dSJeff Layton 		/* Something changed, must use slow path */
7375660e13dSJeff Layton 		spin_lock(&file->f_lock);
7385660e13dSJeff Layton 		old = file->f_wb_err;
7395660e13dSJeff Layton 		err = errseq_check_and_advance(&mapping->wb_err,
7405660e13dSJeff Layton 						&file->f_wb_err);
7415660e13dSJeff Layton 		trace_file_check_and_advance_wb_err(file, old);
7425660e13dSJeff Layton 		spin_unlock(&file->f_lock);
7435660e13dSJeff Layton 	}
744f4e222c5SJeff Layton 
745f4e222c5SJeff Layton 	/*
746f4e222c5SJeff Layton 	 * We're mostly using this function as a drop in replacement for
747f4e222c5SJeff Layton 	 * filemap_check_errors. Clear AS_EIO/AS_ENOSPC to emulate the effect
748f4e222c5SJeff Layton 	 * that the legacy code would have had on these flags.
749f4e222c5SJeff Layton 	 */
750f4e222c5SJeff Layton 	clear_bit(AS_EIO, &mapping->flags);
751f4e222c5SJeff Layton 	clear_bit(AS_ENOSPC, &mapping->flags);
7525660e13dSJeff Layton 	return err;
7535660e13dSJeff Layton }
7545660e13dSJeff Layton EXPORT_SYMBOL(file_check_and_advance_wb_err);
7555660e13dSJeff Layton 
7565660e13dSJeff Layton /**
7575660e13dSJeff Layton  * file_write_and_wait_range - write out & wait on a file range
7585660e13dSJeff Layton  * @file:	file pointing to address_space with pages
7595660e13dSJeff Layton  * @lstart:	offset in bytes where the range starts
7605660e13dSJeff Layton  * @lend:	offset in bytes where the range ends (inclusive)
7615660e13dSJeff Layton  *
7625660e13dSJeff Layton  * Write out and wait upon file offsets lstart->lend, inclusive.
7635660e13dSJeff Layton  *
7645660e13dSJeff Layton  * Note that @lend is inclusive (describes the last byte to be written) so
7655660e13dSJeff Layton  * that this function can be used to write to the very end-of-file (end = -1).
7665660e13dSJeff Layton  *
7675660e13dSJeff Layton  * After writing out and waiting on the data, we check and advance the
7685660e13dSJeff Layton  * f_wb_err cursor to the latest value, and return any errors detected there.
769a862f68aSMike Rapoport  *
770a862f68aSMike Rapoport  * Return: %0 on success, negative error code otherwise.
7715660e13dSJeff Layton  */
file_write_and_wait_range(struct file * file,loff_t lstart,loff_t lend)7725660e13dSJeff Layton int file_write_and_wait_range(struct file *file, loff_t lstart, loff_t lend)
7735660e13dSJeff Layton {
7745660e13dSJeff Layton 	int err = 0, err2;
7755660e13dSJeff Layton 	struct address_space *mapping = file->f_mapping;
7765660e13dSJeff Layton 
777feeb9b26SBrian Foster 	if (lend < lstart)
778feeb9b26SBrian Foster 		return 0;
779feeb9b26SBrian Foster 
7809326c9b2SJeff Layton 	if (mapping_needs_writeback(mapping)) {
7815660e13dSJeff Layton 		err = __filemap_fdatawrite_range(mapping, lstart, lend,
7825660e13dSJeff Layton 						 WB_SYNC_ALL);
7835660e13dSJeff Layton 		/* See comment of filemap_write_and_wait() */
7845660e13dSJeff Layton 		if (err != -EIO)
7855660e13dSJeff Layton 			__filemap_fdatawait_range(mapping, lstart, lend);
7865660e13dSJeff Layton 	}
7875660e13dSJeff Layton 	err2 = file_check_and_advance_wb_err(file);
7885660e13dSJeff Layton 	if (!err)
7895660e13dSJeff Layton 		err = err2;
7905660e13dSJeff Layton 	return err;
7915660e13dSJeff Layton }
7925660e13dSJeff Layton EXPORT_SYMBOL(file_write_and_wait_range);
7935660e13dSJeff Layton 
794485bb99bSRandy Dunlap /**
7953720dd6dSVishal Moola (Oracle)  * replace_page_cache_folio - replace a pagecache folio with a new one
7963720dd6dSVishal Moola (Oracle)  * @old:	folio to be replaced
7973720dd6dSVishal Moola (Oracle)  * @new:	folio to replace with
798ef6a3c63SMiklos Szeredi  *
7993720dd6dSVishal Moola (Oracle)  * This function replaces a folio in the pagecache with a new one.  On
8003720dd6dSVishal Moola (Oracle)  * success it acquires the pagecache reference for the new folio and
8013720dd6dSVishal Moola (Oracle)  * drops it for the old folio.  Both the old and new folios must be
8023720dd6dSVishal Moola (Oracle)  * locked.  This function does not add the new folio to the LRU, the
803ef6a3c63SMiklos Szeredi  * caller must do that.
804ef6a3c63SMiklos Szeredi  *
80574d60958SMatthew Wilcox  * The remove + add is atomic.  This function cannot fail.
806ef6a3c63SMiklos Szeredi  */
replace_page_cache_folio(struct folio * old,struct folio * new)8073720dd6dSVishal Moola (Oracle) void replace_page_cache_folio(struct folio *old, struct folio *new)
808ef6a3c63SMiklos Szeredi {
80974d60958SMatthew Wilcox 	struct address_space *mapping = old->mapping;
810d2329aa0SMatthew Wilcox (Oracle) 	void (*free_folio)(struct folio *) = mapping->a_ops->free_folio;
81174d60958SMatthew Wilcox 	pgoff_t offset = old->index;
81274d60958SMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, offset);
813ef6a3c63SMiklos Szeredi 
8143720dd6dSVishal Moola (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(old), old);
8153720dd6dSVishal Moola (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(new), new);
8163720dd6dSVishal Moola (Oracle) 	VM_BUG_ON_FOLIO(new->mapping, new);
817ef6a3c63SMiklos Szeredi 
8183720dd6dSVishal Moola (Oracle) 	folio_get(new);
819ef6a3c63SMiklos Szeredi 	new->mapping = mapping;
820ef6a3c63SMiklos Szeredi 	new->index = offset;
821ef6a3c63SMiklos Szeredi 
8223720dd6dSVishal Moola (Oracle) 	mem_cgroup_migrate(old, new);
8230d1c2072SJohannes Weiner 
82430472509SJohannes Weiner 	xas_lock_irq(&xas);
82574d60958SMatthew Wilcox 	xas_store(&xas, new);
8264165b9b4SMichal Hocko 
82774d60958SMatthew Wilcox 	old->mapping = NULL;
82874d60958SMatthew Wilcox 	/* hugetlb pages do not participate in page cache accounting. */
8293720dd6dSVishal Moola (Oracle) 	if (!folio_test_hugetlb(old))
8303720dd6dSVishal Moola (Oracle) 		__lruvec_stat_sub_folio(old, NR_FILE_PAGES);
8313720dd6dSVishal Moola (Oracle) 	if (!folio_test_hugetlb(new))
8323720dd6dSVishal Moola (Oracle) 		__lruvec_stat_add_folio(new, NR_FILE_PAGES);
8333720dd6dSVishal Moola (Oracle) 	if (folio_test_swapbacked(old))
8343720dd6dSVishal Moola (Oracle) 		__lruvec_stat_sub_folio(old, NR_SHMEM);
8353720dd6dSVishal Moola (Oracle) 	if (folio_test_swapbacked(new))
8363720dd6dSVishal Moola (Oracle) 		__lruvec_stat_add_folio(new, NR_SHMEM);
83730472509SJohannes Weiner 	xas_unlock_irq(&xas);
838d2329aa0SMatthew Wilcox (Oracle) 	if (free_folio)
8393720dd6dSVishal Moola (Oracle) 		free_folio(old);
8403720dd6dSVishal Moola (Oracle) 	folio_put(old);
841ef6a3c63SMiklos Szeredi }
8423720dd6dSVishal Moola (Oracle) EXPORT_SYMBOL_GPL(replace_page_cache_folio);
843ef6a3c63SMiklos Szeredi 
__filemap_add_folio(struct address_space * mapping,struct folio * folio,pgoff_t index,gfp_t gfp,void ** shadowp)8449dd3d069SMatthew Wilcox (Oracle) noinline int __filemap_add_folio(struct address_space *mapping,
8459dd3d069SMatthew Wilcox (Oracle) 		struct folio *folio, pgoff_t index, gfp_t gfp, void **shadowp)
8461da177e4SLinus Torvalds {
8479dd3d069SMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, index);
8489dd3d069SMatthew Wilcox (Oracle) 	int huge = folio_test_hugetlb(folio);
849da74240eSWaiman Long 	bool charged = false;
850d68eccadSMatthew Wilcox (Oracle) 	long nr = 1;
851e286781dSNick Piggin 
8529dd3d069SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
8539dd3d069SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(folio_test_swapbacked(folio), folio);
85474d60958SMatthew Wilcox 	mapping_set_update(&xas, mapping);
855e286781dSNick Piggin 
8563fea5a49SJohannes Weiner 	if (!huge) {
857d68eccadSMatthew Wilcox (Oracle) 		int error = mem_cgroup_charge(folio, NULL, gfp);
8589dd3d069SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(index & (folio_nr_pages(folio) - 1), folio);
8593fea5a49SJohannes Weiner 		if (error)
860d68eccadSMatthew Wilcox (Oracle) 			return error;
861da74240eSWaiman Long 		charged = true;
862d68eccadSMatthew Wilcox (Oracle) 		xas_set_order(&xas, index, folio_order(folio));
863d68eccadSMatthew Wilcox (Oracle) 		nr = folio_nr_pages(folio);
8643fea5a49SJohannes Weiner 	}
8653fea5a49SJohannes Weiner 
866198b62f8SMatthew Wilcox (Oracle) 	gfp &= GFP_RECLAIM_MASK;
867d68eccadSMatthew Wilcox (Oracle) 	folio_ref_add(folio, nr);
868d68eccadSMatthew Wilcox (Oracle) 	folio->mapping = mapping;
869d68eccadSMatthew Wilcox (Oracle) 	folio->index = xas.xa_index;
870198b62f8SMatthew Wilcox (Oracle) 
87174d60958SMatthew Wilcox 	do {
872198b62f8SMatthew Wilcox (Oracle) 		unsigned int order = xa_get_order(xas.xa, xas.xa_index);
873198b62f8SMatthew Wilcox (Oracle) 		void *entry, *old = NULL;
874198b62f8SMatthew Wilcox (Oracle) 
8759dd3d069SMatthew Wilcox (Oracle) 		if (order > folio_order(folio))
876198b62f8SMatthew Wilcox (Oracle) 			xas_split_alloc(&xas, xa_load(xas.xa, xas.xa_index),
877198b62f8SMatthew Wilcox (Oracle) 					order, gfp);
87874d60958SMatthew Wilcox 		xas_lock_irq(&xas);
879198b62f8SMatthew Wilcox (Oracle) 		xas_for_each_conflict(&xas, entry) {
880198b62f8SMatthew Wilcox (Oracle) 			old = entry;
881198b62f8SMatthew Wilcox (Oracle) 			if (!xa_is_value(entry)) {
88274d60958SMatthew Wilcox 				xas_set_err(&xas, -EEXIST);
883198b62f8SMatthew Wilcox (Oracle) 				goto unlock;
884198b62f8SMatthew Wilcox (Oracle) 			}
885198b62f8SMatthew Wilcox (Oracle) 		}
886198b62f8SMatthew Wilcox (Oracle) 
887198b62f8SMatthew Wilcox (Oracle) 		if (old) {
888198b62f8SMatthew Wilcox (Oracle) 			if (shadowp)
889198b62f8SMatthew Wilcox (Oracle) 				*shadowp = old;
890198b62f8SMatthew Wilcox (Oracle) 			/* entry may have been split before we acquired lock */
891198b62f8SMatthew Wilcox (Oracle) 			order = xa_get_order(xas.xa, xas.xa_index);
8929dd3d069SMatthew Wilcox (Oracle) 			if (order > folio_order(folio)) {
893d68eccadSMatthew Wilcox (Oracle) 				/* How to handle large swap entries? */
894d68eccadSMatthew Wilcox (Oracle) 				BUG_ON(shmem_mapping(mapping));
895198b62f8SMatthew Wilcox (Oracle) 				xas_split(&xas, old, order);
896198b62f8SMatthew Wilcox (Oracle) 				xas_reset(&xas);
897198b62f8SMatthew Wilcox (Oracle) 			}
898198b62f8SMatthew Wilcox (Oracle) 		}
899198b62f8SMatthew Wilcox (Oracle) 
9009dd3d069SMatthew Wilcox (Oracle) 		xas_store(&xas, folio);
90174d60958SMatthew Wilcox 		if (xas_error(&xas))
90274d60958SMatthew Wilcox 			goto unlock;
9034165b9b4SMichal Hocko 
904d68eccadSMatthew Wilcox (Oracle) 		mapping->nrpages += nr;
90574d60958SMatthew Wilcox 
90674d60958SMatthew Wilcox 		/* hugetlb pages do not participate in page cache accounting */
907d68eccadSMatthew Wilcox (Oracle) 		if (!huge) {
908d68eccadSMatthew Wilcox (Oracle) 			__lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr);
909d68eccadSMatthew Wilcox (Oracle) 			if (folio_test_pmd_mappable(folio))
910d68eccadSMatthew Wilcox (Oracle) 				__lruvec_stat_mod_folio(folio,
911d68eccadSMatthew Wilcox (Oracle) 						NR_FILE_THPS, nr);
912d68eccadSMatthew Wilcox (Oracle) 		}
91374d60958SMatthew Wilcox unlock:
91474d60958SMatthew Wilcox 		xas_unlock_irq(&xas);
915198b62f8SMatthew Wilcox (Oracle) 	} while (xas_nomem(&xas, gfp));
91674d60958SMatthew Wilcox 
917d68eccadSMatthew Wilcox (Oracle) 	if (xas_error(&xas))
91874d60958SMatthew Wilcox 		goto error;
91974d60958SMatthew Wilcox 
920a0580c6fSMatthew Wilcox (Oracle) 	trace_mm_filemap_add_to_page_cache(folio);
92166a0c8eeSKirill A. Shutemov 	return 0;
92274d60958SMatthew Wilcox error:
923d68eccadSMatthew Wilcox (Oracle) 	if (charged)
924d68eccadSMatthew Wilcox (Oracle) 		mem_cgroup_uncharge(folio);
9259dd3d069SMatthew Wilcox (Oracle) 	folio->mapping = NULL;
926b85e0effSHugh Dickins 	/* Leave page->index set: truncation relies upon it */
927d68eccadSMatthew Wilcox (Oracle) 	folio_put_refs(folio, nr);
928d68eccadSMatthew Wilcox (Oracle) 	return xas_error(&xas);
9291da177e4SLinus Torvalds }
9309dd3d069SMatthew Wilcox (Oracle) ALLOW_ERROR_INJECTION(__filemap_add_folio, ERRNO);
931a528910eSJohannes Weiner 
filemap_add_folio(struct address_space * mapping,struct folio * folio,pgoff_t index,gfp_t gfp)9329dd3d069SMatthew Wilcox (Oracle) int filemap_add_folio(struct address_space *mapping, struct folio *folio,
9339dd3d069SMatthew Wilcox (Oracle) 				pgoff_t index, gfp_t gfp)
9341da177e4SLinus Torvalds {
935a528910eSJohannes Weiner 	void *shadow = NULL;
9364f98a2feSRik van Riel 	int ret;
9374f98a2feSRik van Riel 
9389dd3d069SMatthew Wilcox (Oracle) 	__folio_set_locked(folio);
9399dd3d069SMatthew Wilcox (Oracle) 	ret = __filemap_add_folio(mapping, folio, index, gfp, &shadow);
940a528910eSJohannes Weiner 	if (unlikely(ret))
9419dd3d069SMatthew Wilcox (Oracle) 		__folio_clear_locked(folio);
942a528910eSJohannes Weiner 	else {
943a528910eSJohannes Weiner 		/*
9449dd3d069SMatthew Wilcox (Oracle) 		 * The folio might have been evicted from cache only
945a528910eSJohannes Weiner 		 * recently, in which case it should be activated like
9469dd3d069SMatthew Wilcox (Oracle) 		 * any other repeatedly accessed folio.
9479dd3d069SMatthew Wilcox (Oracle) 		 * The exception is folios getting rewritten; evicting other
948f0281a00SRik van Riel 		 * data from the working set, only to cache data that will
949f0281a00SRik van Riel 		 * get overwritten with something else, is a waste of memory.
950a528910eSJohannes Weiner 		 */
9519dd3d069SMatthew Wilcox (Oracle) 		WARN_ON_ONCE(folio_test_active(folio));
9529dd3d069SMatthew Wilcox (Oracle) 		if (!(gfp & __GFP_WRITE) && shadow)
9539dd3d069SMatthew Wilcox (Oracle) 			workingset_refault(folio, shadow);
9549dd3d069SMatthew Wilcox (Oracle) 		folio_add_lru(folio);
955a528910eSJohannes Weiner 	}
9561da177e4SLinus Torvalds 	return ret;
9571da177e4SLinus Torvalds }
9589dd3d069SMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(filemap_add_folio);
9591da177e4SLinus Torvalds 
96044110fe3SPaul Jackson #ifdef CONFIG_NUMA
filemap_alloc_folio(gfp_t gfp,unsigned int order)961bb3c579eSMatthew Wilcox (Oracle) struct folio *filemap_alloc_folio(gfp_t gfp, unsigned int order)
96244110fe3SPaul Jackson {
963c0ff7453SMiao Xie 	int n;
964bb3c579eSMatthew Wilcox (Oracle) 	struct folio *folio;
965c0ff7453SMiao Xie 
96644110fe3SPaul Jackson 	if (cpuset_do_page_mem_spread()) {
967cc9a6c87SMel Gorman 		unsigned int cpuset_mems_cookie;
968cc9a6c87SMel Gorman 		do {
969d26914d1SMel Gorman 			cpuset_mems_cookie = read_mems_allowed_begin();
970c0ff7453SMiao Xie 			n = cpuset_mem_spread_node();
971bb3c579eSMatthew Wilcox (Oracle) 			folio = __folio_alloc_node(gfp, order, n);
972bb3c579eSMatthew Wilcox (Oracle) 		} while (!folio && read_mems_allowed_retry(cpuset_mems_cookie));
973cc9a6c87SMel Gorman 
974bb3c579eSMatthew Wilcox (Oracle) 		return folio;
97544110fe3SPaul Jackson 	}
976bb3c579eSMatthew Wilcox (Oracle) 	return folio_alloc(gfp, order);
97744110fe3SPaul Jackson }
978bb3c579eSMatthew Wilcox (Oracle) EXPORT_SYMBOL(filemap_alloc_folio);
97944110fe3SPaul Jackson #endif
98044110fe3SPaul Jackson 
9811da177e4SLinus Torvalds /*
9827506ae6aSJan Kara  * filemap_invalidate_lock_two - lock invalidate_lock for two mappings
9837506ae6aSJan Kara  *
9847506ae6aSJan Kara  * Lock exclusively invalidate_lock of any passed mapping that is not NULL.
9857506ae6aSJan Kara  *
9867506ae6aSJan Kara  * @mapping1: the first mapping to lock
9877506ae6aSJan Kara  * @mapping2: the second mapping to lock
9887506ae6aSJan Kara  */
filemap_invalidate_lock_two(struct address_space * mapping1,struct address_space * mapping2)9897506ae6aSJan Kara void filemap_invalidate_lock_two(struct address_space *mapping1,
9907506ae6aSJan Kara 				 struct address_space *mapping2)
9917506ae6aSJan Kara {
9927506ae6aSJan Kara 	if (mapping1 > mapping2)
9937506ae6aSJan Kara 		swap(mapping1, mapping2);
9947506ae6aSJan Kara 	if (mapping1)
9957506ae6aSJan Kara 		down_write(&mapping1->invalidate_lock);
9967506ae6aSJan Kara 	if (mapping2 && mapping1 != mapping2)
9977506ae6aSJan Kara 		down_write_nested(&mapping2->invalidate_lock, 1);
9987506ae6aSJan Kara }
9997506ae6aSJan Kara EXPORT_SYMBOL(filemap_invalidate_lock_two);
10007506ae6aSJan Kara 
10017506ae6aSJan Kara /*
10027506ae6aSJan Kara  * filemap_invalidate_unlock_two - unlock invalidate_lock for two mappings
10037506ae6aSJan Kara  *
10047506ae6aSJan Kara  * Unlock exclusive invalidate_lock of any passed mapping that is not NULL.
10057506ae6aSJan Kara  *
10067506ae6aSJan Kara  * @mapping1: the first mapping to unlock
10077506ae6aSJan Kara  * @mapping2: the second mapping to unlock
10087506ae6aSJan Kara  */
filemap_invalidate_unlock_two(struct address_space * mapping1,struct address_space * mapping2)10097506ae6aSJan Kara void filemap_invalidate_unlock_two(struct address_space *mapping1,
10107506ae6aSJan Kara 				   struct address_space *mapping2)
10117506ae6aSJan Kara {
10127506ae6aSJan Kara 	if (mapping1)
10137506ae6aSJan Kara 		up_write(&mapping1->invalidate_lock);
10147506ae6aSJan Kara 	if (mapping2 && mapping1 != mapping2)
10157506ae6aSJan Kara 		up_write(&mapping2->invalidate_lock);
10167506ae6aSJan Kara }
10177506ae6aSJan Kara EXPORT_SYMBOL(filemap_invalidate_unlock_two);
10187506ae6aSJan Kara 
10197506ae6aSJan Kara /*
10201da177e4SLinus Torvalds  * In order to wait for pages to become available there must be
10211da177e4SLinus Torvalds  * waitqueues associated with pages. By using a hash table of
10221da177e4SLinus Torvalds  * waitqueues where the bucket discipline is to maintain all
10231da177e4SLinus Torvalds  * waiters on the same queue and wake all when any of the pages
10241da177e4SLinus Torvalds  * become available, and for the woken contexts to check to be
10251da177e4SLinus Torvalds  * sure the appropriate page became available, this saves space
10261da177e4SLinus Torvalds  * at a cost of "thundering herd" phenomena during rare hash
10271da177e4SLinus Torvalds  * collisions.
10281da177e4SLinus Torvalds  */
102962906027SNicholas Piggin #define PAGE_WAIT_TABLE_BITS 8
103062906027SNicholas Piggin #define PAGE_WAIT_TABLE_SIZE (1 << PAGE_WAIT_TABLE_BITS)
1031df4d4f12SMatthew Wilcox (Oracle) static wait_queue_head_t folio_wait_table[PAGE_WAIT_TABLE_SIZE] __cacheline_aligned;
103262906027SNicholas Piggin 
folio_waitqueue(struct folio * folio)1033df4d4f12SMatthew Wilcox (Oracle) static wait_queue_head_t *folio_waitqueue(struct folio *folio)
10341da177e4SLinus Torvalds {
1035df4d4f12SMatthew Wilcox (Oracle) 	return &folio_wait_table[hash_ptr(folio, PAGE_WAIT_TABLE_BITS)];
10361da177e4SLinus Torvalds }
103762906027SNicholas Piggin 
pagecache_init(void)103862906027SNicholas Piggin void __init pagecache_init(void)
103962906027SNicholas Piggin {
104062906027SNicholas Piggin 	int i;
104162906027SNicholas Piggin 
104262906027SNicholas Piggin 	for (i = 0; i < PAGE_WAIT_TABLE_SIZE; i++)
1043df4d4f12SMatthew Wilcox (Oracle) 		init_waitqueue_head(&folio_wait_table[i]);
104462906027SNicholas Piggin 
104562906027SNicholas Piggin 	page_writeback_init();
104662906027SNicholas Piggin }
104762906027SNicholas Piggin 
10485ef64cc8SLinus Torvalds /*
10495ef64cc8SLinus Torvalds  * The page wait code treats the "wait->flags" somewhat unusually, because
10505868ec26SLinus Torvalds  * we have multiple different kinds of waits, not just the usual "exclusive"
10515ef64cc8SLinus Torvalds  * one.
10525ef64cc8SLinus Torvalds  *
10535ef64cc8SLinus Torvalds  * We have:
10545ef64cc8SLinus Torvalds  *
10555ef64cc8SLinus Torvalds  *  (a) no special bits set:
10565ef64cc8SLinus Torvalds  *
10575ef64cc8SLinus Torvalds  *	We're just waiting for the bit to be released, and when a waker
10585ef64cc8SLinus Torvalds  *	calls the wakeup function, we set WQ_FLAG_WOKEN and wake it up,
10595ef64cc8SLinus Torvalds  *	and remove it from the wait queue.
10605ef64cc8SLinus Torvalds  *
10615ef64cc8SLinus Torvalds  *	Simple and straightforward.
10625ef64cc8SLinus Torvalds  *
10635ef64cc8SLinus Torvalds  *  (b) WQ_FLAG_EXCLUSIVE:
10645ef64cc8SLinus Torvalds  *
10655ef64cc8SLinus Torvalds  *	The waiter is waiting to get the lock, and only one waiter should
10665ef64cc8SLinus Torvalds  *	be woken up to avoid any thundering herd behavior. We'll set the
10675ef64cc8SLinus Torvalds  *	WQ_FLAG_WOKEN bit, wake it up, and remove it from the wait queue.
10685ef64cc8SLinus Torvalds  *
10695ef64cc8SLinus Torvalds  *	This is the traditional exclusive wait.
10705ef64cc8SLinus Torvalds  *
10715868ec26SLinus Torvalds  *  (c) WQ_FLAG_EXCLUSIVE | WQ_FLAG_CUSTOM:
10725ef64cc8SLinus Torvalds  *
10735ef64cc8SLinus Torvalds  *	The waiter is waiting to get the bit, and additionally wants the
10745ef64cc8SLinus Torvalds  *	lock to be transferred to it for fair lock behavior. If the lock
10755ef64cc8SLinus Torvalds  *	cannot be taken, we stop walking the wait queue without waking
10765ef64cc8SLinus Torvalds  *	the waiter.
10775ef64cc8SLinus Torvalds  *
10785ef64cc8SLinus Torvalds  *	This is the "fair lock handoff" case, and in addition to setting
10795ef64cc8SLinus Torvalds  *	WQ_FLAG_WOKEN, we set WQ_FLAG_DONE to let the waiter easily see
10805ef64cc8SLinus Torvalds  *	that it now has the lock.
10815ef64cc8SLinus Torvalds  */
wake_page_function(wait_queue_entry_t * wait,unsigned mode,int sync,void * arg)1082ac6424b9SIngo Molnar static int wake_page_function(wait_queue_entry_t *wait, unsigned mode, int sync, void *arg)
108362906027SNicholas Piggin {
10845ef64cc8SLinus Torvalds 	unsigned int flags;
108562906027SNicholas Piggin 	struct wait_page_key *key = arg;
108662906027SNicholas Piggin 	struct wait_page_queue *wait_page
108762906027SNicholas Piggin 		= container_of(wait, struct wait_page_queue, wait);
108862906027SNicholas Piggin 
1089cdc8fcb4SLinus Torvalds 	if (!wake_page_match(wait_page, key))
109062906027SNicholas Piggin 		return 0;
10913510ca20SLinus Torvalds 
10929a1ea439SHugh Dickins 	/*
10935ef64cc8SLinus Torvalds 	 * If it's a lock handoff wait, we get the bit for it, and
10945ef64cc8SLinus Torvalds 	 * stop walking (and do not wake it up) if we can't.
10959a1ea439SHugh Dickins 	 */
10965ef64cc8SLinus Torvalds 	flags = wait->flags;
10975ef64cc8SLinus Torvalds 	if (flags & WQ_FLAG_EXCLUSIVE) {
1098df4d4f12SMatthew Wilcox (Oracle) 		if (test_bit(key->bit_nr, &key->folio->flags))
10995ef64cc8SLinus Torvalds 			return -1;
11005ef64cc8SLinus Torvalds 		if (flags & WQ_FLAG_CUSTOM) {
1101df4d4f12SMatthew Wilcox (Oracle) 			if (test_and_set_bit(key->bit_nr, &key->folio->flags))
11023510ca20SLinus Torvalds 				return -1;
11035ef64cc8SLinus Torvalds 			flags |= WQ_FLAG_DONE;
11042a9127fcSLinus Torvalds 		}
11055ef64cc8SLinus Torvalds 	}
110662906027SNicholas Piggin 
11075ef64cc8SLinus Torvalds 	/*
11085ef64cc8SLinus Torvalds 	 * We are holding the wait-queue lock, but the waiter that
11095ef64cc8SLinus Torvalds 	 * is waiting for this will be checking the flags without
11105ef64cc8SLinus Torvalds 	 * any locking.
11115ef64cc8SLinus Torvalds 	 *
11125ef64cc8SLinus Torvalds 	 * So update the flags atomically, and wake up the waiter
11135ef64cc8SLinus Torvalds 	 * afterwards to avoid any races. This store-release pairs
1114101c0bf6SMatthew Wilcox (Oracle) 	 * with the load-acquire in folio_wait_bit_common().
11155ef64cc8SLinus Torvalds 	 */
11165ef64cc8SLinus Torvalds 	smp_store_release(&wait->flags, flags | WQ_FLAG_WOKEN);
11172a9127fcSLinus Torvalds 	wake_up_state(wait->private, mode);
11182a9127fcSLinus Torvalds 
11192a9127fcSLinus Torvalds 	/*
11202a9127fcSLinus Torvalds 	 * Ok, we have successfully done what we're waiting for,
11212a9127fcSLinus Torvalds 	 * and we can unconditionally remove the wait entry.
11222a9127fcSLinus Torvalds 	 *
11235ef64cc8SLinus Torvalds 	 * Note that this pairs with the "finish_wait()" in the
11245ef64cc8SLinus Torvalds 	 * waiter, and has to be the absolute last thing we do.
11255ef64cc8SLinus Torvalds 	 * After this list_del_init(&wait->entry) the wait entry
11262a9127fcSLinus Torvalds 	 * might be de-allocated and the process might even have
11272a9127fcSLinus Torvalds 	 * exited.
11282a9127fcSLinus Torvalds 	 */
1129c6fe44d9SLinus Torvalds 	list_del_init_careful(&wait->entry);
11305ef64cc8SLinus Torvalds 	return (flags & WQ_FLAG_EXCLUSIVE) != 0;
113162906027SNicholas Piggin }
113262906027SNicholas Piggin 
folio_wake_bit(struct folio * folio,int bit_nr)11336974d7c9SMatthew Wilcox (Oracle) static void folio_wake_bit(struct folio *folio, int bit_nr)
113462906027SNicholas Piggin {
1135df4d4f12SMatthew Wilcox (Oracle) 	wait_queue_head_t *q = folio_waitqueue(folio);
113662906027SNicholas Piggin 	struct wait_page_key key;
113762906027SNicholas Piggin 	unsigned long flags;
113811a19c7bSTim Chen 	wait_queue_entry_t bookmark;
113962906027SNicholas Piggin 
1140df4d4f12SMatthew Wilcox (Oracle) 	key.folio = folio;
114162906027SNicholas Piggin 	key.bit_nr = bit_nr;
114262906027SNicholas Piggin 	key.page_match = 0;
114362906027SNicholas Piggin 
114411a19c7bSTim Chen 	bookmark.flags = 0;
114511a19c7bSTim Chen 	bookmark.private = NULL;
114611a19c7bSTim Chen 	bookmark.func = NULL;
114711a19c7bSTim Chen 	INIT_LIST_HEAD(&bookmark.entry);
114811a19c7bSTim Chen 
114962906027SNicholas Piggin 	spin_lock_irqsave(&q->lock, flags);
115011a19c7bSTim Chen 	__wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
115111a19c7bSTim Chen 
115211a19c7bSTim Chen 	while (bookmark.flags & WQ_FLAG_BOOKMARK) {
115311a19c7bSTim Chen 		/*
115411a19c7bSTim Chen 		 * Take a breather from holding the lock,
115511a19c7bSTim Chen 		 * allow pages that finish wake up asynchronously
115611a19c7bSTim Chen 		 * to acquire the lock and remove themselves
115711a19c7bSTim Chen 		 * from wait queue
115811a19c7bSTim Chen 		 */
115911a19c7bSTim Chen 		spin_unlock_irqrestore(&q->lock, flags);
116011a19c7bSTim Chen 		cpu_relax();
116111a19c7bSTim Chen 		spin_lock_irqsave(&q->lock, flags);
116211a19c7bSTim Chen 		__wake_up_locked_key_bookmark(q, TASK_NORMAL, &key, &bookmark);
116311a19c7bSTim Chen 	}
116411a19c7bSTim Chen 
116562906027SNicholas Piggin 	/*
1166bb43b14bSHugh Dickins 	 * It's possible to miss clearing waiters here, when we woke our page
1167bb43b14bSHugh Dickins 	 * waiters, but the hashed waitqueue has waiters for other pages on it.
116862906027SNicholas Piggin 	 * That's okay, it's a rare case. The next waker will clear it.
1169bb43b14bSHugh Dickins 	 *
1170bb43b14bSHugh Dickins 	 * Note that, depending on the page pool (buddy, hugetlb, ZONE_DEVICE,
1171bb43b14bSHugh Dickins 	 * other), the flag may be cleared in the course of freeing the page;
1172bb43b14bSHugh Dickins 	 * but that is not required for correctness.
117362906027SNicholas Piggin 	 */
1174bb43b14bSHugh Dickins 	if (!waitqueue_active(q) || !key.page_match)
1175bb43b14bSHugh Dickins 		folio_clear_waiters(folio);
1176bb43b14bSHugh Dickins 
117762906027SNicholas Piggin 	spin_unlock_irqrestore(&q->lock, flags);
117862906027SNicholas Piggin }
117974d81bfaSNicholas Piggin 
folio_wake(struct folio * folio,int bit)11804268b480SMatthew Wilcox (Oracle) static void folio_wake(struct folio *folio, int bit)
118174d81bfaSNicholas Piggin {
11824268b480SMatthew Wilcox (Oracle) 	if (!folio_test_waiters(folio))
118374d81bfaSNicholas Piggin 		return;
11846974d7c9SMatthew Wilcox (Oracle) 	folio_wake_bit(folio, bit);
118574d81bfaSNicholas Piggin }
118662906027SNicholas Piggin 
11879a1ea439SHugh Dickins /*
1188101c0bf6SMatthew Wilcox (Oracle)  * A choice of three behaviors for folio_wait_bit_common():
11899a1ea439SHugh Dickins  */
11909a1ea439SHugh Dickins enum behavior {
11919a1ea439SHugh Dickins 	EXCLUSIVE,	/* Hold ref to page and take the bit when woken, like
11927c23c782SMatthew Wilcox (Oracle) 			 * __folio_lock() waiting on then setting PG_locked.
11939a1ea439SHugh Dickins 			 */
11949a1ea439SHugh Dickins 	SHARED,		/* Hold ref to page and check the bit when woken, like
11959f2b04a2SMatthew Wilcox (Oracle) 			 * folio_wait_writeback() waiting on PG_writeback.
11969a1ea439SHugh Dickins 			 */
11979a1ea439SHugh Dickins 	DROP,		/* Drop ref to page before wait, no check when woken,
11989f2b04a2SMatthew Wilcox (Oracle) 			 * like folio_put_wait_locked() on PG_locked.
11999a1ea439SHugh Dickins 			 */
12009a1ea439SHugh Dickins };
12019a1ea439SHugh Dickins 
12022a9127fcSLinus Torvalds /*
1203101c0bf6SMatthew Wilcox (Oracle)  * Attempt to check (or get) the folio flag, and mark us done
12045ef64cc8SLinus Torvalds  * if successful.
12052a9127fcSLinus Torvalds  */
folio_trylock_flag(struct folio * folio,int bit_nr,struct wait_queue_entry * wait)1206101c0bf6SMatthew Wilcox (Oracle) static inline bool folio_trylock_flag(struct folio *folio, int bit_nr,
12072a9127fcSLinus Torvalds 					struct wait_queue_entry *wait)
12082a9127fcSLinus Torvalds {
12092a9127fcSLinus Torvalds 	if (wait->flags & WQ_FLAG_EXCLUSIVE) {
1210101c0bf6SMatthew Wilcox (Oracle) 		if (test_and_set_bit(bit_nr, &folio->flags))
12112a9127fcSLinus Torvalds 			return false;
1212101c0bf6SMatthew Wilcox (Oracle) 	} else if (test_bit(bit_nr, &folio->flags))
12132a9127fcSLinus Torvalds 		return false;
12142a9127fcSLinus Torvalds 
12155ef64cc8SLinus Torvalds 	wait->flags |= WQ_FLAG_WOKEN | WQ_FLAG_DONE;
12162a9127fcSLinus Torvalds 	return true;
12172a9127fcSLinus Torvalds }
12182a9127fcSLinus Torvalds 
12195ef64cc8SLinus Torvalds /* How many times do we accept lock stealing from under a waiter? */
12205ef64cc8SLinus Torvalds int sysctl_page_lock_unfairness = 5;
12215ef64cc8SLinus Torvalds 
folio_wait_bit_common(struct folio * folio,int bit_nr,int state,enum behavior behavior)1222101c0bf6SMatthew Wilcox (Oracle) static inline int folio_wait_bit_common(struct folio *folio, int bit_nr,
1223101c0bf6SMatthew Wilcox (Oracle) 		int state, enum behavior behavior)
122462906027SNicholas Piggin {
1225df4d4f12SMatthew Wilcox (Oracle) 	wait_queue_head_t *q = folio_waitqueue(folio);
12265ef64cc8SLinus Torvalds 	int unfairness = sysctl_page_lock_unfairness;
122762906027SNicholas Piggin 	struct wait_page_queue wait_page;
1228ac6424b9SIngo Molnar 	wait_queue_entry_t *wait = &wait_page.wait;
1229b1d29ba8SJohannes Weiner 	bool thrashing = false;
1230eb414681SJohannes Weiner 	unsigned long pflags;
1231aa1cf99bSYang Yang 	bool in_thrashing;
123262906027SNicholas Piggin 
1233eb414681SJohannes Weiner 	if (bit_nr == PG_locked &&
1234101c0bf6SMatthew Wilcox (Oracle) 	    !folio_test_uptodate(folio) && folio_test_workingset(folio)) {
1235aa1cf99bSYang Yang 		delayacct_thrashing_start(&in_thrashing);
1236eb414681SJohannes Weiner 		psi_memstall_enter(&pflags);
1237b1d29ba8SJohannes Weiner 		thrashing = true;
1238b1d29ba8SJohannes Weiner 	}
1239b1d29ba8SJohannes Weiner 
124062906027SNicholas Piggin 	init_wait(wait);
124162906027SNicholas Piggin 	wait->func = wake_page_function;
1242df4d4f12SMatthew Wilcox (Oracle) 	wait_page.folio = folio;
124362906027SNicholas Piggin 	wait_page.bit_nr = bit_nr;
124462906027SNicholas Piggin 
12455ef64cc8SLinus Torvalds repeat:
12465ef64cc8SLinus Torvalds 	wait->flags = 0;
12475ef64cc8SLinus Torvalds 	if (behavior == EXCLUSIVE) {
12485ef64cc8SLinus Torvalds 		wait->flags = WQ_FLAG_EXCLUSIVE;
12495ef64cc8SLinus Torvalds 		if (--unfairness < 0)
12505ef64cc8SLinus Torvalds 			wait->flags |= WQ_FLAG_CUSTOM;
12515ef64cc8SLinus Torvalds 	}
12525ef64cc8SLinus Torvalds 
12532a9127fcSLinus Torvalds 	/*
12542a9127fcSLinus Torvalds 	 * Do one last check whether we can get the
12552a9127fcSLinus Torvalds 	 * page bit synchronously.
12562a9127fcSLinus Torvalds 	 *
1257101c0bf6SMatthew Wilcox (Oracle) 	 * Do the folio_set_waiters() marking before that
12582a9127fcSLinus Torvalds 	 * to let any waker we _just_ missed know they
12592a9127fcSLinus Torvalds 	 * need to wake us up (otherwise they'll never
12602a9127fcSLinus Torvalds 	 * even go to the slow case that looks at the
12612a9127fcSLinus Torvalds 	 * page queue), and add ourselves to the wait
12622a9127fcSLinus Torvalds 	 * queue if we need to sleep.
12632a9127fcSLinus Torvalds 	 *
12642a9127fcSLinus Torvalds 	 * This part needs to be done under the queue
12652a9127fcSLinus Torvalds 	 * lock to avoid races.
12662a9127fcSLinus Torvalds 	 */
126762906027SNicholas Piggin 	spin_lock_irq(&q->lock);
1268101c0bf6SMatthew Wilcox (Oracle) 	folio_set_waiters(folio);
1269101c0bf6SMatthew Wilcox (Oracle) 	if (!folio_trylock_flag(folio, bit_nr, wait))
12702a9127fcSLinus Torvalds 		__add_wait_queue_entry_tail(q, wait);
127162906027SNicholas Piggin 	spin_unlock_irq(&q->lock);
127262906027SNicholas Piggin 
12732a9127fcSLinus Torvalds 	/*
12742a9127fcSLinus Torvalds 	 * From now on, all the logic will be based on
12755ef64cc8SLinus Torvalds 	 * the WQ_FLAG_WOKEN and WQ_FLAG_DONE flag, to
12765ef64cc8SLinus Torvalds 	 * see whether the page bit testing has already
12775ef64cc8SLinus Torvalds 	 * been done by the wake function.
12782a9127fcSLinus Torvalds 	 *
1279101c0bf6SMatthew Wilcox (Oracle) 	 * We can drop our reference to the folio.
12802a9127fcSLinus Torvalds 	 */
12819a1ea439SHugh Dickins 	if (behavior == DROP)
1282101c0bf6SMatthew Wilcox (Oracle) 		folio_put(folio);
128362906027SNicholas Piggin 
12845ef64cc8SLinus Torvalds 	/*
12855ef64cc8SLinus Torvalds 	 * Note that until the "finish_wait()", or until
12865ef64cc8SLinus Torvalds 	 * we see the WQ_FLAG_WOKEN flag, we need to
12875ef64cc8SLinus Torvalds 	 * be very careful with the 'wait->flags', because
12885ef64cc8SLinus Torvalds 	 * we may race with a waker that sets them.
12895ef64cc8SLinus Torvalds 	 */
12902a9127fcSLinus Torvalds 	for (;;) {
12915ef64cc8SLinus Torvalds 		unsigned int flags;
12925ef64cc8SLinus Torvalds 
12932a9127fcSLinus Torvalds 		set_current_state(state);
12942a9127fcSLinus Torvalds 
12955ef64cc8SLinus Torvalds 		/* Loop until we've been woken or interrupted */
12965ef64cc8SLinus Torvalds 		flags = smp_load_acquire(&wait->flags);
12975ef64cc8SLinus Torvalds 		if (!(flags & WQ_FLAG_WOKEN)) {
12982a9127fcSLinus Torvalds 			if (signal_pending_state(state, current))
12992a9127fcSLinus Torvalds 				break;
13002a9127fcSLinus Torvalds 
13019a1ea439SHugh Dickins 			io_schedule();
13025ef64cc8SLinus Torvalds 			continue;
130362906027SNicholas Piggin 		}
130462906027SNicholas Piggin 
13055ef64cc8SLinus Torvalds 		/* If we were non-exclusive, we're done */
13065ef64cc8SLinus Torvalds 		if (behavior != EXCLUSIVE)
13075ef64cc8SLinus Torvalds 			break;
13085ef64cc8SLinus Torvalds 
13095ef64cc8SLinus Torvalds 		/* If the waker got the lock for us, we're done */
13105ef64cc8SLinus Torvalds 		if (flags & WQ_FLAG_DONE)
13115ef64cc8SLinus Torvalds 			break;
13125ef64cc8SLinus Torvalds 
13135ef64cc8SLinus Torvalds 		/*
13145ef64cc8SLinus Torvalds 		 * Otherwise, if we're getting the lock, we need to
13155ef64cc8SLinus Torvalds 		 * try to get it ourselves.
13165ef64cc8SLinus Torvalds 		 *
13175ef64cc8SLinus Torvalds 		 * And if that fails, we'll have to retry this all.
13185ef64cc8SLinus Torvalds 		 */
1319101c0bf6SMatthew Wilcox (Oracle) 		if (unlikely(test_and_set_bit(bit_nr, folio_flags(folio, 0))))
13205ef64cc8SLinus Torvalds 			goto repeat;
13215ef64cc8SLinus Torvalds 
13225ef64cc8SLinus Torvalds 		wait->flags |= WQ_FLAG_DONE;
13235ef64cc8SLinus Torvalds 		break;
13245ef64cc8SLinus Torvalds 	}
13255ef64cc8SLinus Torvalds 
13265ef64cc8SLinus Torvalds 	/*
13275ef64cc8SLinus Torvalds 	 * If a signal happened, this 'finish_wait()' may remove the last
1328101c0bf6SMatthew Wilcox (Oracle) 	 * waiter from the wait-queues, but the folio waiters bit will remain
13295ef64cc8SLinus Torvalds 	 * set. That's ok. The next wakeup will take care of it, and trying
13305ef64cc8SLinus Torvalds 	 * to do it here would be difficult and prone to races.
13315ef64cc8SLinus Torvalds 	 */
133262906027SNicholas Piggin 	finish_wait(q, wait);
133362906027SNicholas Piggin 
1334eb414681SJohannes Weiner 	if (thrashing) {
1335aa1cf99bSYang Yang 		delayacct_thrashing_end(&in_thrashing);
1336eb414681SJohannes Weiner 		psi_memstall_leave(&pflags);
1337eb414681SJohannes Weiner 	}
1338b1d29ba8SJohannes Weiner 
133962906027SNicholas Piggin 	/*
13405ef64cc8SLinus Torvalds 	 * NOTE! The wait->flags weren't stable until we've done the
13415ef64cc8SLinus Torvalds 	 * 'finish_wait()', and we could have exited the loop above due
13425ef64cc8SLinus Torvalds 	 * to a signal, and had a wakeup event happen after the signal
13435ef64cc8SLinus Torvalds 	 * test but before the 'finish_wait()'.
13445ef64cc8SLinus Torvalds 	 *
13455ef64cc8SLinus Torvalds 	 * So only after the finish_wait() can we reliably determine
13465ef64cc8SLinus Torvalds 	 * if we got woken up or not, so we can now figure out the final
13475ef64cc8SLinus Torvalds 	 * return value based on that state without races.
13485ef64cc8SLinus Torvalds 	 *
13495ef64cc8SLinus Torvalds 	 * Also note that WQ_FLAG_WOKEN is sufficient for a non-exclusive
13505ef64cc8SLinus Torvalds 	 * waiter, but an exclusive one requires WQ_FLAG_DONE.
135162906027SNicholas Piggin 	 */
13525ef64cc8SLinus Torvalds 	if (behavior == EXCLUSIVE)
13535ef64cc8SLinus Torvalds 		return wait->flags & WQ_FLAG_DONE ? 0 : -EINTR;
135462906027SNicholas Piggin 
13552a9127fcSLinus Torvalds 	return wait->flags & WQ_FLAG_WOKEN ? 0 : -EINTR;
135662906027SNicholas Piggin }
13571da177e4SLinus Torvalds 
1358ffa65753SAlistair Popple #ifdef CONFIG_MIGRATION
1359ffa65753SAlistair Popple /**
1360ffa65753SAlistair Popple  * migration_entry_wait_on_locked - Wait for a migration entry to be removed
1361ffa65753SAlistair Popple  * @entry: migration swap entry.
1362ffa65753SAlistair Popple  * @ptl: already locked ptl. This function will drop the lock.
1363ffa65753SAlistair Popple  *
1364ffa65753SAlistair Popple  * Wait for a migration entry referencing the given page to be removed. This is
1365ffa65753SAlistair Popple  * equivalent to put_and_wait_on_page_locked(page, TASK_UNINTERRUPTIBLE) except
1366ffa65753SAlistair Popple  * this can be called without taking a reference on the page. Instead this
1367ffa65753SAlistair Popple  * should be called while holding the ptl for the migration entry referencing
1368ffa65753SAlistair Popple  * the page.
1369ffa65753SAlistair Popple  *
13700cb8fd4dSHugh Dickins  * Returns after unlocking the ptl.
1371ffa65753SAlistair Popple  *
1372ffa65753SAlistair Popple  * This follows the same logic as folio_wait_bit_common() so see the comments
1373ffa65753SAlistair Popple  * there.
1374ffa65753SAlistair Popple  */
migration_entry_wait_on_locked(swp_entry_t entry,spinlock_t * ptl)13750cb8fd4dSHugh Dickins void migration_entry_wait_on_locked(swp_entry_t entry, spinlock_t *ptl)
13760cb8fd4dSHugh Dickins 	__releases(ptl)
1377ffa65753SAlistair Popple {
1378ffa65753SAlistair Popple 	struct wait_page_queue wait_page;
1379ffa65753SAlistair Popple 	wait_queue_entry_t *wait = &wait_page.wait;
1380ffa65753SAlistair Popple 	bool thrashing = false;
1381ffa65753SAlistair Popple 	unsigned long pflags;
1382aa1cf99bSYang Yang 	bool in_thrashing;
1383ffa65753SAlistair Popple 	wait_queue_head_t *q;
1384ffa65753SAlistair Popple 	struct folio *folio = page_folio(pfn_swap_entry_to_page(entry));
1385ffa65753SAlistair Popple 
1386ffa65753SAlistair Popple 	q = folio_waitqueue(folio);
1387ffa65753SAlistair Popple 	if (!folio_test_uptodate(folio) && folio_test_workingset(folio)) {
1388aa1cf99bSYang Yang 		delayacct_thrashing_start(&in_thrashing);
1389ffa65753SAlistair Popple 		psi_memstall_enter(&pflags);
1390ffa65753SAlistair Popple 		thrashing = true;
1391ffa65753SAlistair Popple 	}
1392ffa65753SAlistair Popple 
1393ffa65753SAlistair Popple 	init_wait(wait);
1394ffa65753SAlistair Popple 	wait->func = wake_page_function;
1395ffa65753SAlistair Popple 	wait_page.folio = folio;
1396ffa65753SAlistair Popple 	wait_page.bit_nr = PG_locked;
1397ffa65753SAlistair Popple 	wait->flags = 0;
1398ffa65753SAlistair Popple 
1399ffa65753SAlistair Popple 	spin_lock_irq(&q->lock);
1400ffa65753SAlistair Popple 	folio_set_waiters(folio);
1401ffa65753SAlistair Popple 	if (!folio_trylock_flag(folio, PG_locked, wait))
1402ffa65753SAlistair Popple 		__add_wait_queue_entry_tail(q, wait);
1403ffa65753SAlistair Popple 	spin_unlock_irq(&q->lock);
1404ffa65753SAlistair Popple 
1405ffa65753SAlistair Popple 	/*
1406ffa65753SAlistair Popple 	 * If a migration entry exists for the page the migration path must hold
1407ffa65753SAlistair Popple 	 * a valid reference to the page, and it must take the ptl to remove the
1408ffa65753SAlistair Popple 	 * migration entry. So the page is valid until the ptl is dropped.
1409ffa65753SAlistair Popple 	 */
1410ffa65753SAlistair Popple 	spin_unlock(ptl);
1411ffa65753SAlistair Popple 
1412ffa65753SAlistair Popple 	for (;;) {
1413ffa65753SAlistair Popple 		unsigned int flags;
1414ffa65753SAlistair Popple 
1415ffa65753SAlistair Popple 		set_current_state(TASK_UNINTERRUPTIBLE);
1416ffa65753SAlistair Popple 
1417ffa65753SAlistair Popple 		/* Loop until we've been woken or interrupted */
1418ffa65753SAlistair Popple 		flags = smp_load_acquire(&wait->flags);
1419ffa65753SAlistair Popple 		if (!(flags & WQ_FLAG_WOKEN)) {
1420ffa65753SAlistair Popple 			if (signal_pending_state(TASK_UNINTERRUPTIBLE, current))
1421ffa65753SAlistair Popple 				break;
1422ffa65753SAlistair Popple 
1423ffa65753SAlistair Popple 			io_schedule();
1424ffa65753SAlistair Popple 			continue;
1425ffa65753SAlistair Popple 		}
1426ffa65753SAlistair Popple 		break;
1427ffa65753SAlistair Popple 	}
1428ffa65753SAlistair Popple 
1429ffa65753SAlistair Popple 	finish_wait(q, wait);
1430ffa65753SAlistair Popple 
1431ffa65753SAlistair Popple 	if (thrashing) {
1432aa1cf99bSYang Yang 		delayacct_thrashing_end(&in_thrashing);
1433ffa65753SAlistair Popple 		psi_memstall_leave(&pflags);
1434ffa65753SAlistair Popple 	}
1435ffa65753SAlistair Popple }
1436ffa65753SAlistair Popple #endif
1437ffa65753SAlistair Popple 
folio_wait_bit(struct folio * folio,int bit_nr)1438101c0bf6SMatthew Wilcox (Oracle) void folio_wait_bit(struct folio *folio, int bit_nr)
14391da177e4SLinus Torvalds {
1440101c0bf6SMatthew Wilcox (Oracle) 	folio_wait_bit_common(folio, bit_nr, TASK_UNINTERRUPTIBLE, SHARED);
14411da177e4SLinus Torvalds }
1442101c0bf6SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_wait_bit);
14431da177e4SLinus Torvalds 
folio_wait_bit_killable(struct folio * folio,int bit_nr)1444101c0bf6SMatthew Wilcox (Oracle) int folio_wait_bit_killable(struct folio *folio, int bit_nr)
1445f62e00ccSKOSAKI Motohiro {
1446101c0bf6SMatthew Wilcox (Oracle) 	return folio_wait_bit_common(folio, bit_nr, TASK_KILLABLE, SHARED);
1447f62e00ccSKOSAKI Motohiro }
1448101c0bf6SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_wait_bit_killable);
1449f62e00ccSKOSAKI Motohiro 
14501da177e4SLinus Torvalds /**
14519f2b04a2SMatthew Wilcox (Oracle)  * folio_put_wait_locked - Drop a reference and wait for it to be unlocked
14529f2b04a2SMatthew Wilcox (Oracle)  * @folio: The folio to wait for.
145348054625SMatthew Wilcox (Oracle)  * @state: The sleep state (TASK_KILLABLE, TASK_UNINTERRUPTIBLE, etc).
14549a1ea439SHugh Dickins  *
14559f2b04a2SMatthew Wilcox (Oracle)  * The caller should hold a reference on @folio.  They expect the page to
14569a1ea439SHugh Dickins  * become unlocked relatively soon, but do not wish to hold up migration
14579f2b04a2SMatthew Wilcox (Oracle)  * (for example) by holding the reference while waiting for the folio to
14589a1ea439SHugh Dickins  * come unlocked.  After this function returns, the caller should not
14599f2b04a2SMatthew Wilcox (Oracle)  * dereference @folio.
146048054625SMatthew Wilcox (Oracle)  *
14619f2b04a2SMatthew Wilcox (Oracle)  * Return: 0 if the folio was unlocked or -EINTR if interrupted by a signal.
14629a1ea439SHugh Dickins  */
folio_put_wait_locked(struct folio * folio,int state)1463c195c321SKe Sun static int folio_put_wait_locked(struct folio *folio, int state)
14649a1ea439SHugh Dickins {
14659f2b04a2SMatthew Wilcox (Oracle) 	return folio_wait_bit_common(folio, PG_locked, state, DROP);
14669a1ea439SHugh Dickins }
14679a1ea439SHugh Dickins 
14689a1ea439SHugh Dickins /**
1469df4d4f12SMatthew Wilcox (Oracle)  * folio_add_wait_queue - Add an arbitrary waiter to a folio's wait queue
1470df4d4f12SMatthew Wilcox (Oracle)  * @folio: Folio defining the wait queue of interest
1471697f619fSRandy Dunlap  * @waiter: Waiter to add to the queue
1472385e1ca5SDavid Howells  *
1473df4d4f12SMatthew Wilcox (Oracle)  * Add an arbitrary @waiter to the wait queue for the nominated @folio.
1474385e1ca5SDavid Howells  */
folio_add_wait_queue(struct folio * folio,wait_queue_entry_t * waiter)1475df4d4f12SMatthew Wilcox (Oracle) void folio_add_wait_queue(struct folio *folio, wait_queue_entry_t *waiter)
1476385e1ca5SDavid Howells {
1477df4d4f12SMatthew Wilcox (Oracle) 	wait_queue_head_t *q = folio_waitqueue(folio);
1478385e1ca5SDavid Howells 	unsigned long flags;
1479385e1ca5SDavid Howells 
1480385e1ca5SDavid Howells 	spin_lock_irqsave(&q->lock, flags);
14819c3a815fSLinus Torvalds 	__add_wait_queue_entry_tail(q, waiter);
1482df4d4f12SMatthew Wilcox (Oracle) 	folio_set_waiters(folio);
1483385e1ca5SDavid Howells 	spin_unlock_irqrestore(&q->lock, flags);
1484385e1ca5SDavid Howells }
1485df4d4f12SMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(folio_add_wait_queue);
1486385e1ca5SDavid Howells 
1487b91e1302SLinus Torvalds #ifndef clear_bit_unlock_is_negative_byte
1488b91e1302SLinus Torvalds 
1489b91e1302SLinus Torvalds /*
1490b91e1302SLinus Torvalds  * PG_waiters is the high bit in the same byte as PG_lock.
1491b91e1302SLinus Torvalds  *
1492b91e1302SLinus Torvalds  * On x86 (and on many other architectures), we can clear PG_lock and
1493b91e1302SLinus Torvalds  * test the sign bit at the same time. But if the architecture does
1494b91e1302SLinus Torvalds  * not support that special operation, we just do this all by hand
1495b91e1302SLinus Torvalds  * instead.
1496b91e1302SLinus Torvalds  *
1497b91e1302SLinus Torvalds  * The read of PG_waiters has to be after (or concurrently with) PG_locked
1498ffceeb62SEthon Paul  * being cleared, but a memory barrier should be unnecessary since it is
1499b91e1302SLinus Torvalds  * in the same byte as PG_locked.
1500b91e1302SLinus Torvalds  */
clear_bit_unlock_is_negative_byte(long nr,volatile void * mem)1501b91e1302SLinus Torvalds static inline bool clear_bit_unlock_is_negative_byte(long nr, volatile void *mem)
1502b91e1302SLinus Torvalds {
1503b91e1302SLinus Torvalds 	clear_bit_unlock(nr, mem);
1504b91e1302SLinus Torvalds 	/* smp_mb__after_atomic(); */
150598473f9fSOlof Johansson 	return test_bit(PG_waiters, mem);
1506b91e1302SLinus Torvalds }
1507b91e1302SLinus Torvalds 
1508b91e1302SLinus Torvalds #endif
1509b91e1302SLinus Torvalds 
1510385e1ca5SDavid Howells /**
15114e136428SMatthew Wilcox (Oracle)  * folio_unlock - Unlock a locked folio.
15124e136428SMatthew Wilcox (Oracle)  * @folio: The folio.
15131da177e4SLinus Torvalds  *
15144e136428SMatthew Wilcox (Oracle)  * Unlocks the folio and wakes up any thread sleeping on the page lock.
15151da177e4SLinus Torvalds  *
15164e136428SMatthew Wilcox (Oracle)  * Context: May be called from interrupt or process context.  May not be
15174e136428SMatthew Wilcox (Oracle)  * called from NMI context.
15181da177e4SLinus Torvalds  */
folio_unlock(struct folio * folio)15194e136428SMatthew Wilcox (Oracle) void folio_unlock(struct folio *folio)
15201da177e4SLinus Torvalds {
15214e136428SMatthew Wilcox (Oracle) 	/* Bit 7 allows x86 to check the byte's sign bit */
1522b91e1302SLinus Torvalds 	BUILD_BUG_ON(PG_waiters != 7);
15234e136428SMatthew Wilcox (Oracle) 	BUILD_BUG_ON(PG_locked > 7);
15244e136428SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
15254e136428SMatthew Wilcox (Oracle) 	if (clear_bit_unlock_is_negative_byte(PG_locked, folio_flags(folio, 0)))
15266974d7c9SMatthew Wilcox (Oracle) 		folio_wake_bit(folio, PG_locked);
15271da177e4SLinus Torvalds }
15284e136428SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_unlock);
15291da177e4SLinus Torvalds 
1530485bb99bSRandy Dunlap /**
1531b47393f8SMatthew Wilcox (Oracle)  * folio_end_private_2 - Clear PG_private_2 and wake any waiters.
1532b47393f8SMatthew Wilcox (Oracle)  * @folio: The folio.
153373e10dedSDavid Howells  *
1534b47393f8SMatthew Wilcox (Oracle)  * Clear the PG_private_2 bit on a folio and wake up any sleepers waiting for
1535b47393f8SMatthew Wilcox (Oracle)  * it.  The folio reference held for PG_private_2 being set is released.
153673e10dedSDavid Howells  *
1537b47393f8SMatthew Wilcox (Oracle)  * This is, for example, used when a netfs folio is being written to a local
1538b47393f8SMatthew Wilcox (Oracle)  * disk cache, thereby allowing writes to the cache for the same folio to be
153973e10dedSDavid Howells  * serialised.
154073e10dedSDavid Howells  */
folio_end_private_2(struct folio * folio)1541b47393f8SMatthew Wilcox (Oracle) void folio_end_private_2(struct folio *folio)
154273e10dedSDavid Howells {
15436974d7c9SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_private_2(folio), folio);
15446974d7c9SMatthew Wilcox (Oracle) 	clear_bit_unlock(PG_private_2, folio_flags(folio, 0));
15456974d7c9SMatthew Wilcox (Oracle) 	folio_wake_bit(folio, PG_private_2);
15466974d7c9SMatthew Wilcox (Oracle) 	folio_put(folio);
154773e10dedSDavid Howells }
1548b47393f8SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_end_private_2);
154973e10dedSDavid Howells 
155073e10dedSDavid Howells /**
1551b47393f8SMatthew Wilcox (Oracle)  * folio_wait_private_2 - Wait for PG_private_2 to be cleared on a folio.
1552b47393f8SMatthew Wilcox (Oracle)  * @folio: The folio to wait on.
155373e10dedSDavid Howells  *
1554b47393f8SMatthew Wilcox (Oracle)  * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio.
155573e10dedSDavid Howells  */
folio_wait_private_2(struct folio * folio)1556b47393f8SMatthew Wilcox (Oracle) void folio_wait_private_2(struct folio *folio)
155773e10dedSDavid Howells {
1558101c0bf6SMatthew Wilcox (Oracle) 	while (folio_test_private_2(folio))
1559101c0bf6SMatthew Wilcox (Oracle) 		folio_wait_bit(folio, PG_private_2);
156073e10dedSDavid Howells }
1561b47393f8SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_wait_private_2);
156273e10dedSDavid Howells 
156373e10dedSDavid Howells /**
1564b47393f8SMatthew Wilcox (Oracle)  * folio_wait_private_2_killable - Wait for PG_private_2 to be cleared on a folio.
1565b47393f8SMatthew Wilcox (Oracle)  * @folio: The folio to wait on.
156673e10dedSDavid Howells  *
1567b47393f8SMatthew Wilcox (Oracle)  * Wait for PG_private_2 (aka PG_fscache) to be cleared on a folio or until a
156873e10dedSDavid Howells  * fatal signal is received by the calling task.
156973e10dedSDavid Howells  *
157073e10dedSDavid Howells  * Return:
157173e10dedSDavid Howells  * - 0 if successful.
157273e10dedSDavid Howells  * - -EINTR if a fatal signal was encountered.
157373e10dedSDavid Howells  */
folio_wait_private_2_killable(struct folio * folio)1574b47393f8SMatthew Wilcox (Oracle) int folio_wait_private_2_killable(struct folio *folio)
157573e10dedSDavid Howells {
157673e10dedSDavid Howells 	int ret = 0;
157773e10dedSDavid Howells 
1578101c0bf6SMatthew Wilcox (Oracle) 	while (folio_test_private_2(folio)) {
1579101c0bf6SMatthew Wilcox (Oracle) 		ret = folio_wait_bit_killable(folio, PG_private_2);
158073e10dedSDavid Howells 		if (ret < 0)
158173e10dedSDavid Howells 			break;
158273e10dedSDavid Howells 	}
158373e10dedSDavid Howells 
158473e10dedSDavid Howells 	return ret;
158573e10dedSDavid Howells }
1586b47393f8SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_wait_private_2_killable);
158773e10dedSDavid Howells 
158873e10dedSDavid Howells /**
15894268b480SMatthew Wilcox (Oracle)  * folio_end_writeback - End writeback against a folio.
15904268b480SMatthew Wilcox (Oracle)  * @folio: The folio.
15911da177e4SLinus Torvalds  */
folio_end_writeback(struct folio * folio)15924268b480SMatthew Wilcox (Oracle) void folio_end_writeback(struct folio *folio)
15931da177e4SLinus Torvalds {
1594888cf2dbSMel Gorman 	/*
15954268b480SMatthew Wilcox (Oracle) 	 * folio_test_clear_reclaim() could be used here but it is an
15964268b480SMatthew Wilcox (Oracle) 	 * atomic operation and overkill in this particular case. Failing
15974268b480SMatthew Wilcox (Oracle) 	 * to shuffle a folio marked for immediate reclaim is too mild
15984268b480SMatthew Wilcox (Oracle) 	 * a gain to justify taking an atomic operation penalty at the
15994268b480SMatthew Wilcox (Oracle) 	 * end of every folio writeback.
1600888cf2dbSMel Gorman 	 */
16014268b480SMatthew Wilcox (Oracle) 	if (folio_test_reclaim(folio)) {
16024268b480SMatthew Wilcox (Oracle) 		folio_clear_reclaim(folio);
1603575ced1cSMatthew Wilcox (Oracle) 		folio_rotate_reclaimable(folio);
1604888cf2dbSMel Gorman 	}
1605ac6aadb2SMiklos Szeredi 
1606073861edSHugh Dickins 	/*
16074268b480SMatthew Wilcox (Oracle) 	 * Writeback does not hold a folio reference of its own, relying
1608073861edSHugh Dickins 	 * on truncation to wait for the clearing of PG_writeback.
16094268b480SMatthew Wilcox (Oracle) 	 * But here we must make sure that the folio is not freed and
16104268b480SMatthew Wilcox (Oracle) 	 * reused before the folio_wake().
1611073861edSHugh Dickins 	 */
16124268b480SMatthew Wilcox (Oracle) 	folio_get(folio);
1613269ccca3SMatthew Wilcox (Oracle) 	if (!__folio_end_writeback(folio))
16141da177e4SLinus Torvalds 		BUG();
1615ac6aadb2SMiklos Szeredi 
16164e857c58SPeter Zijlstra 	smp_mb__after_atomic();
16174268b480SMatthew Wilcox (Oracle) 	folio_wake(folio, PG_writeback);
1618512b7931SLinus Torvalds 	acct_reclaim_writeback(folio);
16194268b480SMatthew Wilcox (Oracle) 	folio_put(folio);
16201da177e4SLinus Torvalds }
16214268b480SMatthew Wilcox (Oracle) EXPORT_SYMBOL(folio_end_writeback);
16221da177e4SLinus Torvalds 
1623485bb99bSRandy Dunlap /**
16247c23c782SMatthew Wilcox (Oracle)  * __folio_lock - Get a lock on the folio, assuming we need to sleep to get it.
16257c23c782SMatthew Wilcox (Oracle)  * @folio: The folio to lock
16261da177e4SLinus Torvalds  */
__folio_lock(struct folio * folio)16277c23c782SMatthew Wilcox (Oracle) void __folio_lock(struct folio *folio)
16281da177e4SLinus Torvalds {
1629101c0bf6SMatthew Wilcox (Oracle) 	folio_wait_bit_common(folio, PG_locked, TASK_UNINTERRUPTIBLE,
16309a1ea439SHugh Dickins 				EXCLUSIVE);
16311da177e4SLinus Torvalds }
16327c23c782SMatthew Wilcox (Oracle) EXPORT_SYMBOL(__folio_lock);
16331da177e4SLinus Torvalds 
__folio_lock_killable(struct folio * folio)1634af7f29d9SMatthew Wilcox (Oracle) int __folio_lock_killable(struct folio *folio)
16352687a356SMatthew Wilcox {
1636101c0bf6SMatthew Wilcox (Oracle) 	return folio_wait_bit_common(folio, PG_locked, TASK_KILLABLE,
16379a1ea439SHugh Dickins 					EXCLUSIVE);
16382687a356SMatthew Wilcox }
1639af7f29d9SMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(__folio_lock_killable);
16402687a356SMatthew Wilcox 
__folio_lock_async(struct folio * folio,struct wait_page_queue * wait)1641ffdc8dabSMatthew Wilcox (Oracle) static int __folio_lock_async(struct folio *folio, struct wait_page_queue *wait)
1642dd3e6d50SJens Axboe {
1643df4d4f12SMatthew Wilcox (Oracle) 	struct wait_queue_head *q = folio_waitqueue(folio);
1644f32b5dd7SMatthew Wilcox (Oracle) 	int ret = 0;
1645f32b5dd7SMatthew Wilcox (Oracle) 
1646df4d4f12SMatthew Wilcox (Oracle) 	wait->folio = folio;
1647f32b5dd7SMatthew Wilcox (Oracle) 	wait->bit_nr = PG_locked;
1648f32b5dd7SMatthew Wilcox (Oracle) 
1649f32b5dd7SMatthew Wilcox (Oracle) 	spin_lock_irq(&q->lock);
1650f32b5dd7SMatthew Wilcox (Oracle) 	__add_wait_queue_entry_tail(q, &wait->wait);
1651ffdc8dabSMatthew Wilcox (Oracle) 	folio_set_waiters(folio);
1652ffdc8dabSMatthew Wilcox (Oracle) 	ret = !folio_trylock(folio);
1653f32b5dd7SMatthew Wilcox (Oracle) 	/*
1654f32b5dd7SMatthew Wilcox (Oracle) 	 * If we were successful now, we know we're still on the
1655f32b5dd7SMatthew Wilcox (Oracle) 	 * waitqueue as we're still under the lock. This means it's
1656f32b5dd7SMatthew Wilcox (Oracle) 	 * safe to remove and return success, we know the callback
1657f32b5dd7SMatthew Wilcox (Oracle) 	 * isn't going to trigger.
1658f32b5dd7SMatthew Wilcox (Oracle) 	 */
1659f32b5dd7SMatthew Wilcox (Oracle) 	if (!ret)
1660f32b5dd7SMatthew Wilcox (Oracle) 		__remove_wait_queue(q, &wait->wait);
1661f32b5dd7SMatthew Wilcox (Oracle) 	else
1662f32b5dd7SMatthew Wilcox (Oracle) 		ret = -EIOCBQUEUED;
1663f32b5dd7SMatthew Wilcox (Oracle) 	spin_unlock_irq(&q->lock);
1664f32b5dd7SMatthew Wilcox (Oracle) 	return ret;
1665dd3e6d50SJens Axboe }
1666dd3e6d50SJens Axboe 
16679a95f3cfSPaul Cassella /*
16689a95f3cfSPaul Cassella  * Return values:
1669fdc724d6SSuren Baghdasaryan  * 0 - folio is locked.
1670fdc724d6SSuren Baghdasaryan  * non-zero - folio is not locked.
16711235ccd0SSuren Baghdasaryan  *     mmap_lock or per-VMA lock has been released (mmap_read_unlock() or
16721235ccd0SSuren Baghdasaryan  *     vma_end_read()), unless flags had both FAULT_FLAG_ALLOW_RETRY and
16731235ccd0SSuren Baghdasaryan  *     FAULT_FLAG_RETRY_NOWAIT set, in which case the lock is still held.
16749a95f3cfSPaul Cassella  *
1675fdc724d6SSuren Baghdasaryan  * If neither ALLOW_RETRY nor KILLABLE are set, will always return 0
16761235ccd0SSuren Baghdasaryan  * with the folio locked and the mmap_lock/per-VMA lock is left unperturbed.
16779a95f3cfSPaul Cassella  */
__folio_lock_or_retry(struct folio * folio,struct vm_fault * vmf)1678fdc724d6SSuren Baghdasaryan vm_fault_t __folio_lock_or_retry(struct folio *folio, struct vm_fault *vmf)
1679d065bd81SMichel Lespinasse {
1680fdc724d6SSuren Baghdasaryan 	unsigned int flags = vmf->flags;
1681fdc724d6SSuren Baghdasaryan 
16824064b982SPeter Xu 	if (fault_flag_allow_retry_first(flags)) {
168337b23e05SKOSAKI Motohiro 		/*
16841235ccd0SSuren Baghdasaryan 		 * CAUTION! In this case, mmap_lock/per-VMA lock is not
16851235ccd0SSuren Baghdasaryan 		 * released even though returning VM_FAULT_RETRY.
168637b23e05SKOSAKI Motohiro 		 */
168737b23e05SKOSAKI Motohiro 		if (flags & FAULT_FLAG_RETRY_NOWAIT)
1688fdc724d6SSuren Baghdasaryan 			return VM_FAULT_RETRY;
168937b23e05SKOSAKI Motohiro 
16901235ccd0SSuren Baghdasaryan 		release_fault_lock(vmf);
169137b23e05SKOSAKI Motohiro 		if (flags & FAULT_FLAG_KILLABLE)
16926baa8d60SMatthew Wilcox (Oracle) 			folio_wait_locked_killable(folio);
169337b23e05SKOSAKI Motohiro 		else
16946baa8d60SMatthew Wilcox (Oracle) 			folio_wait_locked(folio);
1695fdc724d6SSuren Baghdasaryan 		return VM_FAULT_RETRY;
1696800bca7cSHailong Liu 	}
169737b23e05SKOSAKI Motohiro 	if (flags & FAULT_FLAG_KILLABLE) {
16989138e47eSMatthew Wilcox (Oracle) 		bool ret;
169937b23e05SKOSAKI Motohiro 
1700af7f29d9SMatthew Wilcox (Oracle) 		ret = __folio_lock_killable(folio);
170137b23e05SKOSAKI Motohiro 		if (ret) {
17021235ccd0SSuren Baghdasaryan 			release_fault_lock(vmf);
1703fdc724d6SSuren Baghdasaryan 			return VM_FAULT_RETRY;
170437b23e05SKOSAKI Motohiro 		}
1705800bca7cSHailong Liu 	} else {
1706af7f29d9SMatthew Wilcox (Oracle) 		__folio_lock(folio);
1707d065bd81SMichel Lespinasse 	}
1708800bca7cSHailong Liu 
1709fdc724d6SSuren Baghdasaryan 	return 0;
1710d065bd81SMichel Lespinasse }
1711d065bd81SMichel Lespinasse 
1712485bb99bSRandy Dunlap /**
17130d3f9296SMatthew Wilcox  * page_cache_next_miss() - Find the next gap in the page cache.
17140d3f9296SMatthew Wilcox  * @mapping: Mapping.
17150d3f9296SMatthew Wilcox  * @index: Index.
17160d3f9296SMatthew Wilcox  * @max_scan: Maximum range to search.
1717e7b563bbSJohannes Weiner  *
17180d3f9296SMatthew Wilcox  * Search the range [index, min(index + max_scan - 1, ULONG_MAX)] for the
17190d3f9296SMatthew Wilcox  * gap with the lowest index.
1720e7b563bbSJohannes Weiner  *
17210d3f9296SMatthew Wilcox  * This function may be called under the rcu_read_lock.  However, this will
17220d3f9296SMatthew Wilcox  * not atomically search a snapshot of the cache at a single point in time.
17230d3f9296SMatthew Wilcox  * For example, if a gap is created at index 5, then subsequently a gap is
17240d3f9296SMatthew Wilcox  * created at index 10, page_cache_next_miss covering both indices may
17250d3f9296SMatthew Wilcox  * return 10 if called under the rcu_read_lock.
1726e7b563bbSJohannes Weiner  *
17270d3f9296SMatthew Wilcox  * Return: The index of the gap if found, otherwise an index outside the
17280d3f9296SMatthew Wilcox  * range specified (in which case 'return - index >= max_scan' will be true).
172916f8eb3eSMike Kravetz  * In the rare case of index wrap-around, 0 will be returned.
1730e7b563bbSJohannes Weiner  */
page_cache_next_miss(struct address_space * mapping,pgoff_t index,unsigned long max_scan)17310d3f9296SMatthew Wilcox pgoff_t page_cache_next_miss(struct address_space *mapping,
1732e7b563bbSJohannes Weiner 			     pgoff_t index, unsigned long max_scan)
1733e7b563bbSJohannes Weiner {
17340d3f9296SMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, index);
1735e7b563bbSJohannes Weiner 
17360d3f9296SMatthew Wilcox 	while (max_scan--) {
17370d3f9296SMatthew Wilcox 		void *entry = xas_next(&xas);
17380d3f9296SMatthew Wilcox 		if (!entry || xa_is_value(entry))
173916f8eb3eSMike Kravetz 			break;
174016f8eb3eSMike Kravetz 		if (xas.xa_index == 0)
174116f8eb3eSMike Kravetz 			break;
1742e7b563bbSJohannes Weiner 	}
1743e7b563bbSJohannes Weiner 
174416f8eb3eSMike Kravetz 	return xas.xa_index;
1745e7b563bbSJohannes Weiner }
17460d3f9296SMatthew Wilcox EXPORT_SYMBOL(page_cache_next_miss);
1747e7b563bbSJohannes Weiner 
1748e7b563bbSJohannes Weiner /**
17492346a560SLaurent Dufour  * page_cache_prev_miss() - Find the previous gap in the page cache.
17500d3f9296SMatthew Wilcox  * @mapping: Mapping.
17510d3f9296SMatthew Wilcox  * @index: Index.
17520d3f9296SMatthew Wilcox  * @max_scan: Maximum range to search.
1753e7b563bbSJohannes Weiner  *
17540d3f9296SMatthew Wilcox  * Search the range [max(index - max_scan + 1, 0), index] for the
17550d3f9296SMatthew Wilcox  * gap with the highest index.
1756e7b563bbSJohannes Weiner  *
17570d3f9296SMatthew Wilcox  * This function may be called under the rcu_read_lock.  However, this will
17580d3f9296SMatthew Wilcox  * not atomically search a snapshot of the cache at a single point in time.
17590d3f9296SMatthew Wilcox  * For example, if a gap is created at index 10, then subsequently a gap is
17600d3f9296SMatthew Wilcox  * created at index 5, page_cache_prev_miss() covering both indices may
17610d3f9296SMatthew Wilcox  * return 5 if called under the rcu_read_lock.
1762e7b563bbSJohannes Weiner  *
17630d3f9296SMatthew Wilcox  * Return: The index of the gap if found, otherwise an index outside the
17640d3f9296SMatthew Wilcox  * range specified (in which case 'index - return >= max_scan' will be true).
176516f8eb3eSMike Kravetz  * In the rare case of wrap-around, ULONG_MAX will be returned.
1766e7b563bbSJohannes Weiner  */
page_cache_prev_miss(struct address_space * mapping,pgoff_t index,unsigned long max_scan)17670d3f9296SMatthew Wilcox pgoff_t page_cache_prev_miss(struct address_space *mapping,
1768e7b563bbSJohannes Weiner 			     pgoff_t index, unsigned long max_scan)
1769e7b563bbSJohannes Weiner {
17700d3f9296SMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, index);
1771e7b563bbSJohannes Weiner 
17720d3f9296SMatthew Wilcox 	while (max_scan--) {
17730d3f9296SMatthew Wilcox 		void *entry = xas_prev(&xas);
17740d3f9296SMatthew Wilcox 		if (!entry || xa_is_value(entry))
177516f8eb3eSMike Kravetz 			break;
177616f8eb3eSMike Kravetz 		if (xas.xa_index == ULONG_MAX)
177716f8eb3eSMike Kravetz 			break;
1778e7b563bbSJohannes Weiner 	}
1779e7b563bbSJohannes Weiner 
178016f8eb3eSMike Kravetz 	return xas.xa_index;
1781e7b563bbSJohannes Weiner }
17820d3f9296SMatthew Wilcox EXPORT_SYMBOL(page_cache_prev_miss);
1783e7b563bbSJohannes Weiner 
178444835d20SMatthew Wilcox (Oracle) /*
1785020853b6SMatthew Wilcox (Oracle)  * Lockless page cache protocol:
1786020853b6SMatthew Wilcox (Oracle)  * On the lookup side:
1787020853b6SMatthew Wilcox (Oracle)  * 1. Load the folio from i_pages
1788020853b6SMatthew Wilcox (Oracle)  * 2. Increment the refcount if it's not zero
1789020853b6SMatthew Wilcox (Oracle)  * 3. If the folio is not found by xas_reload(), put the refcount and retry
1790020853b6SMatthew Wilcox (Oracle)  *
1791020853b6SMatthew Wilcox (Oracle)  * On the removal side:
1792020853b6SMatthew Wilcox (Oracle)  * A. Freeze the page (by zeroing the refcount if nobody else has a reference)
1793020853b6SMatthew Wilcox (Oracle)  * B. Remove the page from i_pages
1794020853b6SMatthew Wilcox (Oracle)  * C. Return the page to the page allocator
1795020853b6SMatthew Wilcox (Oracle)  *
1796020853b6SMatthew Wilcox (Oracle)  * This means that any page may have its reference count temporarily
1797020853b6SMatthew Wilcox (Oracle)  * increased by a speculative page cache (or fast GUP) lookup as it can
1798020853b6SMatthew Wilcox (Oracle)  * be allocated by another user before the RCU grace period expires.
1799020853b6SMatthew Wilcox (Oracle)  * Because the refcount temporarily acquired here may end up being the
1800020853b6SMatthew Wilcox (Oracle)  * last refcount on the page, any page allocation must be freeable by
1801020853b6SMatthew Wilcox (Oracle)  * folio_put().
1802020853b6SMatthew Wilcox (Oracle)  */
1803020853b6SMatthew Wilcox (Oracle) 
1804020853b6SMatthew Wilcox (Oracle) /*
1805263e721eSChristoph Hellwig  * filemap_get_entry - Get a page cache entry.
1806485bb99bSRandy Dunlap  * @mapping: the address_space to search
1807a6de4b48SMatthew Wilcox (Oracle)  * @index: The page cache index.
1808485bb99bSRandy Dunlap  *
1809bca65eeaSMatthew Wilcox (Oracle)  * Looks up the page cache entry at @mapping & @index.  If it is a folio,
1810bca65eeaSMatthew Wilcox (Oracle)  * it is returned with an increased refcount.  If it is a shadow entry
1811bca65eeaSMatthew Wilcox (Oracle)  * of a previously evicted folio, or a swap entry from shmem/tmpfs,
1812bca65eeaSMatthew Wilcox (Oracle)  * it is returned without further action.
18130cd6144aSJohannes Weiner  *
1814bca65eeaSMatthew Wilcox (Oracle)  * Return: The folio, swap or shadow entry, %NULL if nothing is found.
18151da177e4SLinus Torvalds  */
filemap_get_entry(struct address_space * mapping,pgoff_t index)1816263e721eSChristoph Hellwig void *filemap_get_entry(struct address_space *mapping, pgoff_t index)
18171da177e4SLinus Torvalds {
1818a6de4b48SMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, index);
1819bca65eeaSMatthew Wilcox (Oracle) 	struct folio *folio;
18201da177e4SLinus Torvalds 
1821a60637c8SNick Piggin 	rcu_read_lock();
1822a60637c8SNick Piggin repeat:
18234c7472c0SMatthew Wilcox 	xas_reset(&xas);
1824bca65eeaSMatthew Wilcox (Oracle) 	folio = xas_load(&xas);
1825bca65eeaSMatthew Wilcox (Oracle) 	if (xas_retry(&xas, folio))
1826a60637c8SNick Piggin 		goto repeat;
18278079b1c8SHugh Dickins 	/*
18284c7472c0SMatthew Wilcox 	 * A shadow entry of a recently evicted page, or a swap entry from
18294c7472c0SMatthew Wilcox 	 * shmem/tmpfs.  Return it without attempting to raise page count.
18308079b1c8SHugh Dickins 	 */
1831bca65eeaSMatthew Wilcox (Oracle) 	if (!folio || xa_is_value(folio))
18328079b1c8SHugh Dickins 		goto out;
183383929372SKirill A. Shutemov 
1834bca65eeaSMatthew Wilcox (Oracle) 	if (!folio_try_get_rcu(folio))
1835a60637c8SNick Piggin 		goto repeat;
1836a60637c8SNick Piggin 
1837bca65eeaSMatthew Wilcox (Oracle) 	if (unlikely(folio != xas_reload(&xas))) {
1838bca65eeaSMatthew Wilcox (Oracle) 		folio_put(folio);
1839a60637c8SNick Piggin 		goto repeat;
1840a60637c8SNick Piggin 	}
184127d20fddSNick Piggin out:
1842a60637c8SNick Piggin 	rcu_read_unlock();
1843a60637c8SNick Piggin 
1844bca65eeaSMatthew Wilcox (Oracle) 	return folio;
18451da177e4SLinus Torvalds }
18461da177e4SLinus Torvalds 
1847485bb99bSRandy Dunlap /**
18483f0c6a07SMatthew Wilcox (Oracle)  * __filemap_get_folio - Find and get a reference to a folio.
18492294b32eSMatthew Wilcox (Oracle)  * @mapping: The address_space to search.
18502294b32eSMatthew Wilcox (Oracle)  * @index: The page index.
18513f0c6a07SMatthew Wilcox (Oracle)  * @fgp_flags: %FGP flags modify how the folio is returned.
18523f0c6a07SMatthew Wilcox (Oracle)  * @gfp: Memory allocation flags to use if %FGP_CREAT is specified.
18530cd6144aSJohannes Weiner  *
18542294b32eSMatthew Wilcox (Oracle)  * Looks up the page cache entry at @mapping & @index.
18550cd6144aSJohannes Weiner  *
18562294b32eSMatthew Wilcox (Oracle)  * If %FGP_LOCK or %FGP_CREAT are specified then the function may sleep even
18572294b32eSMatthew Wilcox (Oracle)  * if the %GFP flags specified for %FGP_CREAT are atomic.
18582457aec6SMel Gorman  *
1859ffc143dbSMatthew Wilcox (Oracle)  * If this function returns a folio, it is returned with an increased refcount.
1860a862f68aSMike Rapoport  *
186166dabbb6SChristoph Hellwig  * Return: The found folio or an ERR_PTR() otherwise.
18620cd6144aSJohannes Weiner  */
__filemap_get_folio(struct address_space * mapping,pgoff_t index,fgf_t fgp_flags,gfp_t gfp)18633f0c6a07SMatthew Wilcox (Oracle) struct folio *__filemap_get_folio(struct address_space *mapping, pgoff_t index,
1864ffc143dbSMatthew Wilcox (Oracle) 		fgf_t fgp_flags, gfp_t gfp)
18651da177e4SLinus Torvalds {
18663f0c6a07SMatthew Wilcox (Oracle) 	struct folio *folio;
18672457aec6SMel Gorman 
18681da177e4SLinus Torvalds repeat:
1869263e721eSChristoph Hellwig 	folio = filemap_get_entry(mapping, index);
187048c9d113SChristoph Hellwig 	if (xa_is_value(folio))
18713f0c6a07SMatthew Wilcox (Oracle) 		folio = NULL;
18723f0c6a07SMatthew Wilcox (Oracle) 	if (!folio)
18732457aec6SMel Gorman 		goto no_page;
18742457aec6SMel Gorman 
18752457aec6SMel Gorman 	if (fgp_flags & FGP_LOCK) {
18762457aec6SMel Gorman 		if (fgp_flags & FGP_NOWAIT) {
18773f0c6a07SMatthew Wilcox (Oracle) 			if (!folio_trylock(folio)) {
18783f0c6a07SMatthew Wilcox (Oracle) 				folio_put(folio);
187966dabbb6SChristoph Hellwig 				return ERR_PTR(-EAGAIN);
18802457aec6SMel Gorman 			}
18812457aec6SMel Gorman 		} else {
18823f0c6a07SMatthew Wilcox (Oracle) 			folio_lock(folio);
18832457aec6SMel Gorman 		}
18842457aec6SMel Gorman 
18852457aec6SMel Gorman 		/* Has the page been truncated? */
18863f0c6a07SMatthew Wilcox (Oracle) 		if (unlikely(folio->mapping != mapping)) {
18873f0c6a07SMatthew Wilcox (Oracle) 			folio_unlock(folio);
18883f0c6a07SMatthew Wilcox (Oracle) 			folio_put(folio);
18892457aec6SMel Gorman 			goto repeat;
18902457aec6SMel Gorman 		}
18913f0c6a07SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
18922457aec6SMel Gorman 	}
18932457aec6SMel Gorman 
1894c16eb000SKirill Tkhai 	if (fgp_flags & FGP_ACCESSED)
18953f0c6a07SMatthew Wilcox (Oracle) 		folio_mark_accessed(folio);
1896b9306a79SYang Shi 	else if (fgp_flags & FGP_WRITE) {
1897b9306a79SYang Shi 		/* Clear idle flag for buffer write */
18983f0c6a07SMatthew Wilcox (Oracle) 		if (folio_test_idle(folio))
18993f0c6a07SMatthew Wilcox (Oracle) 			folio_clear_idle(folio);
1900b9306a79SYang Shi 	}
19012457aec6SMel Gorman 
1902b27652d9SMatthew Wilcox (Oracle) 	if (fgp_flags & FGP_STABLE)
1903b27652d9SMatthew Wilcox (Oracle) 		folio_wait_stable(folio);
19042457aec6SMel Gorman no_page:
19053f0c6a07SMatthew Wilcox (Oracle) 	if (!folio && (fgp_flags & FGP_CREAT)) {
19064f661701SMatthew Wilcox (Oracle) 		unsigned order = FGF_GET_ORDER(fgp_flags);
19072457aec6SMel Gorman 		int err;
19084f661701SMatthew Wilcox (Oracle) 
1909f56753acSChristoph Hellwig 		if ((fgp_flags & FGP_WRITE) && mapping_can_writeback(mapping))
19103f0c6a07SMatthew Wilcox (Oracle) 			gfp |= __GFP_WRITE;
191145f87de5SMichal Hocko 		if (fgp_flags & FGP_NOFS)
19123f0c6a07SMatthew Wilcox (Oracle) 			gfp &= ~__GFP_FS;
19130dd316baSJens Axboe 		if (fgp_flags & FGP_NOWAIT) {
19140dd316baSJens Axboe 			gfp &= ~GFP_KERNEL;
19150dd316baSJens Axboe 			gfp |= GFP_NOWAIT | __GFP_NOWARN;
19160dd316baSJens Axboe 		}
1917a75d4c33SJosef Bacik 		if (WARN_ON_ONCE(!(fgp_flags & (FGP_LOCK | FGP_FOR_MMAP))))
19182457aec6SMel Gorman 			fgp_flags |= FGP_LOCK;
19192457aec6SMel Gorman 
19204f661701SMatthew Wilcox (Oracle) 		if (!mapping_large_folio_support(mapping))
19214f661701SMatthew Wilcox (Oracle) 			order = 0;
19224f661701SMatthew Wilcox (Oracle) 		if (order > MAX_PAGECACHE_ORDER)
19234f661701SMatthew Wilcox (Oracle) 			order = MAX_PAGECACHE_ORDER;
19244f661701SMatthew Wilcox (Oracle) 		/* If we're not aligned, allocate a smaller folio */
19254f661701SMatthew Wilcox (Oracle) 		if (index & ((1UL << order) - 1))
19264f661701SMatthew Wilcox (Oracle) 			order = __ffs(index);
19274f661701SMatthew Wilcox (Oracle) 
19284f661701SMatthew Wilcox (Oracle) 		do {
19294f661701SMatthew Wilcox (Oracle) 			gfp_t alloc_gfp = gfp;
19304f661701SMatthew Wilcox (Oracle) 
19314f661701SMatthew Wilcox (Oracle) 			err = -ENOMEM;
19324f661701SMatthew Wilcox (Oracle) 			if (order == 1)
19334f661701SMatthew Wilcox (Oracle) 				order = 0;
19344f661701SMatthew Wilcox (Oracle) 			if (order > 0)
19354f661701SMatthew Wilcox (Oracle) 				alloc_gfp |= __GFP_NORETRY | __GFP_NOWARN;
19364f661701SMatthew Wilcox (Oracle) 			folio = filemap_alloc_folio(alloc_gfp, order);
19374f661701SMatthew Wilcox (Oracle) 			if (!folio)
19384f661701SMatthew Wilcox (Oracle) 				continue;
19394f661701SMatthew Wilcox (Oracle) 
1940eb39d618SHugh Dickins 			/* Init accessed so avoid atomic mark_page_accessed later */
19412457aec6SMel Gorman 			if (fgp_flags & FGP_ACCESSED)
19423f0c6a07SMatthew Wilcox (Oracle) 				__folio_set_referenced(folio);
19432457aec6SMel Gorman 
19443f0c6a07SMatthew Wilcox (Oracle) 			err = filemap_add_folio(mapping, folio, index, gfp);
19454f661701SMatthew Wilcox (Oracle) 			if (!err)
19464f661701SMatthew Wilcox (Oracle) 				break;
19473f0c6a07SMatthew Wilcox (Oracle) 			folio_put(folio);
19483f0c6a07SMatthew Wilcox (Oracle) 			folio = NULL;
19494f661701SMatthew Wilcox (Oracle) 		} while (order-- > 0);
19504f661701SMatthew Wilcox (Oracle) 
1951eb2be189SNick Piggin 		if (err == -EEXIST)
19521da177e4SLinus Torvalds 			goto repeat;
19534f661701SMatthew Wilcox (Oracle) 		if (err)
19544f661701SMatthew Wilcox (Oracle) 			return ERR_PTR(err);
1955a75d4c33SJosef Bacik 		/*
19563f0c6a07SMatthew Wilcox (Oracle) 		 * filemap_add_folio locks the page, and for mmap
19573f0c6a07SMatthew Wilcox (Oracle) 		 * we expect an unlocked page.
1958a75d4c33SJosef Bacik 		 */
19593f0c6a07SMatthew Wilcox (Oracle) 		if (folio && (fgp_flags & FGP_FOR_MMAP))
19603f0c6a07SMatthew Wilcox (Oracle) 			folio_unlock(folio);
1961eb2be189SNick Piggin 	}
19622457aec6SMel Gorman 
196366dabbb6SChristoph Hellwig 	if (!folio)
196466dabbb6SChristoph Hellwig 		return ERR_PTR(-ENOENT);
19653f0c6a07SMatthew Wilcox (Oracle) 	return folio;
19661da177e4SLinus Torvalds }
19673f0c6a07SMatthew Wilcox (Oracle) EXPORT_SYMBOL(__filemap_get_folio);
19681da177e4SLinus Torvalds 
find_get_entry(struct xa_state * xas,pgoff_t max,xa_mark_t mark)1969f5e6429aSMatthew Wilcox (Oracle) static inline struct folio *find_get_entry(struct xa_state *xas, pgoff_t max,
1970c7bad633SMatthew Wilcox (Oracle) 		xa_mark_t mark)
1971c7bad633SMatthew Wilcox (Oracle) {
1972f5e6429aSMatthew Wilcox (Oracle) 	struct folio *folio;
1973c7bad633SMatthew Wilcox (Oracle) 
1974c7bad633SMatthew Wilcox (Oracle) retry:
1975c7bad633SMatthew Wilcox (Oracle) 	if (mark == XA_PRESENT)
1976f5e6429aSMatthew Wilcox (Oracle) 		folio = xas_find(xas, max);
1977c7bad633SMatthew Wilcox (Oracle) 	else
1978f5e6429aSMatthew Wilcox (Oracle) 		folio = xas_find_marked(xas, max, mark);
1979c7bad633SMatthew Wilcox (Oracle) 
1980f5e6429aSMatthew Wilcox (Oracle) 	if (xas_retry(xas, folio))
1981c7bad633SMatthew Wilcox (Oracle) 		goto retry;
1982c7bad633SMatthew Wilcox (Oracle) 	/*
1983c7bad633SMatthew Wilcox (Oracle) 	 * A shadow entry of a recently evicted page, a swap
1984c7bad633SMatthew Wilcox (Oracle) 	 * entry from shmem/tmpfs or a DAX entry.  Return it
1985c7bad633SMatthew Wilcox (Oracle) 	 * without attempting to raise page count.
1986c7bad633SMatthew Wilcox (Oracle) 	 */
1987f5e6429aSMatthew Wilcox (Oracle) 	if (!folio || xa_is_value(folio))
1988f5e6429aSMatthew Wilcox (Oracle) 		return folio;
1989c7bad633SMatthew Wilcox (Oracle) 
1990f5e6429aSMatthew Wilcox (Oracle) 	if (!folio_try_get_rcu(folio))
1991c7bad633SMatthew Wilcox (Oracle) 		goto reset;
1992c7bad633SMatthew Wilcox (Oracle) 
1993f5e6429aSMatthew Wilcox (Oracle) 	if (unlikely(folio != xas_reload(xas))) {
1994f5e6429aSMatthew Wilcox (Oracle) 		folio_put(folio);
1995c7bad633SMatthew Wilcox (Oracle) 		goto reset;
1996c7bad633SMatthew Wilcox (Oracle) 	}
1997c7bad633SMatthew Wilcox (Oracle) 
1998f5e6429aSMatthew Wilcox (Oracle) 	return folio;
1999c7bad633SMatthew Wilcox (Oracle) reset:
2000c7bad633SMatthew Wilcox (Oracle) 	xas_reset(xas);
2001c7bad633SMatthew Wilcox (Oracle) 	goto retry;
2002c7bad633SMatthew Wilcox (Oracle) }
2003c7bad633SMatthew Wilcox (Oracle) 
20041da177e4SLinus Torvalds /**
20050cd6144aSJohannes Weiner  * find_get_entries - gang pagecache lookup
20060cd6144aSJohannes Weiner  * @mapping:	The address_space to search
20070cd6144aSJohannes Weiner  * @start:	The starting page cache index
2008ca122fe4SMatthew Wilcox (Oracle)  * @end:	The final page index (inclusive).
20090e499ed3SMatthew Wilcox (Oracle)  * @fbatch:	Where the resulting entries are placed.
20100cd6144aSJohannes Weiner  * @indices:	The cache indices corresponding to the entries in @entries
20110cd6144aSJohannes Weiner  *
2012cf2039afSMatthew Wilcox (Oracle)  * find_get_entries() will search for and return a batch of entries in
20130e499ed3SMatthew Wilcox (Oracle)  * the mapping.  The entries are placed in @fbatch.  find_get_entries()
20140e499ed3SMatthew Wilcox (Oracle)  * takes a reference on any actual folios it returns.
20150cd6144aSJohannes Weiner  *
20160e499ed3SMatthew Wilcox (Oracle)  * The entries have ascending indexes.  The indices may not be consecutive
20170e499ed3SMatthew Wilcox (Oracle)  * due to not-present entries or large folios.
20180cd6144aSJohannes Weiner  *
20190e499ed3SMatthew Wilcox (Oracle)  * Any shadow entries of evicted folios, or swap entries from
2020139b6a6fSJohannes Weiner  * shmem/tmpfs, are included in the returned array.
20210cd6144aSJohannes Weiner  *
20220e499ed3SMatthew Wilcox (Oracle)  * Return: The number of entries which were found.
20230cd6144aSJohannes Weiner  */
find_get_entries(struct address_space * mapping,pgoff_t * start,pgoff_t end,struct folio_batch * fbatch,pgoff_t * indices)20249fb6beeaSVishal Moola (Oracle) unsigned find_get_entries(struct address_space *mapping, pgoff_t *start,
20250e499ed3SMatthew Wilcox (Oracle) 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
20260cd6144aSJohannes Weiner {
20279fb6beeaSVishal Moola (Oracle) 	XA_STATE(xas, &mapping->i_pages, *start);
2028f5e6429aSMatthew Wilcox (Oracle) 	struct folio *folio;
20290cd6144aSJohannes Weiner 
20300cd6144aSJohannes Weiner 	rcu_read_lock();
2031f5e6429aSMatthew Wilcox (Oracle) 	while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) {
20320e499ed3SMatthew Wilcox (Oracle) 		indices[fbatch->nr] = xas.xa_index;
20330e499ed3SMatthew Wilcox (Oracle) 		if (!folio_batch_add(fbatch, folio))
20340cd6144aSJohannes Weiner 			break;
20350cd6144aSJohannes Weiner 	}
20360cd6144aSJohannes Weiner 	rcu_read_unlock();
2037cf2039afSMatthew Wilcox (Oracle) 
20389fb6beeaSVishal Moola (Oracle) 	if (folio_batch_count(fbatch)) {
20399fb6beeaSVishal Moola (Oracle) 		unsigned long nr = 1;
20409fb6beeaSVishal Moola (Oracle) 		int idx = folio_batch_count(fbatch) - 1;
20419fb6beeaSVishal Moola (Oracle) 
20429fb6beeaSVishal Moola (Oracle) 		folio = fbatch->folios[idx];
20439fb6beeaSVishal Moola (Oracle) 		if (!xa_is_value(folio) && !folio_test_hugetlb(folio))
20449fb6beeaSVishal Moola (Oracle) 			nr = folio_nr_pages(folio);
20459fb6beeaSVishal Moola (Oracle) 		*start = indices[idx] + nr;
20469fb6beeaSVishal Moola (Oracle) 	}
20470e499ed3SMatthew Wilcox (Oracle) 	return folio_batch_count(fbatch);
20480cd6144aSJohannes Weiner }
20490cd6144aSJohannes Weiner 
20500cd6144aSJohannes Weiner /**
20515c211ba2SMatthew Wilcox (Oracle)  * find_lock_entries - Find a batch of pagecache entries.
20525c211ba2SMatthew Wilcox (Oracle)  * @mapping:	The address_space to search.
20535c211ba2SMatthew Wilcox (Oracle)  * @start:	The starting page cache index.
20545c211ba2SMatthew Wilcox (Oracle)  * @end:	The final page index (inclusive).
205551dcbdacSMatthew Wilcox (Oracle)  * @fbatch:	Where the resulting entries are placed.
205651dcbdacSMatthew Wilcox (Oracle)  * @indices:	The cache indices of the entries in @fbatch.
20575c211ba2SMatthew Wilcox (Oracle)  *
20585c211ba2SMatthew Wilcox (Oracle)  * find_lock_entries() will return a batch of entries from @mapping.
2059f5e6429aSMatthew Wilcox (Oracle)  * Swap, shadow and DAX entries are included.  Folios are returned
2060f5e6429aSMatthew Wilcox (Oracle)  * locked and with an incremented refcount.  Folios which are locked
2061f5e6429aSMatthew Wilcox (Oracle)  * by somebody else or under writeback are skipped.  Folios which are
2062f5e6429aSMatthew Wilcox (Oracle)  * partially outside the range are not returned.
20635c211ba2SMatthew Wilcox (Oracle)  *
20645c211ba2SMatthew Wilcox (Oracle)  * The entries have ascending indexes.  The indices may not be consecutive
2065f5e6429aSMatthew Wilcox (Oracle)  * due to not-present entries, large folios, folios which could not be
2066f5e6429aSMatthew Wilcox (Oracle)  * locked or folios under writeback.
20675c211ba2SMatthew Wilcox (Oracle)  *
20685c211ba2SMatthew Wilcox (Oracle)  * Return: The number of entries which were found.
20695c211ba2SMatthew Wilcox (Oracle)  */
find_lock_entries(struct address_space * mapping,pgoff_t * start,pgoff_t end,struct folio_batch * fbatch,pgoff_t * indices)20703392ca12SVishal Moola (Oracle) unsigned find_lock_entries(struct address_space *mapping, pgoff_t *start,
207151dcbdacSMatthew Wilcox (Oracle) 		pgoff_t end, struct folio_batch *fbatch, pgoff_t *indices)
20725c211ba2SMatthew Wilcox (Oracle) {
20733392ca12SVishal Moola (Oracle) 	XA_STATE(xas, &mapping->i_pages, *start);
2074f5e6429aSMatthew Wilcox (Oracle) 	struct folio *folio;
20755c211ba2SMatthew Wilcox (Oracle) 
20765c211ba2SMatthew Wilcox (Oracle) 	rcu_read_lock();
2077f5e6429aSMatthew Wilcox (Oracle) 	while ((folio = find_get_entry(&xas, end, XA_PRESENT))) {
2078f5e6429aSMatthew Wilcox (Oracle) 		if (!xa_is_value(folio)) {
20793392ca12SVishal Moola (Oracle) 			if (folio->index < *start)
20805c211ba2SMatthew Wilcox (Oracle) 				goto put;
208187b11f86SSidhartha Kumar 			if (folio_next_index(folio) - 1 > end)
20825c211ba2SMatthew Wilcox (Oracle) 				goto put;
2083f5e6429aSMatthew Wilcox (Oracle) 			if (!folio_trylock(folio))
20845c211ba2SMatthew Wilcox (Oracle) 				goto put;
2085f5e6429aSMatthew Wilcox (Oracle) 			if (folio->mapping != mapping ||
2086f5e6429aSMatthew Wilcox (Oracle) 			    folio_test_writeback(folio))
20875c211ba2SMatthew Wilcox (Oracle) 				goto unlock;
2088f5e6429aSMatthew Wilcox (Oracle) 			VM_BUG_ON_FOLIO(!folio_contains(folio, xas.xa_index),
2089f5e6429aSMatthew Wilcox (Oracle) 					folio);
20905c211ba2SMatthew Wilcox (Oracle) 		}
209151dcbdacSMatthew Wilcox (Oracle) 		indices[fbatch->nr] = xas.xa_index;
209251dcbdacSMatthew Wilcox (Oracle) 		if (!folio_batch_add(fbatch, folio))
20935c211ba2SMatthew Wilcox (Oracle) 			break;
20946b24ca4aSMatthew Wilcox (Oracle) 		continue;
20955c211ba2SMatthew Wilcox (Oracle) unlock:
2096f5e6429aSMatthew Wilcox (Oracle) 		folio_unlock(folio);
20975c211ba2SMatthew Wilcox (Oracle) put:
2098f5e6429aSMatthew Wilcox (Oracle) 		folio_put(folio);
20995c211ba2SMatthew Wilcox (Oracle) 	}
21005c211ba2SMatthew Wilcox (Oracle) 	rcu_read_unlock();
21015c211ba2SMatthew Wilcox (Oracle) 
21023392ca12SVishal Moola (Oracle) 	if (folio_batch_count(fbatch)) {
21033392ca12SVishal Moola (Oracle) 		unsigned long nr = 1;
21043392ca12SVishal Moola (Oracle) 		int idx = folio_batch_count(fbatch) - 1;
21053392ca12SVishal Moola (Oracle) 
21063392ca12SVishal Moola (Oracle) 		folio = fbatch->folios[idx];
21073392ca12SVishal Moola (Oracle) 		if (!xa_is_value(folio) && !folio_test_hugetlb(folio))
21083392ca12SVishal Moola (Oracle) 			nr = folio_nr_pages(folio);
21093392ca12SVishal Moola (Oracle) 		*start = indices[idx] + nr;
21103392ca12SVishal Moola (Oracle) 	}
211151dcbdacSMatthew Wilcox (Oracle) 	return folio_batch_count(fbatch);
21125c211ba2SMatthew Wilcox (Oracle) }
21135c211ba2SMatthew Wilcox (Oracle) 
21145c211ba2SMatthew Wilcox (Oracle) /**
2115be0ced5eSMatthew Wilcox (Oracle)  * filemap_get_folios - Get a batch of folios
21161da177e4SLinus Torvalds  * @mapping:	The address_space to search
21171da177e4SLinus Torvalds  * @start:	The starting page index
2118b947cee4SJan Kara  * @end:	The final page index (inclusive)
2119be0ced5eSMatthew Wilcox (Oracle)  * @fbatch:	The batch to fill.
21201da177e4SLinus Torvalds  *
2121be0ced5eSMatthew Wilcox (Oracle)  * Search for and return a batch of folios in the mapping starting at
2122be0ced5eSMatthew Wilcox (Oracle)  * index @start and up to index @end (inclusive).  The folios are returned
2123be0ced5eSMatthew Wilcox (Oracle)  * in @fbatch with an elevated reference count.
21241da177e4SLinus Torvalds  *
2125be0ced5eSMatthew Wilcox (Oracle)  * The first folio may start before @start; if it does, it will contain
2126be0ced5eSMatthew Wilcox (Oracle)  * @start.  The final folio may extend beyond @end; if it does, it will
2127be0ced5eSMatthew Wilcox (Oracle)  * contain @end.  The folios have ascending indices.  There may be gaps
2128be0ced5eSMatthew Wilcox (Oracle)  * between the folios if there are indices which have no folio in the
2129be0ced5eSMatthew Wilcox (Oracle)  * page cache.  If folios are added to or removed from the page cache
2130be0ced5eSMatthew Wilcox (Oracle)  * while this is running, they may or may not be found by this call.
21311da177e4SLinus Torvalds  *
2132be0ced5eSMatthew Wilcox (Oracle)  * Return: The number of folios which were found.
2133be0ced5eSMatthew Wilcox (Oracle)  * We also update @start to index the next folio for the traversal.
21341da177e4SLinus Torvalds  */
filemap_get_folios(struct address_space * mapping,pgoff_t * start,pgoff_t end,struct folio_batch * fbatch)2135be0ced5eSMatthew Wilcox (Oracle) unsigned filemap_get_folios(struct address_space *mapping, pgoff_t *start,
2136be0ced5eSMatthew Wilcox (Oracle) 		pgoff_t end, struct folio_batch *fbatch)
21371da177e4SLinus Torvalds {
2138fd1b3ceeSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, *start);
2139f5e6429aSMatthew Wilcox (Oracle) 	struct folio *folio;
21401da177e4SLinus Torvalds 
2141a60637c8SNick Piggin 	rcu_read_lock();
2142be0ced5eSMatthew Wilcox (Oracle) 	while ((folio = find_get_entry(&xas, end, XA_PRESENT)) != NULL) {
2143fd1b3ceeSMatthew Wilcox 		/* Skip over shadow, swap and DAX entries */
2144f5e6429aSMatthew Wilcox (Oracle) 		if (xa_is_value(folio))
21452cf938aaSMatthew Wilcox 			continue;
2146be0ced5eSMatthew Wilcox (Oracle) 		if (!folio_batch_add(fbatch, folio)) {
2147be0ced5eSMatthew Wilcox (Oracle) 			unsigned long nr = folio_nr_pages(folio);
2148a60637c8SNick Piggin 
2149be0ced5eSMatthew Wilcox (Oracle) 			if (folio_test_hugetlb(folio))
2150be0ced5eSMatthew Wilcox (Oracle) 				nr = 1;
2151be0ced5eSMatthew Wilcox (Oracle) 			*start = folio->index + nr;
2152b947cee4SJan Kara 			goto out;
2153b947cee4SJan Kara 		}
2154a60637c8SNick Piggin 	}
21555b280c0cSHugh Dickins 
2156b947cee4SJan Kara 	/*
2157b947cee4SJan Kara 	 * We come here when there is no page beyond @end. We take care to not
2158b947cee4SJan Kara 	 * overflow the index @start as it confuses some of the callers. This
2159fd1b3ceeSMatthew Wilcox 	 * breaks the iteration when there is a page at index -1 but that is
2160b947cee4SJan Kara 	 * already broken anyway.
2161b947cee4SJan Kara 	 */
2162b947cee4SJan Kara 	if (end == (pgoff_t)-1)
2163b947cee4SJan Kara 		*start = (pgoff_t)-1;
2164b947cee4SJan Kara 	else
2165b947cee4SJan Kara 		*start = end + 1;
2166b947cee4SJan Kara out:
2167a60637c8SNick Piggin 	rcu_read_unlock();
2168d72dc8a2SJan Kara 
2169be0ced5eSMatthew Wilcox (Oracle) 	return folio_batch_count(fbatch);
2170be0ced5eSMatthew Wilcox (Oracle) }
2171be0ced5eSMatthew Wilcox (Oracle) EXPORT_SYMBOL(filemap_get_folios);
2172be0ced5eSMatthew Wilcox (Oracle) 
2173ebf43500SJens Axboe /**
217435b47146SVishal Moola (Oracle)  * filemap_get_folios_contig - Get a batch of contiguous folios
2175ebf43500SJens Axboe  * @mapping:	The address_space to search
217635b47146SVishal Moola (Oracle)  * @start:	The starting page index
217735b47146SVishal Moola (Oracle)  * @end:	The final page index (inclusive)
217835b47146SVishal Moola (Oracle)  * @fbatch:	The batch to fill
2179ebf43500SJens Axboe  *
218035b47146SVishal Moola (Oracle)  * filemap_get_folios_contig() works exactly like filemap_get_folios(),
218135b47146SVishal Moola (Oracle)  * except the returned folios are guaranteed to be contiguous. This may
218235b47146SVishal Moola (Oracle)  * not return all contiguous folios if the batch gets filled up.
2183ebf43500SJens Axboe  *
218435b47146SVishal Moola (Oracle)  * Return: The number of folios found.
218535b47146SVishal Moola (Oracle)  * Also update @start to be positioned for traversal of the next folio.
2186ebf43500SJens Axboe  */
21870fc9d104SKonstantin Khlebnikov 
filemap_get_folios_contig(struct address_space * mapping,pgoff_t * start,pgoff_t end,struct folio_batch * fbatch)218835b47146SVishal Moola (Oracle) unsigned filemap_get_folios_contig(struct address_space *mapping,
218935b47146SVishal Moola (Oracle) 		pgoff_t *start, pgoff_t end, struct folio_batch *fbatch)
219035b47146SVishal Moola (Oracle) {
219135b47146SVishal Moola (Oracle) 	XA_STATE(xas, &mapping->i_pages, *start);
219235b47146SVishal Moola (Oracle) 	unsigned long nr;
219335b47146SVishal Moola (Oracle) 	struct folio *folio;
2194ebf43500SJens Axboe 
2195a60637c8SNick Piggin 	rcu_read_lock();
219635b47146SVishal Moola (Oracle) 
219735b47146SVishal Moola (Oracle) 	for (folio = xas_load(&xas); folio && xas.xa_index <= end;
219835b47146SVishal Moola (Oracle) 			folio = xas_next(&xas)) {
2199e1c37722SMatthew Wilcox (Oracle) 		if (xas_retry(&xas, folio))
22002cf938aaSMatthew Wilcox 			continue;
22018079b1c8SHugh Dickins 		/*
22023ece58a2SMatthew Wilcox 		 * If the entry has been swapped out, we can stop looking.
22033ece58a2SMatthew Wilcox 		 * No current caller is looking for DAX entries.
22048079b1c8SHugh Dickins 		 */
2205e1c37722SMatthew Wilcox (Oracle) 		if (xa_is_value(folio))
220635b47146SVishal Moola (Oracle) 			goto update_start;
2207a60637c8SNick Piggin 
2208e1c37722SMatthew Wilcox (Oracle) 		if (!folio_try_get_rcu(folio))
22093ece58a2SMatthew Wilcox 			goto retry;
2210a60637c8SNick Piggin 
2211e1c37722SMatthew Wilcox (Oracle) 		if (unlikely(folio != xas_reload(&xas)))
221235b47146SVishal Moola (Oracle) 			goto put_folio;
2213a60637c8SNick Piggin 
221435b47146SVishal Moola (Oracle) 		if (!folio_batch_add(fbatch, folio)) {
221535b47146SVishal Moola (Oracle) 			nr = folio_nr_pages(folio);
221635b47146SVishal Moola (Oracle) 
221735b47146SVishal Moola (Oracle) 			if (folio_test_hugetlb(folio))
221835b47146SVishal Moola (Oracle) 				nr = 1;
221935b47146SVishal Moola (Oracle) 			*start = folio->index + nr;
222035b47146SVishal Moola (Oracle) 			goto out;
22216b24ca4aSMatthew Wilcox (Oracle) 		}
22223ece58a2SMatthew Wilcox 		continue;
222335b47146SVishal Moola (Oracle) put_folio:
2224e1c37722SMatthew Wilcox (Oracle) 		folio_put(folio);
222535b47146SVishal Moola (Oracle) 
22263ece58a2SMatthew Wilcox retry:
22273ece58a2SMatthew Wilcox 		xas_reset(&xas);
2228ebf43500SJens Axboe 	}
222935b47146SVishal Moola (Oracle) 
223035b47146SVishal Moola (Oracle) update_start:
223135b47146SVishal Moola (Oracle) 	nr = folio_batch_count(fbatch);
223235b47146SVishal Moola (Oracle) 
223335b47146SVishal Moola (Oracle) 	if (nr) {
223435b47146SVishal Moola (Oracle) 		folio = fbatch->folios[nr - 1];
223535b47146SVishal Moola (Oracle) 		if (folio_test_hugetlb(folio))
223635b47146SVishal Moola (Oracle) 			*start = folio->index + 1;
223735b47146SVishal Moola (Oracle) 		else
223887b11f86SSidhartha Kumar 			*start = folio_next_index(folio);
2239ebf43500SJens Axboe 	}
224035b47146SVishal Moola (Oracle) out:
224135b47146SVishal Moola (Oracle) 	rcu_read_unlock();
224235b47146SVishal Moola (Oracle) 	return folio_batch_count(fbatch);
224335b47146SVishal Moola (Oracle) }
224435b47146SVishal Moola (Oracle) EXPORT_SYMBOL(filemap_get_folios_contig);
2245ebf43500SJens Axboe 
2246485bb99bSRandy Dunlap /**
2247247f9e1fSVishal Moola (Oracle)  * filemap_get_folios_tag - Get a batch of folios matching @tag
2248247f9e1fSVishal Moola (Oracle)  * @mapping:    The address_space to search
2249247f9e1fSVishal Moola (Oracle)  * @start:      The starting page index
225072b045aeSJan Kara  * @end:        The final page index (inclusive)
2251247f9e1fSVishal Moola (Oracle)  * @tag:        The tag index
2252247f9e1fSVishal Moola (Oracle)  * @fbatch:     The batch to fill
2253485bb99bSRandy Dunlap  *
2254247f9e1fSVishal Moola (Oracle)  * Same as filemap_get_folios(), but only returning folios tagged with @tag.
2255a862f68aSMike Rapoport  *
2256247f9e1fSVishal Moola (Oracle)  * Return: The number of folios found.
2257247f9e1fSVishal Moola (Oracle)  * Also update @start to index the next folio for traversal.
22581da177e4SLinus Torvalds  */
filemap_get_folios_tag(struct address_space * mapping,pgoff_t * start,pgoff_t end,xa_mark_t tag,struct folio_batch * fbatch)2259247f9e1fSVishal Moola (Oracle) unsigned filemap_get_folios_tag(struct address_space *mapping, pgoff_t *start,
2260247f9e1fSVishal Moola (Oracle) 			pgoff_t end, xa_mark_t tag, struct folio_batch *fbatch)
22611da177e4SLinus Torvalds {
2262247f9e1fSVishal Moola (Oracle) 	XA_STATE(xas, &mapping->i_pages, *start);
2263f5e6429aSMatthew Wilcox (Oracle) 	struct folio *folio;
22641da177e4SLinus Torvalds 
2265a60637c8SNick Piggin 	rcu_read_lock();
2266247f9e1fSVishal Moola (Oracle) 	while ((folio = find_get_entry(&xas, end, tag)) != NULL) {
22678079b1c8SHugh Dickins 		/*
2268a6906972SMatthew Wilcox 		 * Shadow entries should never be tagged, but this iteration
2269a6906972SMatthew Wilcox 		 * is lockless so there is a window for page reclaim to evict
2270a6906972SMatthew Wilcox 		 * a page we saw tagged. Skip over it.
22718079b1c8SHugh Dickins 		 */
2272f5e6429aSMatthew Wilcox (Oracle) 		if (xa_is_value(folio))
2273139b6a6fSJohannes Weiner 			continue;
2274247f9e1fSVishal Moola (Oracle) 		if (!folio_batch_add(fbatch, folio)) {
2275247f9e1fSVishal Moola (Oracle) 			unsigned long nr = folio_nr_pages(folio);
2276a60637c8SNick Piggin 
2277247f9e1fSVishal Moola (Oracle) 			if (folio_test_hugetlb(folio))
2278247f9e1fSVishal Moola (Oracle) 				nr = 1;
2279247f9e1fSVishal Moola (Oracle) 			*start = folio->index + nr;
228072b045aeSJan Kara 			goto out;
228172b045aeSJan Kara 		}
2282a60637c8SNick Piggin 	}
228372b045aeSJan Kara 	/*
2284247f9e1fSVishal Moola (Oracle) 	 * We come here when there is no page beyond @end. We take care to not
2285247f9e1fSVishal Moola (Oracle) 	 * overflow the index @start as it confuses some of the callers. This
2286247f9e1fSVishal Moola (Oracle) 	 * breaks the iteration when there is a page at index -1 but that is
2287247f9e1fSVishal Moola (Oracle) 	 * already broke anyway.
228872b045aeSJan Kara 	 */
228972b045aeSJan Kara 	if (end == (pgoff_t)-1)
2290247f9e1fSVishal Moola (Oracle) 		*start = (pgoff_t)-1;
229172b045aeSJan Kara 	else
2292247f9e1fSVishal Moola (Oracle) 		*start = end + 1;
229372b045aeSJan Kara out:
2294a60637c8SNick Piggin 	rcu_read_unlock();
2295a60637c8SNick Piggin 
2296247f9e1fSVishal Moola (Oracle) 	return folio_batch_count(fbatch);
22971da177e4SLinus Torvalds }
2298247f9e1fSVishal Moola (Oracle) EXPORT_SYMBOL(filemap_get_folios_tag);
22991da177e4SLinus Torvalds 
230076d42bd9SWu Fengguang /*
230176d42bd9SWu Fengguang  * CD/DVDs are error prone. When a medium error occurs, the driver may fail
230276d42bd9SWu Fengguang  * a _large_ part of the i/o request. Imagine the worst scenario:
230376d42bd9SWu Fengguang  *
230476d42bd9SWu Fengguang  *      ---R__________________________________________B__________
230576d42bd9SWu Fengguang  *         ^ reading here                             ^ bad block(assume 4k)
230676d42bd9SWu Fengguang  *
230776d42bd9SWu Fengguang  * read(R) => miss => readahead(R...B) => media error => frustrating retries
230876d42bd9SWu Fengguang  * => failing the whole request => read(R) => read(R+1) =>
230976d42bd9SWu Fengguang  * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
231076d42bd9SWu Fengguang  * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
231176d42bd9SWu Fengguang  * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
231276d42bd9SWu Fengguang  *
231376d42bd9SWu Fengguang  * It is going insane. Fix it by quickly scaling down the readahead size.
231476d42bd9SWu Fengguang  */
shrink_readahead_size_eio(struct file_ra_state * ra)23150f8e2db4SSouptick Joarder static void shrink_readahead_size_eio(struct file_ra_state *ra)
231676d42bd9SWu Fengguang {
231776d42bd9SWu Fengguang 	ra->ra_pages /= 4;
231876d42bd9SWu Fengguang }
231976d42bd9SWu Fengguang 
2320cbd59c48SMatthew Wilcox (Oracle) /*
232125d6a23eSMatthew Wilcox (Oracle)  * filemap_get_read_batch - Get a batch of folios for read
2322cbd59c48SMatthew Wilcox (Oracle)  *
232325d6a23eSMatthew Wilcox (Oracle)  * Get a batch of folios which represent a contiguous range of bytes in
232425d6a23eSMatthew Wilcox (Oracle)  * the file.  No exceptional entries will be returned.  If @index is in
232525d6a23eSMatthew Wilcox (Oracle)  * the middle of a folio, the entire folio will be returned.  The last
232625d6a23eSMatthew Wilcox (Oracle)  * folio in the batch may have the readahead flag set or the uptodate flag
232725d6a23eSMatthew Wilcox (Oracle)  * clear so that the caller can take the appropriate action.
2328cbd59c48SMatthew Wilcox (Oracle)  */
filemap_get_read_batch(struct address_space * mapping,pgoff_t index,pgoff_t max,struct folio_batch * fbatch)2329cbd59c48SMatthew Wilcox (Oracle) static void filemap_get_read_batch(struct address_space *mapping,
233025d6a23eSMatthew Wilcox (Oracle) 		pgoff_t index, pgoff_t max, struct folio_batch *fbatch)
2331cbd59c48SMatthew Wilcox (Oracle) {
2332cbd59c48SMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, index);
2333bdb72932SMatthew Wilcox (Oracle) 	struct folio *folio;
2334cbd59c48SMatthew Wilcox (Oracle) 
2335cbd59c48SMatthew Wilcox (Oracle) 	rcu_read_lock();
2336bdb72932SMatthew Wilcox (Oracle) 	for (folio = xas_load(&xas); folio; folio = xas_next(&xas)) {
2337bdb72932SMatthew Wilcox (Oracle) 		if (xas_retry(&xas, folio))
2338cbd59c48SMatthew Wilcox (Oracle) 			continue;
2339bdb72932SMatthew Wilcox (Oracle) 		if (xas.xa_index > max || xa_is_value(folio))
2340cbd59c48SMatthew Wilcox (Oracle) 			break;
2341cb995f4eSMatthew Wilcox (Oracle) 		if (xa_is_sibling(folio))
2342cb995f4eSMatthew Wilcox (Oracle) 			break;
2343bdb72932SMatthew Wilcox (Oracle) 		if (!folio_try_get_rcu(folio))
2344cbd59c48SMatthew Wilcox (Oracle) 			goto retry;
2345cbd59c48SMatthew Wilcox (Oracle) 
2346bdb72932SMatthew Wilcox (Oracle) 		if (unlikely(folio != xas_reload(&xas)))
234725d6a23eSMatthew Wilcox (Oracle) 			goto put_folio;
2348cbd59c48SMatthew Wilcox (Oracle) 
234925d6a23eSMatthew Wilcox (Oracle) 		if (!folio_batch_add(fbatch, folio))
2350cbd59c48SMatthew Wilcox (Oracle) 			break;
2351bdb72932SMatthew Wilcox (Oracle) 		if (!folio_test_uptodate(folio))
2352cbd59c48SMatthew Wilcox (Oracle) 			break;
2353bdb72932SMatthew Wilcox (Oracle) 		if (folio_test_readahead(folio))
2354cbd59c48SMatthew Wilcox (Oracle) 			break;
235587b11f86SSidhartha Kumar 		xas_advance(&xas, folio_next_index(folio) - 1);
2356cbd59c48SMatthew Wilcox (Oracle) 		continue;
235725d6a23eSMatthew Wilcox (Oracle) put_folio:
2358bdb72932SMatthew Wilcox (Oracle) 		folio_put(folio);
2359cbd59c48SMatthew Wilcox (Oracle) retry:
2360cbd59c48SMatthew Wilcox (Oracle) 		xas_reset(&xas);
2361cbd59c48SMatthew Wilcox (Oracle) 	}
2362cbd59c48SMatthew Wilcox (Oracle) 	rcu_read_unlock();
2363cbd59c48SMatthew Wilcox (Oracle) }
2364cbd59c48SMatthew Wilcox (Oracle) 
filemap_read_folio(struct file * file,filler_t filler,struct folio * folio)2365290e1a32SMatthew Wilcox (Oracle) static int filemap_read_folio(struct file *file, filler_t filler,
23669d427b4eSMatthew Wilcox (Oracle) 		struct folio *folio)
2367723ef24bSKent Overstreet {
236817604240SChristoph Hellwig 	bool workingset = folio_test_workingset(folio);
236917604240SChristoph Hellwig 	unsigned long pflags;
2370723ef24bSKent Overstreet 	int error;
2371723ef24bSKent Overstreet 
2372723ef24bSKent Overstreet 	/*
237368430303SMatthew Wilcox (Oracle) 	 * A previous I/O error may have been due to temporary failures,
23747e0a1265SMatthew Wilcox (Oracle) 	 * eg. multipath errors.  PG_error will be set again if read_folio
237568430303SMatthew Wilcox (Oracle) 	 * fails.
2376723ef24bSKent Overstreet 	 */
23779d427b4eSMatthew Wilcox (Oracle) 	folio_clear_error(folio);
237817604240SChristoph Hellwig 
2379723ef24bSKent Overstreet 	/* Start the actual read. The read will unlock the page. */
238017604240SChristoph Hellwig 	if (unlikely(workingset))
238117604240SChristoph Hellwig 		psi_memstall_enter(&pflags);
2382290e1a32SMatthew Wilcox (Oracle) 	error = filler(file, folio);
238317604240SChristoph Hellwig 	if (unlikely(workingset))
238417604240SChristoph Hellwig 		psi_memstall_leave(&pflags);
238568430303SMatthew Wilcox (Oracle) 	if (error)
238668430303SMatthew Wilcox (Oracle) 		return error;
2387723ef24bSKent Overstreet 
23889d427b4eSMatthew Wilcox (Oracle) 	error = folio_wait_locked_killable(folio);
238968430303SMatthew Wilcox (Oracle) 	if (error)
239068430303SMatthew Wilcox (Oracle) 		return error;
23919d427b4eSMatthew Wilcox (Oracle) 	if (folio_test_uptodate(folio))
2392aa1ec2f6SMatthew Wilcox (Oracle) 		return 0;
2393290e1a32SMatthew Wilcox (Oracle) 	if (file)
239468430303SMatthew Wilcox (Oracle) 		shrink_readahead_size_eio(&file->f_ra);
2395aa1ec2f6SMatthew Wilcox (Oracle) 	return -EIO;
2396723ef24bSKent Overstreet }
2397723ef24bSKent Overstreet 
filemap_range_uptodate(struct address_space * mapping,loff_t pos,size_t count,struct folio * folio,bool need_uptodate)2398fce70da3SMatthew Wilcox (Oracle) static bool filemap_range_uptodate(struct address_space *mapping,
2399dd5b9d00SDavid Howells 		loff_t pos, size_t count, struct folio *folio,
2400dd5b9d00SDavid Howells 		bool need_uptodate)
2401fce70da3SMatthew Wilcox (Oracle) {
24022fa4eeb8SMatthew Wilcox (Oracle) 	if (folio_test_uptodate(folio))
2403fce70da3SMatthew Wilcox (Oracle) 		return true;
2404fce70da3SMatthew Wilcox (Oracle) 	/* pipes can't handle partially uptodate pages */
2405dd5b9d00SDavid Howells 	if (need_uptodate)
2406fce70da3SMatthew Wilcox (Oracle) 		return false;
2407fce70da3SMatthew Wilcox (Oracle) 	if (!mapping->a_ops->is_partially_uptodate)
2408fce70da3SMatthew Wilcox (Oracle) 		return false;
24092fa4eeb8SMatthew Wilcox (Oracle) 	if (mapping->host->i_blkbits >= folio_shift(folio))
2410fce70da3SMatthew Wilcox (Oracle) 		return false;
2411fce70da3SMatthew Wilcox (Oracle) 
24122fa4eeb8SMatthew Wilcox (Oracle) 	if (folio_pos(folio) > pos) {
24132fa4eeb8SMatthew Wilcox (Oracle) 		count -= folio_pos(folio) - pos;
2414fce70da3SMatthew Wilcox (Oracle) 		pos = 0;
2415fce70da3SMatthew Wilcox (Oracle) 	} else {
24162fa4eeb8SMatthew Wilcox (Oracle) 		pos -= folio_pos(folio);
2417fce70da3SMatthew Wilcox (Oracle) 	}
2418fce70da3SMatthew Wilcox (Oracle) 
24192e7e80f7SMatthew Wilcox (Oracle) 	return mapping->a_ops->is_partially_uptodate(folio, pos, count);
2420fce70da3SMatthew Wilcox (Oracle) }
2421fce70da3SMatthew Wilcox (Oracle) 
filemap_update_page(struct kiocb * iocb,struct address_space * mapping,size_t count,struct folio * folio,bool need_uptodate)24224612aeefSMatthew Wilcox (Oracle) static int filemap_update_page(struct kiocb *iocb,
2423dd5b9d00SDavid Howells 		struct address_space *mapping, size_t count,
2424dd5b9d00SDavid Howells 		struct folio *folio, bool need_uptodate)
2425723ef24bSKent Overstreet {
2426723ef24bSKent Overstreet 	int error;
2427723ef24bSKent Overstreet 
2428730633f0SJan Kara 	if (iocb->ki_flags & IOCB_NOWAIT) {
2429730633f0SJan Kara 		if (!filemap_invalidate_trylock_shared(mapping))
243087d1d7b6SMatthew Wilcox (Oracle) 			return -EAGAIN;
2431730633f0SJan Kara 	} else {
2432730633f0SJan Kara 		filemap_invalidate_lock_shared(mapping);
2433730633f0SJan Kara 	}
2434730633f0SJan Kara 
2435ffdc8dabSMatthew Wilcox (Oracle) 	if (!folio_trylock(folio)) {
2436730633f0SJan Kara 		error = -EAGAIN;
2437730633f0SJan Kara 		if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_NOIO))
2438730633f0SJan Kara 			goto unlock_mapping;
243987d1d7b6SMatthew Wilcox (Oracle) 		if (!(iocb->ki_flags & IOCB_WAITQ)) {
2440730633f0SJan Kara 			filemap_invalidate_unlock_shared(mapping);
24419f2b04a2SMatthew Wilcox (Oracle) 			/*
24429f2b04a2SMatthew Wilcox (Oracle) 			 * This is where we usually end up waiting for a
24439f2b04a2SMatthew Wilcox (Oracle) 			 * previously submitted readahead to finish.
24449f2b04a2SMatthew Wilcox (Oracle) 			 */
24459f2b04a2SMatthew Wilcox (Oracle) 			folio_put_wait_locked(folio, TASK_KILLABLE);
24464612aeefSMatthew Wilcox (Oracle) 			return AOP_TRUNCATED_PAGE;
2447bd8a1f36SMatthew Wilcox (Oracle) 		}
2448ffdc8dabSMatthew Wilcox (Oracle) 		error = __folio_lock_async(folio, iocb->ki_waitq);
244987d1d7b6SMatthew Wilcox (Oracle) 		if (error)
2450730633f0SJan Kara 			goto unlock_mapping;
2451bd8a1f36SMatthew Wilcox (Oracle) 	}
2452723ef24bSKent Overstreet 
2453730633f0SJan Kara 	error = AOP_TRUNCATED_PAGE;
2454ffdc8dabSMatthew Wilcox (Oracle) 	if (!folio->mapping)
2455730633f0SJan Kara 		goto unlock;
2456723ef24bSKent Overstreet 
2457fce70da3SMatthew Wilcox (Oracle) 	error = 0;
2458dd5b9d00SDavid Howells 	if (filemap_range_uptodate(mapping, iocb->ki_pos, count, folio,
2459dd5b9d00SDavid Howells 				   need_uptodate))
2460fce70da3SMatthew Wilcox (Oracle) 		goto unlock;
2461fce70da3SMatthew Wilcox (Oracle) 
2462fce70da3SMatthew Wilcox (Oracle) 	error = -EAGAIN;
2463fce70da3SMatthew Wilcox (Oracle) 	if (iocb->ki_flags & (IOCB_NOIO | IOCB_NOWAIT | IOCB_WAITQ))
2464fce70da3SMatthew Wilcox (Oracle) 		goto unlock;
2465fce70da3SMatthew Wilcox (Oracle) 
2466290e1a32SMatthew Wilcox (Oracle) 	error = filemap_read_folio(iocb->ki_filp, mapping->a_ops->read_folio,
2467290e1a32SMatthew Wilcox (Oracle) 			folio);
2468730633f0SJan Kara 	goto unlock_mapping;
2469fce70da3SMatthew Wilcox (Oracle) unlock:
2470ffdc8dabSMatthew Wilcox (Oracle) 	folio_unlock(folio);
2471730633f0SJan Kara unlock_mapping:
2472730633f0SJan Kara 	filemap_invalidate_unlock_shared(mapping);
2473730633f0SJan Kara 	if (error == AOP_TRUNCATED_PAGE)
2474ffdc8dabSMatthew Wilcox (Oracle) 		folio_put(folio);
2475fce70da3SMatthew Wilcox (Oracle) 	return error;
2476723ef24bSKent Overstreet }
2477723ef24bSKent Overstreet 
filemap_create_folio(struct file * file,struct address_space * mapping,pgoff_t index,struct folio_batch * fbatch)2478a5d4ad09SMatthew Wilcox (Oracle) static int filemap_create_folio(struct file *file,
2479f253e185SMatthew Wilcox (Oracle) 		struct address_space *mapping, pgoff_t index,
248025d6a23eSMatthew Wilcox (Oracle) 		struct folio_batch *fbatch)
2481723ef24bSKent Overstreet {
2482a5d4ad09SMatthew Wilcox (Oracle) 	struct folio *folio;
2483723ef24bSKent Overstreet 	int error;
2484723ef24bSKent Overstreet 
2485a5d4ad09SMatthew Wilcox (Oracle) 	folio = filemap_alloc_folio(mapping_gfp_mask(mapping), 0);
2486a5d4ad09SMatthew Wilcox (Oracle) 	if (!folio)
2487f253e185SMatthew Wilcox (Oracle) 		return -ENOMEM;
2488723ef24bSKent Overstreet 
2489730633f0SJan Kara 	/*
2490a5d4ad09SMatthew Wilcox (Oracle) 	 * Protect against truncate / hole punch. Grabbing invalidate_lock
2491a5d4ad09SMatthew Wilcox (Oracle) 	 * here assures we cannot instantiate and bring uptodate new
2492a5d4ad09SMatthew Wilcox (Oracle) 	 * pagecache folios after evicting page cache during truncate
2493a5d4ad09SMatthew Wilcox (Oracle) 	 * and before actually freeing blocks.	Note that we could
2494a5d4ad09SMatthew Wilcox (Oracle) 	 * release invalidate_lock after inserting the folio into
2495a5d4ad09SMatthew Wilcox (Oracle) 	 * the page cache as the locked folio would then be enough to
2496a5d4ad09SMatthew Wilcox (Oracle) 	 * synchronize with hole punching. But there are code paths
2497a5d4ad09SMatthew Wilcox (Oracle) 	 * such as filemap_update_page() filling in partially uptodate
2498704528d8SMatthew Wilcox (Oracle) 	 * pages or ->readahead() that need to hold invalidate_lock
2499a5d4ad09SMatthew Wilcox (Oracle) 	 * while mapping blocks for IO so let's hold the lock here as
2500a5d4ad09SMatthew Wilcox (Oracle) 	 * well to keep locking rules simple.
2501730633f0SJan Kara 	 */
2502730633f0SJan Kara 	filemap_invalidate_lock_shared(mapping);
2503a5d4ad09SMatthew Wilcox (Oracle) 	error = filemap_add_folio(mapping, folio, index,
2504723ef24bSKent Overstreet 			mapping_gfp_constraint(mapping, GFP_KERNEL));
2505f253e185SMatthew Wilcox (Oracle) 	if (error == -EEXIST)
2506f253e185SMatthew Wilcox (Oracle) 		error = AOP_TRUNCATED_PAGE;
2507f253e185SMatthew Wilcox (Oracle) 	if (error)
2508f253e185SMatthew Wilcox (Oracle) 		goto error;
2509f253e185SMatthew Wilcox (Oracle) 
2510290e1a32SMatthew Wilcox (Oracle) 	error = filemap_read_folio(file, mapping->a_ops->read_folio, folio);
2511f253e185SMatthew Wilcox (Oracle) 	if (error)
2512f253e185SMatthew Wilcox (Oracle) 		goto error;
2513f253e185SMatthew Wilcox (Oracle) 
2514730633f0SJan Kara 	filemap_invalidate_unlock_shared(mapping);
251525d6a23eSMatthew Wilcox (Oracle) 	folio_batch_add(fbatch, folio);
2516f253e185SMatthew Wilcox (Oracle) 	return 0;
2517f253e185SMatthew Wilcox (Oracle) error:
2518730633f0SJan Kara 	filemap_invalidate_unlock_shared(mapping);
2519a5d4ad09SMatthew Wilcox (Oracle) 	folio_put(folio);
2520f253e185SMatthew Wilcox (Oracle) 	return error;
2521723ef24bSKent Overstreet }
2522723ef24bSKent Overstreet 
filemap_readahead(struct kiocb * iocb,struct file * file,struct address_space * mapping,struct folio * folio,pgoff_t last_index)25235963fe03SMatthew Wilcox (Oracle) static int filemap_readahead(struct kiocb *iocb, struct file *file,
252465bca53bSMatthew Wilcox (Oracle) 		struct address_space *mapping, struct folio *folio,
25255963fe03SMatthew Wilcox (Oracle) 		pgoff_t last_index)
25265963fe03SMatthew Wilcox (Oracle) {
252765bca53bSMatthew Wilcox (Oracle) 	DEFINE_READAHEAD(ractl, file, &file->f_ra, mapping, folio->index);
252865bca53bSMatthew Wilcox (Oracle) 
25295963fe03SMatthew Wilcox (Oracle) 	if (iocb->ki_flags & IOCB_NOIO)
25305963fe03SMatthew Wilcox (Oracle) 		return -EAGAIN;
253165bca53bSMatthew Wilcox (Oracle) 	page_cache_async_ra(&ractl, folio, last_index - folio->index);
25325963fe03SMatthew Wilcox (Oracle) 	return 0;
25335963fe03SMatthew Wilcox (Oracle) }
25345963fe03SMatthew Wilcox (Oracle) 
filemap_get_pages(struct kiocb * iocb,size_t count,struct folio_batch * fbatch,bool need_uptodate)2535dd5b9d00SDavid Howells static int filemap_get_pages(struct kiocb *iocb, size_t count,
2536dd5b9d00SDavid Howells 		struct folio_batch *fbatch, bool need_uptodate)
253706c04442SKent Overstreet {
253806c04442SKent Overstreet 	struct file *filp = iocb->ki_filp;
253906c04442SKent Overstreet 	struct address_space *mapping = filp->f_mapping;
254006c04442SKent Overstreet 	struct file_ra_state *ra = &filp->f_ra;
254106c04442SKent Overstreet 	pgoff_t index = iocb->ki_pos >> PAGE_SHIFT;
2542cbd59c48SMatthew Wilcox (Oracle) 	pgoff_t last_index;
254365bca53bSMatthew Wilcox (Oracle) 	struct folio *folio;
2544cbd59c48SMatthew Wilcox (Oracle) 	int err = 0;
254506c04442SKent Overstreet 
25465956592cSQian Yingjin 	/* "last_index" is the index of the page beyond the end of the read */
2547dd5b9d00SDavid Howells 	last_index = DIV_ROUND_UP(iocb->ki_pos + count, PAGE_SIZE);
25482642fca6SMatthew Wilcox (Oracle) retry:
254906c04442SKent Overstreet 	if (fatal_signal_pending(current))
255006c04442SKent Overstreet 		return -EINTR;
255106c04442SKent Overstreet 
25525956592cSQian Yingjin 	filemap_get_read_batch(mapping, index, last_index - 1, fbatch);
255325d6a23eSMatthew Wilcox (Oracle) 	if (!folio_batch_count(fbatch)) {
255406c04442SKent Overstreet 		if (iocb->ki_flags & IOCB_NOIO)
255506c04442SKent Overstreet 			return -EAGAIN;
25562642fca6SMatthew Wilcox (Oracle) 		page_cache_sync_readahead(mapping, ra, filp, index,
25572642fca6SMatthew Wilcox (Oracle) 				last_index - index);
25585956592cSQian Yingjin 		filemap_get_read_batch(mapping, index, last_index - 1, fbatch);
25592642fca6SMatthew Wilcox (Oracle) 	}
256025d6a23eSMatthew Wilcox (Oracle) 	if (!folio_batch_count(fbatch)) {
2561f253e185SMatthew Wilcox (Oracle) 		if (iocb->ki_flags & (IOCB_NOWAIT | IOCB_WAITQ))
2562f253e185SMatthew Wilcox (Oracle) 			return -EAGAIN;
2563a5d4ad09SMatthew Wilcox (Oracle) 		err = filemap_create_folio(filp, mapping,
256425d6a23eSMatthew Wilcox (Oracle) 				iocb->ki_pos >> PAGE_SHIFT, fbatch);
2565f253e185SMatthew Wilcox (Oracle) 		if (err == AOP_TRUNCATED_PAGE)
25662642fca6SMatthew Wilcox (Oracle) 			goto retry;
2567f253e185SMatthew Wilcox (Oracle) 		return err;
2568f253e185SMatthew Wilcox (Oracle) 	}
256906c04442SKent Overstreet 
257025d6a23eSMatthew Wilcox (Oracle) 	folio = fbatch->folios[folio_batch_count(fbatch) - 1];
257165bca53bSMatthew Wilcox (Oracle) 	if (folio_test_readahead(folio)) {
257265bca53bSMatthew Wilcox (Oracle) 		err = filemap_readahead(iocb, filp, mapping, folio, last_index);
25732642fca6SMatthew Wilcox (Oracle) 		if (err)
2574cbd59c48SMatthew Wilcox (Oracle) 			goto err;
257506c04442SKent Overstreet 	}
257665bca53bSMatthew Wilcox (Oracle) 	if (!folio_test_uptodate(folio)) {
257725d6a23eSMatthew Wilcox (Oracle) 		if ((iocb->ki_flags & IOCB_WAITQ) &&
257825d6a23eSMatthew Wilcox (Oracle) 		    folio_batch_count(fbatch) > 1)
257987d1d7b6SMatthew Wilcox (Oracle) 			iocb->ki_flags |= IOCB_NOWAIT;
2580dd5b9d00SDavid Howells 		err = filemap_update_page(iocb, mapping, count, folio,
2581dd5b9d00SDavid Howells 					  need_uptodate);
25822642fca6SMatthew Wilcox (Oracle) 		if (err)
25832642fca6SMatthew Wilcox (Oracle) 			goto err;
258406c04442SKent Overstreet 	}
258506c04442SKent Overstreet 
25862642fca6SMatthew Wilcox (Oracle) 	return 0;
2587cbd59c48SMatthew Wilcox (Oracle) err:
25882642fca6SMatthew Wilcox (Oracle) 	if (err < 0)
258965bca53bSMatthew Wilcox (Oracle) 		folio_put(folio);
259025d6a23eSMatthew Wilcox (Oracle) 	if (likely(--fbatch->nr))
2591ff993ba1SMatthew Wilcox (Oracle) 		return 0;
25924612aeefSMatthew Wilcox (Oracle) 	if (err == AOP_TRUNCATED_PAGE)
25932642fca6SMatthew Wilcox (Oracle) 		goto retry;
259406c04442SKent Overstreet 	return err;
259506c04442SKent Overstreet }
259606c04442SKent Overstreet 
pos_same_folio(loff_t pos1,loff_t pos2,struct folio * folio)25975ccc944dSMatthew Wilcox (Oracle) static inline bool pos_same_folio(loff_t pos1, loff_t pos2, struct folio *folio)
25985ccc944dSMatthew Wilcox (Oracle) {
25995ccc944dSMatthew Wilcox (Oracle) 	unsigned int shift = folio_shift(folio);
26005ccc944dSMatthew Wilcox (Oracle) 
26015ccc944dSMatthew Wilcox (Oracle) 	return (pos1 >> shift == pos2 >> shift);
26025ccc944dSMatthew Wilcox (Oracle) }
26035ccc944dSMatthew Wilcox (Oracle) 
2604485bb99bSRandy Dunlap /**
260587fa0f3eSChristoph Hellwig  * filemap_read - Read data from the page cache.
260687fa0f3eSChristoph Hellwig  * @iocb: The iocb to read.
260787fa0f3eSChristoph Hellwig  * @iter: Destination for the data.
260887fa0f3eSChristoph Hellwig  * @already_read: Number of bytes already read by the caller.
2609485bb99bSRandy Dunlap  *
261087fa0f3eSChristoph Hellwig  * Copies data from the page cache.  If the data is not currently present,
26117e0a1265SMatthew Wilcox (Oracle)  * uses the readahead and read_folio address_space operations to fetch it.
26121da177e4SLinus Torvalds  *
261387fa0f3eSChristoph Hellwig  * Return: Total number of bytes copied, including those already read by
261487fa0f3eSChristoph Hellwig  * the caller.  If an error happens before any bytes are copied, returns
261587fa0f3eSChristoph Hellwig  * a negative error number.
26161da177e4SLinus Torvalds  */
filemap_read(struct kiocb * iocb,struct iov_iter * iter,ssize_t already_read)261787fa0f3eSChristoph Hellwig ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
261887fa0f3eSChristoph Hellwig 		ssize_t already_read)
26191da177e4SLinus Torvalds {
262047c27bc4SChristoph Hellwig 	struct file *filp = iocb->ki_filp;
262106c04442SKent Overstreet 	struct file_ra_state *ra = &filp->f_ra;
262236e78914SChristoph Hellwig 	struct address_space *mapping = filp->f_mapping;
26231da177e4SLinus Torvalds 	struct inode *inode = mapping->host;
262425d6a23eSMatthew Wilcox (Oracle) 	struct folio_batch fbatch;
2625ff993ba1SMatthew Wilcox (Oracle) 	int i, error = 0;
262606c04442SKent Overstreet 	bool writably_mapped;
262706c04442SKent Overstreet 	loff_t isize, end_offset;
2628f04d16eeSHaibo Li 	loff_t last_pos = ra->prev_pos;
26291da177e4SLinus Torvalds 
2630723ef24bSKent Overstreet 	if (unlikely(iocb->ki_pos >= inode->i_sb->s_maxbytes))
2631d05c5f7bSLinus Torvalds 		return 0;
26323644e2d2SKent Overstreet 	if (unlikely(!iov_iter_count(iter)))
26333644e2d2SKent Overstreet 		return 0;
26343644e2d2SKent Overstreet 
2635c2a9737fSWei Fang 	iov_iter_truncate(iter, inode->i_sb->s_maxbytes);
263625d6a23eSMatthew Wilcox (Oracle) 	folio_batch_init(&fbatch);
2637c2a9737fSWei Fang 
263806c04442SKent Overstreet 	do {
263906c04442SKent Overstreet 		cond_resched();
26401da177e4SLinus Torvalds 
264113bd6914SJens Axboe 		/*
264213bd6914SJens Axboe 		 * If we've already successfully copied some data, then we
264313bd6914SJens Axboe 		 * can no longer safely return -EIOCBQUEUED. Hence mark
264413bd6914SJens Axboe 		 * an async read NOWAIT at that point.
264513bd6914SJens Axboe 		 */
264687fa0f3eSChristoph Hellwig 		if ((iocb->ki_flags & IOCB_WAITQ) && already_read)
264713bd6914SJens Axboe 			iocb->ki_flags |= IOCB_NOWAIT;
264813bd6914SJens Axboe 
26498c8387eeSDavid Howells 		if (unlikely(iocb->ki_pos >= i_size_read(inode)))
26508c8387eeSDavid Howells 			break;
26518c8387eeSDavid Howells 
26523fc40265SDavid Howells 		error = filemap_get_pages(iocb, iter->count, &fbatch, false);
2653ff993ba1SMatthew Wilcox (Oracle) 		if (error < 0)
265406c04442SKent Overstreet 			break;
26555abf186aSMichal Hocko 
2656723ef24bSKent Overstreet 		/*
265706c04442SKent Overstreet 		 * i_size must be checked after we know the pages are Uptodate.
265806c04442SKent Overstreet 		 *
265906c04442SKent Overstreet 		 * Checking i_size after the check allows us to calculate
266006c04442SKent Overstreet 		 * the correct value for "nr", which means the zero-filled
266106c04442SKent Overstreet 		 * part of the page is not copied back to userspace (unless
266206c04442SKent Overstreet 		 * another truncate extends the file - this is desired though).
2663723ef24bSKent Overstreet 		 */
266406c04442SKent Overstreet 		isize = i_size_read(inode);
266506c04442SKent Overstreet 		if (unlikely(iocb->ki_pos >= isize))
266625d6a23eSMatthew Wilcox (Oracle) 			goto put_folios;
266706c04442SKent Overstreet 		end_offset = min_t(loff_t, isize, iocb->ki_pos + iter->count);
2668c8d317aaSHao Xu 
266906c04442SKent Overstreet 		/*
2670d16eb52cSBaokun Li 		 * Pairs with a barrier in
2671d16eb52cSBaokun Li 		 * block_write_end()->mark_buffer_dirty() or other page
2672d16eb52cSBaokun Li 		 * dirtying routines like iomap_write_end() to ensure
2673d16eb52cSBaokun Li 		 * changes to page contents are visible before we see
2674d16eb52cSBaokun Li 		 * increased inode size.
2675d16eb52cSBaokun Li 		 */
2676d16eb52cSBaokun Li 		smp_rmb();
2677d16eb52cSBaokun Li 
2678d16eb52cSBaokun Li 		/*
267906c04442SKent Overstreet 		 * Once we start copying data, we don't want to be touching any
268006c04442SKent Overstreet 		 * cachelines that might be contended:
268106c04442SKent Overstreet 		 */
268206c04442SKent Overstreet 		writably_mapped = mapping_writably_mapped(mapping);
268306c04442SKent Overstreet 
268406c04442SKent Overstreet 		/*
26855ccc944dSMatthew Wilcox (Oracle) 		 * When a read accesses the same folio several times, only
268606c04442SKent Overstreet 		 * mark it as accessed the first time.
268706c04442SKent Overstreet 		 */
2688f04d16eeSHaibo Li 		if (!pos_same_folio(iocb->ki_pos, last_pos - 1,
26895ccc944dSMatthew Wilcox (Oracle) 				    fbatch.folios[0]))
269025d6a23eSMatthew Wilcox (Oracle) 			folio_mark_accessed(fbatch.folios[0]);
269106c04442SKent Overstreet 
269225d6a23eSMatthew Wilcox (Oracle) 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
269325d6a23eSMatthew Wilcox (Oracle) 			struct folio *folio = fbatch.folios[i];
2694d996fc7fSMatthew Wilcox (Oracle) 			size_t fsize = folio_size(folio);
2695d996fc7fSMatthew Wilcox (Oracle) 			size_t offset = iocb->ki_pos & (fsize - 1);
2696cbd59c48SMatthew Wilcox (Oracle) 			size_t bytes = min_t(loff_t, end_offset - iocb->ki_pos,
2697d996fc7fSMatthew Wilcox (Oracle) 					     fsize - offset);
2698cbd59c48SMatthew Wilcox (Oracle) 			size_t copied;
269906c04442SKent Overstreet 
2700d996fc7fSMatthew Wilcox (Oracle) 			if (end_offset < folio_pos(folio))
2701cbd59c48SMatthew Wilcox (Oracle) 				break;
2702cbd59c48SMatthew Wilcox (Oracle) 			if (i > 0)
2703d996fc7fSMatthew Wilcox (Oracle) 				folio_mark_accessed(folio);
270406c04442SKent Overstreet 			/*
2705d996fc7fSMatthew Wilcox (Oracle) 			 * If users can be writing to this folio using arbitrary
2706d996fc7fSMatthew Wilcox (Oracle) 			 * virtual addresses, take care of potential aliasing
2707d996fc7fSMatthew Wilcox (Oracle) 			 * before reading the folio on the kernel side.
270806c04442SKent Overstreet 			 */
2709d996fc7fSMatthew Wilcox (Oracle) 			if (writably_mapped)
2710d996fc7fSMatthew Wilcox (Oracle) 				flush_dcache_folio(folio);
271106c04442SKent Overstreet 
2712d996fc7fSMatthew Wilcox (Oracle) 			copied = copy_folio_to_iter(folio, offset, bytes, iter);
271306c04442SKent Overstreet 
271487fa0f3eSChristoph Hellwig 			already_read += copied;
271506c04442SKent Overstreet 			iocb->ki_pos += copied;
2716f04d16eeSHaibo Li 			last_pos = iocb->ki_pos;
271706c04442SKent Overstreet 
271806c04442SKent Overstreet 			if (copied < bytes) {
271906c04442SKent Overstreet 				error = -EFAULT;
272006c04442SKent Overstreet 				break;
27211da177e4SLinus Torvalds 			}
27221da177e4SLinus Torvalds 		}
272325d6a23eSMatthew Wilcox (Oracle) put_folios:
272425d6a23eSMatthew Wilcox (Oracle) 		for (i = 0; i < folio_batch_count(&fbatch); i++)
272525d6a23eSMatthew Wilcox (Oracle) 			folio_put(fbatch.folios[i]);
272625d6a23eSMatthew Wilcox (Oracle) 		folio_batch_init(&fbatch);
272706c04442SKent Overstreet 	} while (iov_iter_count(iter) && iocb->ki_pos < isize && !error);
27281da177e4SLinus Torvalds 
27291da177e4SLinus Torvalds 	file_accessed(filp);
2730f04d16eeSHaibo Li 	ra->prev_pos = last_pos;
273187fa0f3eSChristoph Hellwig 	return already_read ? already_read : error;
27321da177e4SLinus Torvalds }
273387fa0f3eSChristoph Hellwig EXPORT_SYMBOL_GPL(filemap_read);
27341da177e4SLinus Torvalds 
kiocb_write_and_wait(struct kiocb * iocb,size_t count)27353c435a0fSChristoph Hellwig int kiocb_write_and_wait(struct kiocb *iocb, size_t count)
27363c435a0fSChristoph Hellwig {
27373c435a0fSChristoph Hellwig 	struct address_space *mapping = iocb->ki_filp->f_mapping;
27383c435a0fSChristoph Hellwig 	loff_t pos = iocb->ki_pos;
27393c435a0fSChristoph Hellwig 	loff_t end = pos + count - 1;
27403c435a0fSChristoph Hellwig 
27413c435a0fSChristoph Hellwig 	if (iocb->ki_flags & IOCB_NOWAIT) {
27423c435a0fSChristoph Hellwig 		if (filemap_range_needs_writeback(mapping, pos, end))
27433c435a0fSChristoph Hellwig 			return -EAGAIN;
27443c435a0fSChristoph Hellwig 		return 0;
27453c435a0fSChristoph Hellwig 	}
27463c435a0fSChristoph Hellwig 
27473c435a0fSChristoph Hellwig 	return filemap_write_and_wait_range(mapping, pos, end);
27483c435a0fSChristoph Hellwig }
27493c435a0fSChristoph Hellwig 
kiocb_invalidate_pages(struct kiocb * iocb,size_t count)2750e003f74aSChristoph Hellwig int kiocb_invalidate_pages(struct kiocb *iocb, size_t count)
2751e003f74aSChristoph Hellwig {
2752e003f74aSChristoph Hellwig 	struct address_space *mapping = iocb->ki_filp->f_mapping;
2753e003f74aSChristoph Hellwig 	loff_t pos = iocb->ki_pos;
2754e003f74aSChristoph Hellwig 	loff_t end = pos + count - 1;
2755e003f74aSChristoph Hellwig 	int ret;
2756e003f74aSChristoph Hellwig 
2757e003f74aSChristoph Hellwig 	if (iocb->ki_flags & IOCB_NOWAIT) {
2758e003f74aSChristoph Hellwig 		/* we could block if there are any pages in the range */
2759e003f74aSChristoph Hellwig 		if (filemap_range_has_page(mapping, pos, end))
2760e003f74aSChristoph Hellwig 			return -EAGAIN;
2761e003f74aSChristoph Hellwig 	} else {
2762e003f74aSChristoph Hellwig 		ret = filemap_write_and_wait_range(mapping, pos, end);
2763e003f74aSChristoph Hellwig 		if (ret)
2764e003f74aSChristoph Hellwig 			return ret;
2765e003f74aSChristoph Hellwig 	}
2766e003f74aSChristoph Hellwig 
2767e003f74aSChristoph Hellwig 	/*
2768e003f74aSChristoph Hellwig 	 * After a write we want buffered reads to be sure to go to disk to get
2769e003f74aSChristoph Hellwig 	 * the new data.  We invalidate clean cached page from the region we're
2770e003f74aSChristoph Hellwig 	 * about to write.  We do this *before* the write so that we can return
2771e003f74aSChristoph Hellwig 	 * without clobbering -EIOCBQUEUED from ->direct_IO().
2772e003f74aSChristoph Hellwig 	 */
2773e003f74aSChristoph Hellwig 	return invalidate_inode_pages2_range(mapping, pos >> PAGE_SHIFT,
2774e003f74aSChristoph Hellwig 					     end >> PAGE_SHIFT);
2775e003f74aSChristoph Hellwig }
2776e003f74aSChristoph Hellwig 
2777485bb99bSRandy Dunlap /**
27786abd2322SAl Viro  * generic_file_read_iter - generic filesystem read routine
2779485bb99bSRandy Dunlap  * @iocb:	kernel I/O control block
27806abd2322SAl Viro  * @iter:	destination for the data read
2781485bb99bSRandy Dunlap  *
27826abd2322SAl Viro  * This is the "read_iter()" routine for all filesystems
27831da177e4SLinus Torvalds  * that can use the page cache directly.
278441da51bcSAndreas Gruenbacher  *
278541da51bcSAndreas Gruenbacher  * The IOCB_NOWAIT flag in iocb->ki_flags indicates that -EAGAIN shall
278641da51bcSAndreas Gruenbacher  * be returned when no data can be read without waiting for I/O requests
278741da51bcSAndreas Gruenbacher  * to complete; it doesn't prevent readahead.
278841da51bcSAndreas Gruenbacher  *
278941da51bcSAndreas Gruenbacher  * The IOCB_NOIO flag in iocb->ki_flags indicates that no new I/O
279041da51bcSAndreas Gruenbacher  * requests shall be made for the read or for readahead.  When no data
279141da51bcSAndreas Gruenbacher  * can be read, -EAGAIN shall be returned.  When readahead would be
279241da51bcSAndreas Gruenbacher  * triggered, a partial, possibly empty read shall be returned.
279341da51bcSAndreas Gruenbacher  *
2794a862f68aSMike Rapoport  * Return:
2795a862f68aSMike Rapoport  * * number of bytes copied, even for partial reads
279641da51bcSAndreas Gruenbacher  * * negative error code (or 0 if IOCB_NOIO) if nothing was read
27971da177e4SLinus Torvalds  */
27981da177e4SLinus Torvalds ssize_t
generic_file_read_iter(struct kiocb * iocb,struct iov_iter * iter)2799ed978a81SAl Viro generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
28001da177e4SLinus Torvalds {
2801e7080a43SNicolai Stange 	size_t count = iov_iter_count(iter);
280247c27bc4SChristoph Hellwig 	ssize_t retval = 0;
2803e7080a43SNicolai Stange 
2804e7080a43SNicolai Stange 	if (!count)
2805826ea860SChristoph Hellwig 		return 0; /* skip atime */
28061da177e4SLinus Torvalds 
28072ba48ce5SAl Viro 	if (iocb->ki_flags & IOCB_DIRECT) {
280847c27bc4SChristoph Hellwig 		struct file *file = iocb->ki_filp;
2809ed978a81SAl Viro 		struct address_space *mapping = file->f_mapping;
2810ed978a81SAl Viro 		struct inode *inode = mapping->host;
28111da177e4SLinus Torvalds 
28123c435a0fSChristoph Hellwig 		retval = kiocb_write_and_wait(iocb, count);
28130d5b0cf2SChristoph Hellwig 		if (retval < 0)
2814826ea860SChristoph Hellwig 			return retval;
28150d5b0cf2SChristoph Hellwig 		file_accessed(file);
28160d5b0cf2SChristoph Hellwig 
28175ecda137SAl Viro 		retval = mapping->a_ops->direct_IO(iocb, iter);
2818c3a69024SAl Viro 		if (retval >= 0) {
2819c64fb5c7SChristoph Hellwig 			iocb->ki_pos += retval;
28205ecda137SAl Viro 			count -= retval;
282166f998f6SJosef Bacik 		}
2822ab2125dfSPavel Begunkov 		if (retval != -EIOCBQUEUED)
28235b47d59aSAl Viro 			iov_iter_revert(iter, count - iov_iter_count(iter));
282466f998f6SJosef Bacik 
282566f998f6SJosef Bacik 		/*
282666f998f6SJosef Bacik 		 * Btrfs can have a short DIO read if we encounter
282766f998f6SJosef Bacik 		 * compressed extents, so if there was an error, or if
282866f998f6SJosef Bacik 		 * we've already read everything we wanted to, or if
282966f998f6SJosef Bacik 		 * there was a short read because we hit EOF, go ahead
283066f998f6SJosef Bacik 		 * and return.  Otherwise fallthrough to buffered io for
2831fbbbad4bSMatthew Wilcox 		 * the rest of the read.  Buffered reads will not work for
2832fbbbad4bSMatthew Wilcox 		 * DAX files, so don't bother trying.
283366f998f6SJosef Bacik 		 */
283461d0017eSJens Axboe 		if (retval < 0 || !count || IS_DAX(inode))
283561d0017eSJens Axboe 			return retval;
283661d0017eSJens Axboe 		if (iocb->ki_pos >= i_size_read(inode))
2837826ea860SChristoph Hellwig 			return retval;
28381da177e4SLinus Torvalds 	}
28391da177e4SLinus Torvalds 
2840826ea860SChristoph Hellwig 	return filemap_read(iocb, iter, retval);
28411da177e4SLinus Torvalds }
2842ed978a81SAl Viro EXPORT_SYMBOL(generic_file_read_iter);
28431da177e4SLinus Torvalds 
284407073eb0SDavid Howells /*
284507073eb0SDavid Howells  * Splice subpages from a folio into a pipe.
284607073eb0SDavid Howells  */
splice_folio_into_pipe(struct pipe_inode_info * pipe,struct folio * folio,loff_t fpos,size_t size)284707073eb0SDavid Howells size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
284807073eb0SDavid Howells 			      struct folio *folio, loff_t fpos, size_t size)
284907073eb0SDavid Howells {
285007073eb0SDavid Howells 	struct page *page;
285107073eb0SDavid Howells 	size_t spliced = 0, offset = offset_in_folio(folio, fpos);
285207073eb0SDavid Howells 
285307073eb0SDavid Howells 	page = folio_page(folio, offset / PAGE_SIZE);
285407073eb0SDavid Howells 	size = min(size, folio_size(folio) - offset);
285507073eb0SDavid Howells 	offset %= PAGE_SIZE;
285607073eb0SDavid Howells 
285707073eb0SDavid Howells 	while (spliced < size &&
285807073eb0SDavid Howells 	       !pipe_full(pipe->head, pipe->tail, pipe->max_usage)) {
285907073eb0SDavid Howells 		struct pipe_buffer *buf = pipe_head_buf(pipe);
286007073eb0SDavid Howells 		size_t part = min_t(size_t, PAGE_SIZE - offset, size - spliced);
286107073eb0SDavid Howells 
286207073eb0SDavid Howells 		*buf = (struct pipe_buffer) {
286307073eb0SDavid Howells 			.ops	= &page_cache_pipe_buf_ops,
286407073eb0SDavid Howells 			.page	= page,
286507073eb0SDavid Howells 			.offset	= offset,
286607073eb0SDavid Howells 			.len	= part,
286707073eb0SDavid Howells 		};
286807073eb0SDavid Howells 		folio_get(folio);
286907073eb0SDavid Howells 		pipe->head++;
287007073eb0SDavid Howells 		page++;
287107073eb0SDavid Howells 		spliced += part;
287207073eb0SDavid Howells 		offset = 0;
287307073eb0SDavid Howells 	}
287407073eb0SDavid Howells 
287507073eb0SDavid Howells 	return spliced;
287607073eb0SDavid Howells }
287707073eb0SDavid Howells 
28789eee8bd8SDavid Howells /**
28799eee8bd8SDavid Howells  * filemap_splice_read -  Splice data from a file's pagecache into a pipe
28809eee8bd8SDavid Howells  * @in: The file to read from
28819eee8bd8SDavid Howells  * @ppos: Pointer to the file position to read from
28829eee8bd8SDavid Howells  * @pipe: The pipe to splice into
28839eee8bd8SDavid Howells  * @len: The amount to splice
28849eee8bd8SDavid Howells  * @flags: The SPLICE_F_* flags
28859eee8bd8SDavid Howells  *
28869eee8bd8SDavid Howells  * This function gets folios from a file's pagecache and splices them into the
28879eee8bd8SDavid Howells  * pipe.  Readahead will be called as necessary to fill more folios.  This may
28889eee8bd8SDavid Howells  * be used for blockdevs also.
28899eee8bd8SDavid Howells  *
28909eee8bd8SDavid Howells  * Return: On success, the number of bytes read will be returned and *@ppos
28919eee8bd8SDavid Howells  * will be updated if appropriate; 0 will be returned if there is no more data
28929eee8bd8SDavid Howells  * to be read; -EAGAIN will be returned if the pipe had no space, and some
28939eee8bd8SDavid Howells  * other negative error code will be returned on error.  A short read may occur
28949eee8bd8SDavid Howells  * if the pipe has insufficient space, we reach the end of the data or we hit a
28959eee8bd8SDavid Howells  * hole.
289607073eb0SDavid Howells  */
filemap_splice_read(struct file * in,loff_t * ppos,struct pipe_inode_info * pipe,size_t len,unsigned int flags)289707073eb0SDavid Howells ssize_t filemap_splice_read(struct file *in, loff_t *ppos,
289807073eb0SDavid Howells 			    struct pipe_inode_info *pipe,
289907073eb0SDavid Howells 			    size_t len, unsigned int flags)
290007073eb0SDavid Howells {
290107073eb0SDavid Howells 	struct folio_batch fbatch;
290207073eb0SDavid Howells 	struct kiocb iocb;
290307073eb0SDavid Howells 	size_t total_spliced = 0, used, npages;
290407073eb0SDavid Howells 	loff_t isize, end_offset;
290507073eb0SDavid Howells 	bool writably_mapped;
290607073eb0SDavid Howells 	int i, error = 0;
290707073eb0SDavid Howells 
290883aeff88SDavid Howells 	if (unlikely(*ppos >= in->f_mapping->host->i_sb->s_maxbytes))
290983aeff88SDavid Howells 		return 0;
291083aeff88SDavid Howells 
291107073eb0SDavid Howells 	init_sync_kiocb(&iocb, in);
291207073eb0SDavid Howells 	iocb.ki_pos = *ppos;
291307073eb0SDavid Howells 
291407073eb0SDavid Howells 	/* Work out how much data we can actually add into the pipe */
291507073eb0SDavid Howells 	used = pipe_occupancy(pipe->head, pipe->tail);
291607073eb0SDavid Howells 	npages = max_t(ssize_t, pipe->max_usage - used, 0);
291707073eb0SDavid Howells 	len = min_t(size_t, len, npages * PAGE_SIZE);
291807073eb0SDavid Howells 
291907073eb0SDavid Howells 	folio_batch_init(&fbatch);
292007073eb0SDavid Howells 
292107073eb0SDavid Howells 	do {
292207073eb0SDavid Howells 		cond_resched();
292307073eb0SDavid Howells 
2924c3722208SDavid Howells 		if (*ppos >= i_size_read(in->f_mapping->host))
292507073eb0SDavid Howells 			break;
292607073eb0SDavid Howells 
292707073eb0SDavid Howells 		iocb.ki_pos = *ppos;
292807073eb0SDavid Howells 		error = filemap_get_pages(&iocb, len, &fbatch, true);
292907073eb0SDavid Howells 		if (error < 0)
293007073eb0SDavid Howells 			break;
293107073eb0SDavid Howells 
293207073eb0SDavid Howells 		/*
293307073eb0SDavid Howells 		 * i_size must be checked after we know the pages are Uptodate.
293407073eb0SDavid Howells 		 *
293507073eb0SDavid Howells 		 * Checking i_size after the check allows us to calculate
293607073eb0SDavid Howells 		 * the correct value for "nr", which means the zero-filled
293707073eb0SDavid Howells 		 * part of the page is not copied back to userspace (unless
293807073eb0SDavid Howells 		 * another truncate extends the file - this is desired though).
293907073eb0SDavid Howells 		 */
2940c3722208SDavid Howells 		isize = i_size_read(in->f_mapping->host);
294107073eb0SDavid Howells 		if (unlikely(*ppos >= isize))
294207073eb0SDavid Howells 			break;
294307073eb0SDavid Howells 		end_offset = min_t(loff_t, isize, *ppos + len);
294407073eb0SDavid Howells 
294507073eb0SDavid Howells 		/*
294607073eb0SDavid Howells 		 * Once we start copying data, we don't want to be touching any
294707073eb0SDavid Howells 		 * cachelines that might be contended:
294807073eb0SDavid Howells 		 */
294907073eb0SDavid Howells 		writably_mapped = mapping_writably_mapped(in->f_mapping);
295007073eb0SDavid Howells 
295107073eb0SDavid Howells 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
295207073eb0SDavid Howells 			struct folio *folio = fbatch.folios[i];
295307073eb0SDavid Howells 			size_t n;
295407073eb0SDavid Howells 
295507073eb0SDavid Howells 			if (folio_pos(folio) >= end_offset)
295607073eb0SDavid Howells 				goto out;
295707073eb0SDavid Howells 			folio_mark_accessed(folio);
295807073eb0SDavid Howells 
295907073eb0SDavid Howells 			/*
296007073eb0SDavid Howells 			 * If users can be writing to this folio using arbitrary
296107073eb0SDavid Howells 			 * virtual addresses, take care of potential aliasing
296207073eb0SDavid Howells 			 * before reading the folio on the kernel side.
296307073eb0SDavid Howells 			 */
296407073eb0SDavid Howells 			if (writably_mapped)
296507073eb0SDavid Howells 				flush_dcache_folio(folio);
296607073eb0SDavid Howells 
296707073eb0SDavid Howells 			n = min_t(loff_t, len, isize - *ppos);
296807073eb0SDavid Howells 			n = splice_folio_into_pipe(pipe, folio, *ppos, n);
296907073eb0SDavid Howells 			if (!n)
297007073eb0SDavid Howells 				goto out;
297107073eb0SDavid Howells 			len -= n;
297207073eb0SDavid Howells 			total_spliced += n;
297307073eb0SDavid Howells 			*ppos += n;
297407073eb0SDavid Howells 			in->f_ra.prev_pos = *ppos;
297507073eb0SDavid Howells 			if (pipe_full(pipe->head, pipe->tail, pipe->max_usage))
297607073eb0SDavid Howells 				goto out;
297707073eb0SDavid Howells 		}
297807073eb0SDavid Howells 
297907073eb0SDavid Howells 		folio_batch_release(&fbatch);
298007073eb0SDavid Howells 	} while (len);
298107073eb0SDavid Howells 
298207073eb0SDavid Howells out:
298307073eb0SDavid Howells 	folio_batch_release(&fbatch);
298407073eb0SDavid Howells 	file_accessed(in);
298507073eb0SDavid Howells 
298607073eb0SDavid Howells 	return total_spliced ? total_spliced : error;
298707073eb0SDavid Howells }
29887c8e01ebSDavid Howells EXPORT_SYMBOL(filemap_splice_read);
298907073eb0SDavid Howells 
folio_seek_hole_data(struct xa_state * xas,struct address_space * mapping,struct folio * folio,loff_t start,loff_t end,bool seek_data)2990f5e6429aSMatthew Wilcox (Oracle) static inline loff_t folio_seek_hole_data(struct xa_state *xas,
2991f5e6429aSMatthew Wilcox (Oracle) 		struct address_space *mapping, struct folio *folio,
299254fa39acSMatthew Wilcox (Oracle) 		loff_t start, loff_t end, bool seek_data)
299341139aa4SMatthew Wilcox (Oracle) {
299454fa39acSMatthew Wilcox (Oracle) 	const struct address_space_operations *ops = mapping->a_ops;
299554fa39acSMatthew Wilcox (Oracle) 	size_t offset, bsz = i_blocksize(mapping->host);
299654fa39acSMatthew Wilcox (Oracle) 
2997f5e6429aSMatthew Wilcox (Oracle) 	if (xa_is_value(folio) || folio_test_uptodate(folio))
299854fa39acSMatthew Wilcox (Oracle) 		return seek_data ? start : end;
299954fa39acSMatthew Wilcox (Oracle) 	if (!ops->is_partially_uptodate)
300054fa39acSMatthew Wilcox (Oracle) 		return seek_data ? end : start;
300154fa39acSMatthew Wilcox (Oracle) 
300254fa39acSMatthew Wilcox (Oracle) 	xas_pause(xas);
300354fa39acSMatthew Wilcox (Oracle) 	rcu_read_unlock();
3004f5e6429aSMatthew Wilcox (Oracle) 	folio_lock(folio);
3005f5e6429aSMatthew Wilcox (Oracle) 	if (unlikely(folio->mapping != mapping))
300654fa39acSMatthew Wilcox (Oracle) 		goto unlock;
300754fa39acSMatthew Wilcox (Oracle) 
3008f5e6429aSMatthew Wilcox (Oracle) 	offset = offset_in_folio(folio, start) & ~(bsz - 1);
300954fa39acSMatthew Wilcox (Oracle) 
301054fa39acSMatthew Wilcox (Oracle) 	do {
30112e7e80f7SMatthew Wilcox (Oracle) 		if (ops->is_partially_uptodate(folio, offset, bsz) ==
3012f5e6429aSMatthew Wilcox (Oracle) 							seek_data)
301354fa39acSMatthew Wilcox (Oracle) 			break;
301454fa39acSMatthew Wilcox (Oracle) 		start = (start + bsz) & ~(bsz - 1);
301554fa39acSMatthew Wilcox (Oracle) 		offset += bsz;
3016f5e6429aSMatthew Wilcox (Oracle) 	} while (offset < folio_size(folio));
301754fa39acSMatthew Wilcox (Oracle) unlock:
3018f5e6429aSMatthew Wilcox (Oracle) 	folio_unlock(folio);
301954fa39acSMatthew Wilcox (Oracle) 	rcu_read_lock();
302054fa39acSMatthew Wilcox (Oracle) 	return start;
302141139aa4SMatthew Wilcox (Oracle) }
302241139aa4SMatthew Wilcox (Oracle) 
seek_folio_size(struct xa_state * xas,struct folio * folio)3023f5e6429aSMatthew Wilcox (Oracle) static inline size_t seek_folio_size(struct xa_state *xas, struct folio *folio)
302441139aa4SMatthew Wilcox (Oracle) {
3025f5e6429aSMatthew Wilcox (Oracle) 	if (xa_is_value(folio))
302641139aa4SMatthew Wilcox (Oracle) 		return PAGE_SIZE << xa_get_order(xas->xa, xas->xa_index);
3027f5e6429aSMatthew Wilcox (Oracle) 	return folio_size(folio);
302841139aa4SMatthew Wilcox (Oracle) }
302941139aa4SMatthew Wilcox (Oracle) 
303041139aa4SMatthew Wilcox (Oracle) /**
303141139aa4SMatthew Wilcox (Oracle)  * mapping_seek_hole_data - Seek for SEEK_DATA / SEEK_HOLE in the page cache.
303241139aa4SMatthew Wilcox (Oracle)  * @mapping: Address space to search.
303341139aa4SMatthew Wilcox (Oracle)  * @start: First byte to consider.
303441139aa4SMatthew Wilcox (Oracle)  * @end: Limit of search (exclusive).
303541139aa4SMatthew Wilcox (Oracle)  * @whence: Either SEEK_HOLE or SEEK_DATA.
303641139aa4SMatthew Wilcox (Oracle)  *
303741139aa4SMatthew Wilcox (Oracle)  * If the page cache knows which blocks contain holes and which blocks
303841139aa4SMatthew Wilcox (Oracle)  * contain data, your filesystem can use this function to implement
303941139aa4SMatthew Wilcox (Oracle)  * SEEK_HOLE and SEEK_DATA.  This is useful for filesystems which are
304041139aa4SMatthew Wilcox (Oracle)  * entirely memory-based such as tmpfs, and filesystems which support
304141139aa4SMatthew Wilcox (Oracle)  * unwritten extents.
304241139aa4SMatthew Wilcox (Oracle)  *
3043f0953a1bSIngo Molnar  * Return: The requested offset on success, or -ENXIO if @whence specifies
304441139aa4SMatthew Wilcox (Oracle)  * SEEK_DATA and there is no data after @start.  There is an implicit hole
304541139aa4SMatthew Wilcox (Oracle)  * after @end - 1, so SEEK_HOLE returns @end if all the bytes between @start
304641139aa4SMatthew Wilcox (Oracle)  * and @end contain data.
304741139aa4SMatthew Wilcox (Oracle)  */
mapping_seek_hole_data(struct address_space * mapping,loff_t start,loff_t end,int whence)304841139aa4SMatthew Wilcox (Oracle) loff_t mapping_seek_hole_data(struct address_space *mapping, loff_t start,
304941139aa4SMatthew Wilcox (Oracle) 		loff_t end, int whence)
305041139aa4SMatthew Wilcox (Oracle) {
305141139aa4SMatthew Wilcox (Oracle) 	XA_STATE(xas, &mapping->i_pages, start >> PAGE_SHIFT);
3052ed98b015SHugh Dickins 	pgoff_t max = (end - 1) >> PAGE_SHIFT;
305341139aa4SMatthew Wilcox (Oracle) 	bool seek_data = (whence == SEEK_DATA);
3054f5e6429aSMatthew Wilcox (Oracle) 	struct folio *folio;
305541139aa4SMatthew Wilcox (Oracle) 
305641139aa4SMatthew Wilcox (Oracle) 	if (end <= start)
305741139aa4SMatthew Wilcox (Oracle) 		return -ENXIO;
305841139aa4SMatthew Wilcox (Oracle) 
305941139aa4SMatthew Wilcox (Oracle) 	rcu_read_lock();
3060f5e6429aSMatthew Wilcox (Oracle) 	while ((folio = find_get_entry(&xas, max, XA_PRESENT))) {
3061ed98b015SHugh Dickins 		loff_t pos = (u64)xas.xa_index << PAGE_SHIFT;
3062f5e6429aSMatthew Wilcox (Oracle) 		size_t seek_size;
306341139aa4SMatthew Wilcox (Oracle) 
306441139aa4SMatthew Wilcox (Oracle) 		if (start < pos) {
306541139aa4SMatthew Wilcox (Oracle) 			if (!seek_data)
306641139aa4SMatthew Wilcox (Oracle) 				goto unlock;
306741139aa4SMatthew Wilcox (Oracle) 			start = pos;
306841139aa4SMatthew Wilcox (Oracle) 		}
306941139aa4SMatthew Wilcox (Oracle) 
3070f5e6429aSMatthew Wilcox (Oracle) 		seek_size = seek_folio_size(&xas, folio);
3071f5e6429aSMatthew Wilcox (Oracle) 		pos = round_up((u64)pos + 1, seek_size);
3072f5e6429aSMatthew Wilcox (Oracle) 		start = folio_seek_hole_data(&xas, mapping, folio, start, pos,
307354fa39acSMatthew Wilcox (Oracle) 				seek_data);
307454fa39acSMatthew Wilcox (Oracle) 		if (start < pos)
307541139aa4SMatthew Wilcox (Oracle) 			goto unlock;
3076ed98b015SHugh Dickins 		if (start >= end)
3077ed98b015SHugh Dickins 			break;
3078ed98b015SHugh Dickins 		if (seek_size > PAGE_SIZE)
3079ed98b015SHugh Dickins 			xas_set(&xas, pos >> PAGE_SHIFT);
3080f5e6429aSMatthew Wilcox (Oracle) 		if (!xa_is_value(folio))
3081f5e6429aSMatthew Wilcox (Oracle) 			folio_put(folio);
308241139aa4SMatthew Wilcox (Oracle) 	}
308341139aa4SMatthew Wilcox (Oracle) 	if (seek_data)
3084ed98b015SHugh Dickins 		start = -ENXIO;
308541139aa4SMatthew Wilcox (Oracle) unlock:
308641139aa4SMatthew Wilcox (Oracle) 	rcu_read_unlock();
3087f5e6429aSMatthew Wilcox (Oracle) 	if (folio && !xa_is_value(folio))
3088f5e6429aSMatthew Wilcox (Oracle) 		folio_put(folio);
308941139aa4SMatthew Wilcox (Oracle) 	if (start > end)
309041139aa4SMatthew Wilcox (Oracle) 		return end;
309141139aa4SMatthew Wilcox (Oracle) 	return start;
309241139aa4SMatthew Wilcox (Oracle) }
309341139aa4SMatthew Wilcox (Oracle) 
30941da177e4SLinus Torvalds #ifdef CONFIG_MMU
30951da177e4SLinus Torvalds #define MMAP_LOTSAMISS  (100)
30966b4c9f44SJosef Bacik /*
3097e292e6d6SMatthew Wilcox (Oracle)  * lock_folio_maybe_drop_mmap - lock the page, possibly dropping the mmap_lock
30986b4c9f44SJosef Bacik  * @vmf - the vm_fault for this fault.
3099e292e6d6SMatthew Wilcox (Oracle)  * @folio - the folio to lock.
31006b4c9f44SJosef Bacik  * @fpin - the pointer to the file we may pin (or is already pinned).
31016b4c9f44SJosef Bacik  *
3102e292e6d6SMatthew Wilcox (Oracle)  * This works similar to lock_folio_or_retry in that it can drop the
3103e292e6d6SMatthew Wilcox (Oracle)  * mmap_lock.  It differs in that it actually returns the folio locked
3104e292e6d6SMatthew Wilcox (Oracle)  * if it returns 1 and 0 if it couldn't lock the folio.  If we did have
3105e292e6d6SMatthew Wilcox (Oracle)  * to drop the mmap_lock then fpin will point to the pinned file and
3106e292e6d6SMatthew Wilcox (Oracle)  * needs to be fput()'ed at a later point.
31076b4c9f44SJosef Bacik  */
lock_folio_maybe_drop_mmap(struct vm_fault * vmf,struct folio * folio,struct file ** fpin)3108e292e6d6SMatthew Wilcox (Oracle) static int lock_folio_maybe_drop_mmap(struct vm_fault *vmf, struct folio *folio,
31096b4c9f44SJosef Bacik 				     struct file **fpin)
31106b4c9f44SJosef Bacik {
31117c23c782SMatthew Wilcox (Oracle) 	if (folio_trylock(folio))
31126b4c9f44SJosef Bacik 		return 1;
31136b4c9f44SJosef Bacik 
31148b0f9fa2SLinus Torvalds 	/*
31158b0f9fa2SLinus Torvalds 	 * NOTE! This will make us return with VM_FAULT_RETRY, but with
3116c1e8d7c6SMichel Lespinasse 	 * the mmap_lock still held. That's how FAULT_FLAG_RETRY_NOWAIT
31178b0f9fa2SLinus Torvalds 	 * is supposed to work. We have way too many special cases..
31188b0f9fa2SLinus Torvalds 	 */
31196b4c9f44SJosef Bacik 	if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
31206b4c9f44SJosef Bacik 		return 0;
31216b4c9f44SJosef Bacik 
31226b4c9f44SJosef Bacik 	*fpin = maybe_unlock_mmap_for_io(vmf, *fpin);
31236b4c9f44SJosef Bacik 	if (vmf->flags & FAULT_FLAG_KILLABLE) {
3124af7f29d9SMatthew Wilcox (Oracle) 		if (__folio_lock_killable(folio)) {
31256b4c9f44SJosef Bacik 			/*
3126c1e8d7c6SMichel Lespinasse 			 * We didn't have the right flags to drop the mmap_lock,
31276b4c9f44SJosef Bacik 			 * but all fault_handlers only check for fatal signals
31286b4c9f44SJosef Bacik 			 * if we return VM_FAULT_RETRY, so we need to drop the
3129c1e8d7c6SMichel Lespinasse 			 * mmap_lock here and return 0 if we don't have a fpin.
31306b4c9f44SJosef Bacik 			 */
31316b4c9f44SJosef Bacik 			if (*fpin == NULL)
3132d8ed45c5SMichel Lespinasse 				mmap_read_unlock(vmf->vma->vm_mm);
31336b4c9f44SJosef Bacik 			return 0;
31346b4c9f44SJosef Bacik 		}
31356b4c9f44SJosef Bacik 	} else
31367c23c782SMatthew Wilcox (Oracle) 		__folio_lock(folio);
31377c23c782SMatthew Wilcox (Oracle) 
31386b4c9f44SJosef Bacik 	return 1;
31396b4c9f44SJosef Bacik }
31406b4c9f44SJosef Bacik 
31416b4c9f44SJosef Bacik /*
31426b4c9f44SJosef Bacik  * Synchronous readahead happens when we don't even find a page in the page
31436b4c9f44SJosef Bacik  * cache at all.  We don't want to perform IO under the mmap sem, so if we have
31446b4c9f44SJosef Bacik  * to drop the mmap sem we return the file that was pinned in order for us to do
31456b4c9f44SJosef Bacik  * that.  If we didn't pin a file then we return NULL.  The file that is
31466b4c9f44SJosef Bacik  * returned needs to be fput()'ed when we're done with it.
31476b4c9f44SJosef Bacik  */
do_sync_mmap_readahead(struct vm_fault * vmf)31486b4c9f44SJosef Bacik static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)
3149ef00e08eSLinus Torvalds {
31502a1180f1SJosef Bacik 	struct file *file = vmf->vma->vm_file;
31512a1180f1SJosef Bacik 	struct file_ra_state *ra = &file->f_ra;
3152ef00e08eSLinus Torvalds 	struct address_space *mapping = file->f_mapping;
3153fcd9ae4fSMatthew Wilcox (Oracle) 	DEFINE_READAHEAD(ractl, file, ra, mapping, vmf->pgoff);
31546b4c9f44SJosef Bacik 	struct file *fpin = NULL;
3155dcfa24baSMatthew Wilcox (Oracle) 	unsigned long vm_flags = vmf->vma->vm_flags;
3156e630bfacSKirill A. Shutemov 	unsigned int mmap_miss;
3157ef00e08eSLinus Torvalds 
31584687fdbbSMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
31594687fdbbSMatthew Wilcox (Oracle) 	/* Use the readahead code, even if readahead is disabled */
3160dcfa24baSMatthew Wilcox (Oracle) 	if (vm_flags & VM_HUGEPAGE) {
31614687fdbbSMatthew Wilcox (Oracle) 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
31624687fdbbSMatthew Wilcox (Oracle) 		ractl._index &= ~((unsigned long)HPAGE_PMD_NR - 1);
31634687fdbbSMatthew Wilcox (Oracle) 		ra->size = HPAGE_PMD_NR;
31644687fdbbSMatthew Wilcox (Oracle) 		/*
31654687fdbbSMatthew Wilcox (Oracle) 		 * Fetch two PMD folios, so we get the chance to actually
31664687fdbbSMatthew Wilcox (Oracle) 		 * readahead, unless we've been told not to.
31674687fdbbSMatthew Wilcox (Oracle) 		 */
3168dcfa24baSMatthew Wilcox (Oracle) 		if (!(vm_flags & VM_RAND_READ))
31694687fdbbSMatthew Wilcox (Oracle) 			ra->size *= 2;
31704687fdbbSMatthew Wilcox (Oracle) 		ra->async_size = HPAGE_PMD_NR;
31714687fdbbSMatthew Wilcox (Oracle) 		page_cache_ra_order(&ractl, ra, HPAGE_PMD_ORDER);
31724687fdbbSMatthew Wilcox (Oracle) 		return fpin;
31734687fdbbSMatthew Wilcox (Oracle) 	}
31744687fdbbSMatthew Wilcox (Oracle) #endif
31754687fdbbSMatthew Wilcox (Oracle) 
3176ef00e08eSLinus Torvalds 	/* If we don't want any read-ahead, don't bother */
3177dcfa24baSMatthew Wilcox (Oracle) 	if (vm_flags & VM_RAND_READ)
31786b4c9f44SJosef Bacik 		return fpin;
3179275b12bfSWu Fengguang 	if (!ra->ra_pages)
31806b4c9f44SJosef Bacik 		return fpin;
3181ef00e08eSLinus Torvalds 
3182dcfa24baSMatthew Wilcox (Oracle) 	if (vm_flags & VM_SEQ_READ) {
31836b4c9f44SJosef Bacik 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3184fcd9ae4fSMatthew Wilcox (Oracle) 		page_cache_sync_ra(&ractl, ra->ra_pages);
31856b4c9f44SJosef Bacik 		return fpin;
3186ef00e08eSLinus Torvalds 	}
3187ef00e08eSLinus Torvalds 
3188207d04baSAndi Kleen 	/* Avoid banging the cache line if not needed */
3189e630bfacSKirill A. Shutemov 	mmap_miss = READ_ONCE(ra->mmap_miss);
3190e630bfacSKirill A. Shutemov 	if (mmap_miss < MMAP_LOTSAMISS * 10)
3191e630bfacSKirill A. Shutemov 		WRITE_ONCE(ra->mmap_miss, ++mmap_miss);
3192ef00e08eSLinus Torvalds 
3193ef00e08eSLinus Torvalds 	/*
3194ef00e08eSLinus Torvalds 	 * Do we miss much more than hit in this file? If so,
3195ef00e08eSLinus Torvalds 	 * stop bothering with read-ahead. It will only hurt.
3196ef00e08eSLinus Torvalds 	 */
3197e630bfacSKirill A. Shutemov 	if (mmap_miss > MMAP_LOTSAMISS)
31986b4c9f44SJosef Bacik 		return fpin;
3199ef00e08eSLinus Torvalds 
3200d30a1100SWu Fengguang 	/*
3201d30a1100SWu Fengguang 	 * mmap read-around
3202d30a1100SWu Fengguang 	 */
32036b4c9f44SJosef Bacik 	fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3204db660d46SDavid Howells 	ra->start = max_t(long, 0, vmf->pgoff - ra->ra_pages / 2);
3205600e19afSRoman Gushchin 	ra->size = ra->ra_pages;
3206600e19afSRoman Gushchin 	ra->async_size = ra->ra_pages / 4;
3207db660d46SDavid Howells 	ractl._index = ra->start;
320856a4d67cSMatthew Wilcox (Oracle) 	page_cache_ra_order(&ractl, ra, 0);
32096b4c9f44SJosef Bacik 	return fpin;
3210ef00e08eSLinus Torvalds }
3211ef00e08eSLinus Torvalds 
3212ef00e08eSLinus Torvalds /*
3213ef00e08eSLinus Torvalds  * Asynchronous readahead happens when we find the page and PG_readahead,
32146b4c9f44SJosef Bacik  * so we want to possibly extend the readahead further.  We return the file that
3215c1e8d7c6SMichel Lespinasse  * was pinned if we have to drop the mmap_lock in order to do IO.
3216ef00e08eSLinus Torvalds  */
do_async_mmap_readahead(struct vm_fault * vmf,struct folio * folio)32176b4c9f44SJosef Bacik static struct file *do_async_mmap_readahead(struct vm_fault *vmf,
321879598cedSMatthew Wilcox (Oracle) 					    struct folio *folio)
3219ef00e08eSLinus Torvalds {
32202a1180f1SJosef Bacik 	struct file *file = vmf->vma->vm_file;
32212a1180f1SJosef Bacik 	struct file_ra_state *ra = &file->f_ra;
322279598cedSMatthew Wilcox (Oracle) 	DEFINE_READAHEAD(ractl, file, ra, file->f_mapping, vmf->pgoff);
32236b4c9f44SJosef Bacik 	struct file *fpin = NULL;
3224e630bfacSKirill A. Shutemov 	unsigned int mmap_miss;
3225ef00e08eSLinus Torvalds 
3226ef00e08eSLinus Torvalds 	/* If we don't want any read-ahead, don't bother */
32275c72feeeSJan Kara 	if (vmf->vma->vm_flags & VM_RAND_READ || !ra->ra_pages)
32286b4c9f44SJosef Bacik 		return fpin;
322979598cedSMatthew Wilcox (Oracle) 
3230e630bfacSKirill A. Shutemov 	mmap_miss = READ_ONCE(ra->mmap_miss);
3231e630bfacSKirill A. Shutemov 	if (mmap_miss)
3232e630bfacSKirill A. Shutemov 		WRITE_ONCE(ra->mmap_miss, --mmap_miss);
323379598cedSMatthew Wilcox (Oracle) 
323479598cedSMatthew Wilcox (Oracle) 	if (folio_test_readahead(folio)) {
32356b4c9f44SJosef Bacik 		fpin = maybe_unlock_mmap_for_io(vmf, fpin);
323679598cedSMatthew Wilcox (Oracle) 		page_cache_async_ra(&ractl, folio, ra->ra_pages);
3237ef00e08eSLinus Torvalds 	}
32386b4c9f44SJosef Bacik 	return fpin;
32396b4c9f44SJosef Bacik }
3240ef00e08eSLinus Torvalds 
3241485bb99bSRandy Dunlap /**
324254cb8821SNick Piggin  * filemap_fault - read in file data for page fault handling
3243d0217ac0SNick Piggin  * @vmf:	struct vm_fault containing details of the fault
3244485bb99bSRandy Dunlap  *
324554cb8821SNick Piggin  * filemap_fault() is invoked via the vma operations vector for a
32461da177e4SLinus Torvalds  * mapped memory region to read in file data during a page fault.
32471da177e4SLinus Torvalds  *
32481da177e4SLinus Torvalds  * The goto's are kind of ugly, but this streamlines the normal case of having
32491da177e4SLinus Torvalds  * it in the page cache, and handles the special cases reasonably without
32501da177e4SLinus Torvalds  * having a lot of duplicated code.
32519a95f3cfSPaul Cassella  *
3252c1e8d7c6SMichel Lespinasse  * vma->vm_mm->mmap_lock must be held on entry.
32539a95f3cfSPaul Cassella  *
3254c1e8d7c6SMichel Lespinasse  * If our return value has VM_FAULT_RETRY set, it's because the mmap_lock
3255e292e6d6SMatthew Wilcox (Oracle)  * may be dropped before doing I/O or by lock_folio_maybe_drop_mmap().
32569a95f3cfSPaul Cassella  *
3257c1e8d7c6SMichel Lespinasse  * If our return value does not have VM_FAULT_RETRY set, the mmap_lock
32589a95f3cfSPaul Cassella  * has not been released.
32599a95f3cfSPaul Cassella  *
32609a95f3cfSPaul Cassella  * We never return with VM_FAULT_RETRY and a bit from VM_FAULT_ERROR set.
3261a862f68aSMike Rapoport  *
3262a862f68aSMike Rapoport  * Return: bitwise-OR of %VM_FAULT_ codes.
32631da177e4SLinus Torvalds  */
filemap_fault(struct vm_fault * vmf)32642bcd6454SSouptick Joarder vm_fault_t filemap_fault(struct vm_fault *vmf)
32651da177e4SLinus Torvalds {
32661da177e4SLinus Torvalds 	int error;
326711bac800SDave Jiang 	struct file *file = vmf->vma->vm_file;
32686b4c9f44SJosef Bacik 	struct file *fpin = NULL;
32691da177e4SLinus Torvalds 	struct address_space *mapping = file->f_mapping;
32701da177e4SLinus Torvalds 	struct inode *inode = mapping->host;
3271e292e6d6SMatthew Wilcox (Oracle) 	pgoff_t max_idx, index = vmf->pgoff;
3272e292e6d6SMatthew Wilcox (Oracle) 	struct folio *folio;
32732bcd6454SSouptick Joarder 	vm_fault_t ret = 0;
3274730633f0SJan Kara 	bool mapping_locked = false;
32751da177e4SLinus Torvalds 
3276e292e6d6SMatthew Wilcox (Oracle) 	max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3277e292e6d6SMatthew Wilcox (Oracle) 	if (unlikely(index >= max_idx))
32785307cc1aSLinus Torvalds 		return VM_FAULT_SIGBUS;
32791da177e4SLinus Torvalds 
32801da177e4SLinus Torvalds 	/*
328149426420SJohannes Weiner 	 * Do we have something in the page cache already?
32821da177e4SLinus Torvalds 	 */
3283e292e6d6SMatthew Wilcox (Oracle) 	folio = filemap_get_folio(mapping, index);
328466dabbb6SChristoph Hellwig 	if (likely(!IS_ERR(folio))) {
32853ea89ee8SFengguang Wu 		/*
3286730633f0SJan Kara 		 * We found the page, so try async readahead before waiting for
3287730633f0SJan Kara 		 * the lock.
32883ea89ee8SFengguang Wu 		 */
3289730633f0SJan Kara 		if (!(vmf->flags & FAULT_FLAG_TRIED))
329079598cedSMatthew Wilcox (Oracle) 			fpin = do_async_mmap_readahead(vmf, folio);
3291e292e6d6SMatthew Wilcox (Oracle) 		if (unlikely(!folio_test_uptodate(folio))) {
3292730633f0SJan Kara 			filemap_invalidate_lock_shared(mapping);
3293730633f0SJan Kara 			mapping_locked = true;
3294730633f0SJan Kara 		}
3295730633f0SJan Kara 	} else {
3296ef00e08eSLinus Torvalds 		/* No page in the page cache at all */
3297f8891e5eSChristoph Lameter 		count_vm_event(PGMAJFAULT);
32982262185cSRoman Gushchin 		count_memcg_event_mm(vmf->vma->vm_mm, PGMAJFAULT);
3299ef00e08eSLinus Torvalds 		ret = VM_FAULT_MAJOR;
33006b4c9f44SJosef Bacik 		fpin = do_sync_mmap_readahead(vmf);
3301ef00e08eSLinus Torvalds retry_find:
3302730633f0SJan Kara 		/*
3303e292e6d6SMatthew Wilcox (Oracle) 		 * See comment in filemap_create_folio() why we need
3304730633f0SJan Kara 		 * invalidate_lock
3305730633f0SJan Kara 		 */
3306730633f0SJan Kara 		if (!mapping_locked) {
3307730633f0SJan Kara 			filemap_invalidate_lock_shared(mapping);
3308730633f0SJan Kara 			mapping_locked = true;
3309730633f0SJan Kara 		}
3310e292e6d6SMatthew Wilcox (Oracle) 		folio = __filemap_get_folio(mapping, index,
3311a75d4c33SJosef Bacik 					  FGP_CREAT|FGP_FOR_MMAP,
3312a75d4c33SJosef Bacik 					  vmf->gfp_mask);
331366dabbb6SChristoph Hellwig 		if (IS_ERR(folio)) {
33146b4c9f44SJosef Bacik 			if (fpin)
33156b4c9f44SJosef Bacik 				goto out_retry;
3316730633f0SJan Kara 			filemap_invalidate_unlock_shared(mapping);
3317e520e932SMatthew Wilcox (Oracle) 			return VM_FAULT_OOM;
33181da177e4SLinus Torvalds 		}
3319d88c0922SMichel Lespinasse 	}
3320b522c94dSMichel Lespinasse 
3321e292e6d6SMatthew Wilcox (Oracle) 	if (!lock_folio_maybe_drop_mmap(vmf, folio, &fpin))
33226b4c9f44SJosef Bacik 		goto out_retry;
33236b4c9f44SJosef Bacik 
3324b522c94dSMichel Lespinasse 	/* Did it get truncated? */
3325e292e6d6SMatthew Wilcox (Oracle) 	if (unlikely(folio->mapping != mapping)) {
3326e292e6d6SMatthew Wilcox (Oracle) 		folio_unlock(folio);
3327e292e6d6SMatthew Wilcox (Oracle) 		folio_put(folio);
3328b522c94dSMichel Lespinasse 		goto retry_find;
3329b522c94dSMichel Lespinasse 	}
3330e292e6d6SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_contains(folio, index), folio);
3331b522c94dSMichel Lespinasse 
33321da177e4SLinus Torvalds 	/*
3333d00806b1SNick Piggin 	 * We have a locked page in the page cache, now we need to check
3334d00806b1SNick Piggin 	 * that it's up-to-date. If not, it is going to be due to an error.
33351da177e4SLinus Torvalds 	 */
3336e292e6d6SMatthew Wilcox (Oracle) 	if (unlikely(!folio_test_uptodate(folio))) {
3337730633f0SJan Kara 		/*
3338730633f0SJan Kara 		 * The page was in cache and uptodate and now it is not.
3339730633f0SJan Kara 		 * Strange but possible since we didn't hold the page lock all
3340730633f0SJan Kara 		 * the time. Let's drop everything get the invalidate lock and
3341730633f0SJan Kara 		 * try again.
3342730633f0SJan Kara 		 */
3343730633f0SJan Kara 		if (!mapping_locked) {
3344e292e6d6SMatthew Wilcox (Oracle) 			folio_unlock(folio);
3345e292e6d6SMatthew Wilcox (Oracle) 			folio_put(folio);
3346730633f0SJan Kara 			goto retry_find;
3347730633f0SJan Kara 		}
33481da177e4SLinus Torvalds 		goto page_not_uptodate;
3349730633f0SJan Kara 	}
33501da177e4SLinus Torvalds 
3351ef00e08eSLinus Torvalds 	/*
3352c1e8d7c6SMichel Lespinasse 	 * We've made it this far and we had to drop our mmap_lock, now is the
33536b4c9f44SJosef Bacik 	 * time to return to the upper layer and have it re-find the vma and
33546b4c9f44SJosef Bacik 	 * redo the fault.
33556b4c9f44SJosef Bacik 	 */
33566b4c9f44SJosef Bacik 	if (fpin) {
3357e292e6d6SMatthew Wilcox (Oracle) 		folio_unlock(folio);
33586b4c9f44SJosef Bacik 		goto out_retry;
33596b4c9f44SJosef Bacik 	}
3360730633f0SJan Kara 	if (mapping_locked)
3361730633f0SJan Kara 		filemap_invalidate_unlock_shared(mapping);
33626b4c9f44SJosef Bacik 
33636b4c9f44SJosef Bacik 	/*
3364ef00e08eSLinus Torvalds 	 * Found the page and have a reference on it.
3365ef00e08eSLinus Torvalds 	 * We must recheck i_size under page lock.
3366ef00e08eSLinus Torvalds 	 */
3367e292e6d6SMatthew Wilcox (Oracle) 	max_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3368e292e6d6SMatthew Wilcox (Oracle) 	if (unlikely(index >= max_idx)) {
3369e292e6d6SMatthew Wilcox (Oracle) 		folio_unlock(folio);
3370e292e6d6SMatthew Wilcox (Oracle) 		folio_put(folio);
33715307cc1aSLinus Torvalds 		return VM_FAULT_SIGBUS;
3372d00806b1SNick Piggin 	}
3373d00806b1SNick Piggin 
3374e292e6d6SMatthew Wilcox (Oracle) 	vmf->page = folio_file_page(folio, index);
337583c54070SNick Piggin 	return ret | VM_FAULT_LOCKED;
33761da177e4SLinus Torvalds 
33771da177e4SLinus Torvalds page_not_uptodate:
33781da177e4SLinus Torvalds 	/*
33791da177e4SLinus Torvalds 	 * Umm, take care of errors if the page isn't up-to-date.
33801da177e4SLinus Torvalds 	 * Try to re-read it _once_. We do this synchronously,
33811da177e4SLinus Torvalds 	 * because there really aren't any performance issues here
33821da177e4SLinus Torvalds 	 * and we need to check for errors.
33831da177e4SLinus Torvalds 	 */
33846b4c9f44SJosef Bacik 	fpin = maybe_unlock_mmap_for_io(vmf, fpin);
3385290e1a32SMatthew Wilcox (Oracle) 	error = filemap_read_folio(file, mapping->a_ops->read_folio, folio);
33866b4c9f44SJosef Bacik 	if (fpin)
33876b4c9f44SJosef Bacik 		goto out_retry;
3388e292e6d6SMatthew Wilcox (Oracle) 	folio_put(folio);
33891da177e4SLinus Torvalds 
3390d00806b1SNick Piggin 	if (!error || error == AOP_TRUNCATED_PAGE)
3391d00806b1SNick Piggin 		goto retry_find;
3392730633f0SJan Kara 	filemap_invalidate_unlock_shared(mapping);
3393d00806b1SNick Piggin 
3394d0217ac0SNick Piggin 	return VM_FAULT_SIGBUS;
33956b4c9f44SJosef Bacik 
33966b4c9f44SJosef Bacik out_retry:
33976b4c9f44SJosef Bacik 	/*
3398c1e8d7c6SMichel Lespinasse 	 * We dropped the mmap_lock, we need to return to the fault handler to
33996b4c9f44SJosef Bacik 	 * re-find the vma and come back and find our hopefully still populated
34006b4c9f44SJosef Bacik 	 * page.
34016b4c9f44SJosef Bacik 	 */
340238a55db9SMatthew Wilcox 	if (!IS_ERR(folio))
3403e292e6d6SMatthew Wilcox (Oracle) 		folio_put(folio);
3404730633f0SJan Kara 	if (mapping_locked)
3405730633f0SJan Kara 		filemap_invalidate_unlock_shared(mapping);
34066b4c9f44SJosef Bacik 	if (fpin)
34076b4c9f44SJosef Bacik 		fput(fpin);
34086b4c9f44SJosef Bacik 	return ret | VM_FAULT_RETRY;
340954cb8821SNick Piggin }
341054cb8821SNick Piggin EXPORT_SYMBOL(filemap_fault);
341154cb8821SNick Piggin 
filemap_map_pmd(struct vm_fault * vmf,struct folio * folio,pgoff_t start)34128808ecabSMatthew Wilcox (Oracle) static bool filemap_map_pmd(struct vm_fault *vmf, struct folio *folio,
34138808ecabSMatthew Wilcox (Oracle) 		pgoff_t start)
3414f9ce0be7SKirill A. Shutemov {
3415f9ce0be7SKirill A. Shutemov 	struct mm_struct *mm = vmf->vma->vm_mm;
3416f9ce0be7SKirill A. Shutemov 
3417f9ce0be7SKirill A. Shutemov 	/* Huge page is mapped? No need to proceed. */
3418f9ce0be7SKirill A. Shutemov 	if (pmd_trans_huge(*vmf->pmd)) {
34198808ecabSMatthew Wilcox (Oracle) 		folio_unlock(folio);
34208808ecabSMatthew Wilcox (Oracle) 		folio_put(folio);
3421f9ce0be7SKirill A. Shutemov 		return true;
3422f9ce0be7SKirill A. Shutemov 	}
3423f9ce0be7SKirill A. Shutemov 
34248808ecabSMatthew Wilcox (Oracle) 	if (pmd_none(*vmf->pmd) && folio_test_pmd_mappable(folio)) {
34258808ecabSMatthew Wilcox (Oracle) 		struct page *page = folio_file_page(folio, start);
3426f9ce0be7SKirill A. Shutemov 		vm_fault_t ret = do_set_pmd(vmf, page);
3427f9ce0be7SKirill A. Shutemov 		if (!ret) {
3428f9ce0be7SKirill A. Shutemov 			/* The page is mapped successfully, reference consumed. */
34298808ecabSMatthew Wilcox (Oracle) 			folio_unlock(folio);
3430f9ce0be7SKirill A. Shutemov 			return true;
3431f9ce0be7SKirill A. Shutemov 		}
3432f9ce0be7SKirill A. Shutemov 	}
3433f9ce0be7SKirill A. Shutemov 
3434799f90c3SHugh Dickins 	if (pmd_none(*vmf->pmd) && vmf->prealloc_pte)
343503c4f204SQi Zheng 		pmd_install(mm, vmf->pmd, &vmf->prealloc_pte);
3436f9ce0be7SKirill A. Shutemov 
3437f9ce0be7SKirill A. Shutemov 	return false;
3438f9ce0be7SKirill A. Shutemov }
3439f9ce0be7SKirill A. Shutemov 
next_uptodate_folio(struct xa_state * xas,struct address_space * mapping,pgoff_t end_pgoff)3440de74976eSYin Fengwei static struct folio *next_uptodate_folio(struct xa_state *xas,
3441de74976eSYin Fengwei 		struct address_space *mapping, pgoff_t end_pgoff)
3442f9ce0be7SKirill A. Shutemov {
3443de74976eSYin Fengwei 	struct folio *folio = xas_next_entry(xas, end_pgoff);
3444f9ce0be7SKirill A. Shutemov 	unsigned long max_idx;
3445f9ce0be7SKirill A. Shutemov 
3446f9ce0be7SKirill A. Shutemov 	do {
34479184a307SMatthew Wilcox (Oracle) 		if (!folio)
3448f9ce0be7SKirill A. Shutemov 			return NULL;
34499184a307SMatthew Wilcox (Oracle) 		if (xas_retry(xas, folio))
3450f9ce0be7SKirill A. Shutemov 			continue;
34519184a307SMatthew Wilcox (Oracle) 		if (xa_is_value(folio))
3452f9ce0be7SKirill A. Shutemov 			continue;
34539184a307SMatthew Wilcox (Oracle) 		if (folio_test_locked(folio))
3454f9ce0be7SKirill A. Shutemov 			continue;
34559184a307SMatthew Wilcox (Oracle) 		if (!folio_try_get_rcu(folio))
3456f9ce0be7SKirill A. Shutemov 			continue;
3457f9ce0be7SKirill A. Shutemov 		/* Has the page moved or been split? */
34589184a307SMatthew Wilcox (Oracle) 		if (unlikely(folio != xas_reload(xas)))
3459f9ce0be7SKirill A. Shutemov 			goto skip;
34609184a307SMatthew Wilcox (Oracle) 		if (!folio_test_uptodate(folio) || folio_test_readahead(folio))
3461f9ce0be7SKirill A. Shutemov 			goto skip;
34629184a307SMatthew Wilcox (Oracle) 		if (!folio_trylock(folio))
3463f9ce0be7SKirill A. Shutemov 			goto skip;
34649184a307SMatthew Wilcox (Oracle) 		if (folio->mapping != mapping)
3465f9ce0be7SKirill A. Shutemov 			goto unlock;
34669184a307SMatthew Wilcox (Oracle) 		if (!folio_test_uptodate(folio))
3467f9ce0be7SKirill A. Shutemov 			goto unlock;
3468f9ce0be7SKirill A. Shutemov 		max_idx = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
3469f9ce0be7SKirill A. Shutemov 		if (xas->xa_index >= max_idx)
3470f9ce0be7SKirill A. Shutemov 			goto unlock;
3471820b05e9SMatthew Wilcox (Oracle) 		return folio;
3472f9ce0be7SKirill A. Shutemov unlock:
34739184a307SMatthew Wilcox (Oracle) 		folio_unlock(folio);
3474f9ce0be7SKirill A. Shutemov skip:
34759184a307SMatthew Wilcox (Oracle) 		folio_put(folio);
34769184a307SMatthew Wilcox (Oracle) 	} while ((folio = xas_next_entry(xas, end_pgoff)) != NULL);
3477f9ce0be7SKirill A. Shutemov 
3478f9ce0be7SKirill A. Shutemov 	return NULL;
3479f9ce0be7SKirill A. Shutemov }
3480f9ce0be7SKirill A. Shutemov 
3481de74976eSYin Fengwei /*
3482de74976eSYin Fengwei  * Map page range [start_page, start_page + nr_pages) of folio.
3483de74976eSYin Fengwei  * start_page is gotten from start by folio_page(folio, start)
3484de74976eSYin Fengwei  */
filemap_map_folio_range(struct vm_fault * vmf,struct folio * folio,unsigned long start,unsigned long addr,unsigned int nr_pages,unsigned int * mmap_miss)3485de74976eSYin Fengwei static vm_fault_t filemap_map_folio_range(struct vm_fault *vmf,
3486de74976eSYin Fengwei 			struct folio *folio, unsigned long start,
3487c8be0380SYin Fengwei 			unsigned long addr, unsigned int nr_pages,
3488c8be0380SYin Fengwei 			unsigned int *mmap_miss)
3489f9ce0be7SKirill A. Shutemov {
3490de74976eSYin Fengwei 	vm_fault_t ret = 0;
3491de74976eSYin Fengwei 	struct page *page = folio_page(folio, start);
3492617c28ecSYin Fengwei 	unsigned int count = 0;
3493617c28ecSYin Fengwei 	pte_t *old_ptep = vmf->pte;
3494f9ce0be7SKirill A. Shutemov 
3495de74976eSYin Fengwei 	do {
3496617c28ecSYin Fengwei 		if (PageHWPoison(page + count))
3497617c28ecSYin Fengwei 			goto skip;
3498de74976eSYin Fengwei 
3499c8be0380SYin Fengwei 		(*mmap_miss)++;
3500de74976eSYin Fengwei 
3501de74976eSYin Fengwei 		/*
3502de74976eSYin Fengwei 		 * NOTE: If there're PTE markers, we'll leave them to be
3503de74976eSYin Fengwei 		 * handled in the specific fault path, and it'll prohibit the
3504de74976eSYin Fengwei 		 * fault-around logic.
3505de74976eSYin Fengwei 		 */
3506617c28ecSYin Fengwei 		if (!pte_none(vmf->pte[count]))
3507617c28ecSYin Fengwei 			goto skip;
3508617c28ecSYin Fengwei 
3509617c28ecSYin Fengwei 		count++;
3510de74976eSYin Fengwei 		continue;
3511617c28ecSYin Fengwei skip:
3512617c28ecSYin Fengwei 		if (count) {
3513617c28ecSYin Fengwei 			set_pte_range(vmf, folio, page, count, addr);
3514617c28ecSYin Fengwei 			folio_ref_add(folio, count);
3515a501a070SMatthew Wilcox (Oracle) 			if (in_range(vmf->address, addr, count * PAGE_SIZE))
3516de74976eSYin Fengwei 				ret = VM_FAULT_NOPAGE;
3517f9ce0be7SKirill A. Shutemov 		}
3518f9ce0be7SKirill A. Shutemov 
3519617c28ecSYin Fengwei 		count++;
3520617c28ecSYin Fengwei 		page += count;
3521617c28ecSYin Fengwei 		vmf->pte += count;
3522617c28ecSYin Fengwei 		addr += count * PAGE_SIZE;
3523617c28ecSYin Fengwei 		count = 0;
3524617c28ecSYin Fengwei 	} while (--nr_pages > 0);
3525de74976eSYin Fengwei 
3526617c28ecSYin Fengwei 	if (count) {
3527617c28ecSYin Fengwei 		set_pte_range(vmf, folio, page, count, addr);
3528617c28ecSYin Fengwei 		folio_ref_add(folio, count);
3529a501a070SMatthew Wilcox (Oracle) 		if (in_range(vmf->address, addr, count * PAGE_SIZE))
3530617c28ecSYin Fengwei 			ret = VM_FAULT_NOPAGE;
3531617c28ecSYin Fengwei 	}
3532de74976eSYin Fengwei 
3533617c28ecSYin Fengwei 	vmf->pte = old_ptep;
3534c8be0380SYin Fengwei 
3535c8be0380SYin Fengwei 	return ret;
3536c8be0380SYin Fengwei }
3537c8be0380SYin Fengwei 
filemap_map_order0_folio(struct vm_fault * vmf,struct folio * folio,unsigned long addr,unsigned int * mmap_miss)3538c8be0380SYin Fengwei static vm_fault_t filemap_map_order0_folio(struct vm_fault *vmf,
3539c8be0380SYin Fengwei 		struct folio *folio, unsigned long addr,
3540c8be0380SYin Fengwei 		unsigned int *mmap_miss)
3541c8be0380SYin Fengwei {
3542c8be0380SYin Fengwei 	vm_fault_t ret = 0;
3543c8be0380SYin Fengwei 	struct page *page = &folio->page;
3544c8be0380SYin Fengwei 
3545c8be0380SYin Fengwei 	if (PageHWPoison(page))
3546c8be0380SYin Fengwei 		return ret;
3547c8be0380SYin Fengwei 
3548c8be0380SYin Fengwei 	(*mmap_miss)++;
3549c8be0380SYin Fengwei 
3550c8be0380SYin Fengwei 	/*
3551c8be0380SYin Fengwei 	 * NOTE: If there're PTE markers, we'll leave them to be
3552c8be0380SYin Fengwei 	 * handled in the specific fault path, and it'll prohibit
3553c8be0380SYin Fengwei 	 * the fault-around logic.
3554c8be0380SYin Fengwei 	 */
3555c8be0380SYin Fengwei 	if (!pte_none(ptep_get(vmf->pte)))
3556c8be0380SYin Fengwei 		return ret;
3557c8be0380SYin Fengwei 
3558c8be0380SYin Fengwei 	if (vmf->address == addr)
3559c8be0380SYin Fengwei 		ret = VM_FAULT_NOPAGE;
3560c8be0380SYin Fengwei 
3561c8be0380SYin Fengwei 	set_pte_range(vmf, folio, page, 1, addr);
3562c8be0380SYin Fengwei 	folio_ref_inc(folio);
3563de74976eSYin Fengwei 
3564de74976eSYin Fengwei 	return ret;
3565f9ce0be7SKirill A. Shutemov }
3566f9ce0be7SKirill A. Shutemov 
filemap_map_pages(struct vm_fault * vmf,pgoff_t start_pgoff,pgoff_t end_pgoff)3567f9ce0be7SKirill A. Shutemov vm_fault_t filemap_map_pages(struct vm_fault *vmf,
3568bae473a4SKirill A. Shutemov 			     pgoff_t start_pgoff, pgoff_t end_pgoff)
3569f1820361SKirill A. Shutemov {
3570f9ce0be7SKirill A. Shutemov 	struct vm_area_struct *vma = vmf->vma;
3571f9ce0be7SKirill A. Shutemov 	struct file *file = vma->vm_file;
3572f1820361SKirill A. Shutemov 	struct address_space *mapping = file->f_mapping;
3573bae473a4SKirill A. Shutemov 	pgoff_t last_pgoff = start_pgoff;
35749d3af4b4SWill Deacon 	unsigned long addr;
3575070e807cSMatthew Wilcox 	XA_STATE(xas, &mapping->i_pages, start_pgoff);
3576820b05e9SMatthew Wilcox (Oracle) 	struct folio *folio;
3577f9ce0be7SKirill A. Shutemov 	vm_fault_t ret = 0;
3578c8be0380SYin Fengwei 	unsigned int nr_pages = 0, mmap_miss = 0, mmap_miss_saved;
3579f1820361SKirill A. Shutemov 
3580f1820361SKirill A. Shutemov 	rcu_read_lock();
3581de74976eSYin Fengwei 	folio = next_uptodate_folio(&xas, mapping, end_pgoff);
3582820b05e9SMatthew Wilcox (Oracle) 	if (!folio)
3583f9ce0be7SKirill A. Shutemov 		goto out;
3584f1820361SKirill A. Shutemov 
35858808ecabSMatthew Wilcox (Oracle) 	if (filemap_map_pmd(vmf, folio, start_pgoff)) {
3586f9ce0be7SKirill A. Shutemov 		ret = VM_FAULT_NOPAGE;
3587f9ce0be7SKirill A. Shutemov 		goto out;
3588f9ce0be7SKirill A. Shutemov 	}
3589f1820361SKirill A. Shutemov 
35909d3af4b4SWill Deacon 	addr = vma->vm_start + ((start_pgoff - vma->vm_pgoff) << PAGE_SHIFT);
35919d3af4b4SWill Deacon 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
359265747aafSHugh Dickins 	if (!vmf->pte) {
359365747aafSHugh Dickins 		folio_unlock(folio);
359465747aafSHugh Dickins 		folio_put(folio);
359565747aafSHugh Dickins 		goto out;
359665747aafSHugh Dickins 	}
3597f9ce0be7SKirill A. Shutemov 	do {
3598de74976eSYin Fengwei 		unsigned long end;
35997267ec00SKirill A. Shutemov 
36009d3af4b4SWill Deacon 		addr += (xas.xa_index - last_pgoff) << PAGE_SHIFT;
3601070e807cSMatthew Wilcox 		vmf->pte += xas.xa_index - last_pgoff;
3602070e807cSMatthew Wilcox 		last_pgoff = xas.xa_index;
3603de74976eSYin Fengwei 		end = folio->index + folio_nr_pages(folio) - 1;
3604de74976eSYin Fengwei 		nr_pages = min(end, end_pgoff) - xas.xa_index + 1;
3605f9ce0be7SKirill A. Shutemov 
3606c8be0380SYin Fengwei 		if (!folio_test_large(folio))
3607c8be0380SYin Fengwei 			ret |= filemap_map_order0_folio(vmf,
3608c8be0380SYin Fengwei 					folio, addr, &mmap_miss);
3609c8be0380SYin Fengwei 		else
3610de74976eSYin Fengwei 			ret |= filemap_map_folio_range(vmf, folio,
3611c8be0380SYin Fengwei 					xas.xa_index - folio->index, addr,
3612c8be0380SYin Fengwei 					nr_pages, &mmap_miss);
361346bdb427SWill Deacon 
3614820b05e9SMatthew Wilcox (Oracle) 		folio_unlock(folio);
3615820b05e9SMatthew Wilcox (Oracle) 		folio_put(folio);
3616c8be0380SYin Fengwei 	} while ((folio = next_uptodate_folio(&xas, mapping, end_pgoff)) != NULL);
3617f9ce0be7SKirill A. Shutemov 	pte_unmap_unlock(vmf->pte, vmf->ptl);
3618f9ce0be7SKirill A. Shutemov out:
3619f1820361SKirill A. Shutemov 	rcu_read_unlock();
3620c8be0380SYin Fengwei 
3621c8be0380SYin Fengwei 	mmap_miss_saved = READ_ONCE(file->f_ra.mmap_miss);
3622c8be0380SYin Fengwei 	if (mmap_miss >= mmap_miss_saved)
3623c8be0380SYin Fengwei 		WRITE_ONCE(file->f_ra.mmap_miss, 0);
3624c8be0380SYin Fengwei 	else
3625c8be0380SYin Fengwei 		WRITE_ONCE(file->f_ra.mmap_miss, mmap_miss_saved - mmap_miss);
3626c8be0380SYin Fengwei 
3627f9ce0be7SKirill A. Shutemov 	return ret;
3628f1820361SKirill A. Shutemov }
3629f1820361SKirill A. Shutemov EXPORT_SYMBOL(filemap_map_pages);
3630f1820361SKirill A. Shutemov 
filemap_page_mkwrite(struct vm_fault * vmf)36312bcd6454SSouptick Joarder vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
36324fcf1c62SJan Kara {
36335df1a672SChristoph Hellwig 	struct address_space *mapping = vmf->vma->vm_file->f_mapping;
3634960ea971SMatthew Wilcox (Oracle) 	struct folio *folio = page_folio(vmf->page);
36352bcd6454SSouptick Joarder 	vm_fault_t ret = VM_FAULT_LOCKED;
36364fcf1c62SJan Kara 
36375df1a672SChristoph Hellwig 	sb_start_pagefault(mapping->host->i_sb);
363811bac800SDave Jiang 	file_update_time(vmf->vma->vm_file);
3639960ea971SMatthew Wilcox (Oracle) 	folio_lock(folio);
3640960ea971SMatthew Wilcox (Oracle) 	if (folio->mapping != mapping) {
3641960ea971SMatthew Wilcox (Oracle) 		folio_unlock(folio);
36424fcf1c62SJan Kara 		ret = VM_FAULT_NOPAGE;
36434fcf1c62SJan Kara 		goto out;
36444fcf1c62SJan Kara 	}
364514da9200SJan Kara 	/*
3646960ea971SMatthew Wilcox (Oracle) 	 * We mark the folio dirty already here so that when freeze is in
364714da9200SJan Kara 	 * progress, we are guaranteed that writeback during freezing will
3648960ea971SMatthew Wilcox (Oracle) 	 * see the dirty folio and writeprotect it again.
364914da9200SJan Kara 	 */
3650960ea971SMatthew Wilcox (Oracle) 	folio_mark_dirty(folio);
3651960ea971SMatthew Wilcox (Oracle) 	folio_wait_stable(folio);
36524fcf1c62SJan Kara out:
36535df1a672SChristoph Hellwig 	sb_end_pagefault(mapping->host->i_sb);
36544fcf1c62SJan Kara 	return ret;
36554fcf1c62SJan Kara }
36564fcf1c62SJan Kara 
3657f0f37e2fSAlexey Dobriyan const struct vm_operations_struct generic_file_vm_ops = {
365854cb8821SNick Piggin 	.fault		= filemap_fault,
3659f1820361SKirill A. Shutemov 	.map_pages	= filemap_map_pages,
36604fcf1c62SJan Kara 	.page_mkwrite	= filemap_page_mkwrite,
36611da177e4SLinus Torvalds };
36621da177e4SLinus Torvalds 
36631da177e4SLinus Torvalds /* This is used for a general mmap of a disk file */
36641da177e4SLinus Torvalds 
generic_file_mmap(struct file * file,struct vm_area_struct * vma)36651da177e4SLinus Torvalds int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
36661da177e4SLinus Torvalds {
36671da177e4SLinus Torvalds 	struct address_space *mapping = file->f_mapping;
36681da177e4SLinus Torvalds 
36697e0a1265SMatthew Wilcox (Oracle) 	if (!mapping->a_ops->read_folio)
36701da177e4SLinus Torvalds 		return -ENOEXEC;
36711da177e4SLinus Torvalds 	file_accessed(file);
36721da177e4SLinus Torvalds 	vma->vm_ops = &generic_file_vm_ops;
36731da177e4SLinus Torvalds 	return 0;
36741da177e4SLinus Torvalds }
36751da177e4SLinus Torvalds 
36761da177e4SLinus Torvalds /*
36771da177e4SLinus Torvalds  * This is for filesystems which do not implement ->writepage.
36781da177e4SLinus Torvalds  */
generic_file_readonly_mmap(struct file * file,struct vm_area_struct * vma)36791da177e4SLinus Torvalds int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
36801da177e4SLinus Torvalds {
36811da177e4SLinus Torvalds 	if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
36821da177e4SLinus Torvalds 		return -EINVAL;
36831da177e4SLinus Torvalds 	return generic_file_mmap(file, vma);
36841da177e4SLinus Torvalds }
36851da177e4SLinus Torvalds #else
filemap_page_mkwrite(struct vm_fault * vmf)36864b96a37dSSouptick Joarder vm_fault_t filemap_page_mkwrite(struct vm_fault *vmf)
368745397228SArnd Bergmann {
36884b96a37dSSouptick Joarder 	return VM_FAULT_SIGBUS;
368945397228SArnd Bergmann }
generic_file_mmap(struct file * file,struct vm_area_struct * vma)36901da177e4SLinus Torvalds int generic_file_mmap(struct file *file, struct vm_area_struct *vma)
36911da177e4SLinus Torvalds {
36921da177e4SLinus Torvalds 	return -ENOSYS;
36931da177e4SLinus Torvalds }
generic_file_readonly_mmap(struct file * file,struct vm_area_struct * vma)36941da177e4SLinus Torvalds int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
36951da177e4SLinus Torvalds {
36961da177e4SLinus Torvalds 	return -ENOSYS;
36971da177e4SLinus Torvalds }
36981da177e4SLinus Torvalds #endif /* CONFIG_MMU */
36991da177e4SLinus Torvalds 
370045397228SArnd Bergmann EXPORT_SYMBOL(filemap_page_mkwrite);
37011da177e4SLinus Torvalds EXPORT_SYMBOL(generic_file_mmap);
37021da177e4SLinus Torvalds EXPORT_SYMBOL(generic_file_readonly_mmap);
37031da177e4SLinus Torvalds 
do_read_cache_folio(struct address_space * mapping,pgoff_t index,filler_t filler,struct file * file,gfp_t gfp)3704539a3322SMatthew Wilcox (Oracle) static struct folio *do_read_cache_folio(struct address_space *mapping,
3705e9b5b23eSMatthew Wilcox (Oracle) 		pgoff_t index, filler_t filler, struct file *file, gfp_t gfp)
370667f9fd91SSasha Levin {
3707539a3322SMatthew Wilcox (Oracle) 	struct folio *folio;
37081da177e4SLinus Torvalds 	int err;
370907950008SMatthew Wilcox (Oracle) 
371007950008SMatthew Wilcox (Oracle) 	if (!filler)
371107950008SMatthew Wilcox (Oracle) 		filler = mapping->a_ops->read_folio;
37121da177e4SLinus Torvalds repeat:
3713539a3322SMatthew Wilcox (Oracle) 	folio = filemap_get_folio(mapping, index);
371466dabbb6SChristoph Hellwig 	if (IS_ERR(folio)) {
3715539a3322SMatthew Wilcox (Oracle) 		folio = filemap_alloc_folio(gfp, 0);
3716539a3322SMatthew Wilcox (Oracle) 		if (!folio)
37171da177e4SLinus Torvalds 			return ERR_PTR(-ENOMEM);
3718539a3322SMatthew Wilcox (Oracle) 		err = filemap_add_folio(mapping, folio, index, gfp);
3719eb2be189SNick Piggin 		if (unlikely(err)) {
3720539a3322SMatthew Wilcox (Oracle) 			folio_put(folio);
37211da177e4SLinus Torvalds 			if (err == -EEXIST)
37221da177e4SLinus Torvalds 				goto repeat;
372322ecdb4fSMatthew Wilcox 			/* Presumably ENOMEM for xarray node */
37241da177e4SLinus Torvalds 			return ERR_PTR(err);
37251da177e4SLinus Torvalds 		}
372632b63529SMel Gorman 
37279bc3e869SMatthew Wilcox (Oracle) 		goto filler;
372832b63529SMel Gorman 	}
3729539a3322SMatthew Wilcox (Oracle) 	if (folio_test_uptodate(folio))
37301da177e4SLinus Torvalds 		goto out;
37311da177e4SLinus Torvalds 
373281f4c03bSMatthew Wilcox (Oracle) 	if (!folio_trylock(folio)) {
373381f4c03bSMatthew Wilcox (Oracle) 		folio_put_wait_locked(folio, TASK_UNINTERRUPTIBLE);
373481f4c03bSMatthew Wilcox (Oracle) 		goto repeat;
373581f4c03bSMatthew Wilcox (Oracle) 	}
3736ebded027SMel Gorman 
373781f4c03bSMatthew Wilcox (Oracle) 	/* Folio was truncated from mapping */
3738539a3322SMatthew Wilcox (Oracle) 	if (!folio->mapping) {
3739539a3322SMatthew Wilcox (Oracle) 		folio_unlock(folio);
3740539a3322SMatthew Wilcox (Oracle) 		folio_put(folio);
374132b63529SMel Gorman 		goto repeat;
37421da177e4SLinus Torvalds 	}
3743ebded027SMel Gorman 
3744ebded027SMel Gorman 	/* Someone else locked and filled the page in a very small window */
3745539a3322SMatthew Wilcox (Oracle) 	if (folio_test_uptodate(folio)) {
3746539a3322SMatthew Wilcox (Oracle) 		folio_unlock(folio);
37471da177e4SLinus Torvalds 		goto out;
37481da177e4SLinus Torvalds 	}
3749faffdfa0SXianting Tian 
37509bc3e869SMatthew Wilcox (Oracle) filler:
3751290e1a32SMatthew Wilcox (Oracle) 	err = filemap_read_folio(file, filler, folio);
37521dfa24a4SMatthew Wilcox (Oracle) 	if (err) {
37539bc3e869SMatthew Wilcox (Oracle) 		folio_put(folio);
37541dfa24a4SMatthew Wilcox (Oracle) 		if (err == AOP_TRUNCATED_PAGE)
37551dfa24a4SMatthew Wilcox (Oracle) 			goto repeat;
37569bc3e869SMatthew Wilcox (Oracle) 		return ERR_PTR(err);
37579bc3e869SMatthew Wilcox (Oracle) 	}
375832b63529SMel Gorman 
37591da177e4SLinus Torvalds out:
3760539a3322SMatthew Wilcox (Oracle) 	folio_mark_accessed(folio);
3761539a3322SMatthew Wilcox (Oracle) 	return folio;
37626fe6900eSNick Piggin }
37630531b2aaSLinus Torvalds 
37640531b2aaSLinus Torvalds /**
3765e9b5b23eSMatthew Wilcox (Oracle)  * read_cache_folio - Read into page cache, fill it if needed.
3766e9b5b23eSMatthew Wilcox (Oracle)  * @mapping: The address_space to read from.
3767e9b5b23eSMatthew Wilcox (Oracle)  * @index: The index to read.
3768e9b5b23eSMatthew Wilcox (Oracle)  * @filler: Function to perform the read, or NULL to use aops->read_folio().
3769e9b5b23eSMatthew Wilcox (Oracle)  * @file: Passed to filler function, may be NULL if not required.
37700531b2aaSLinus Torvalds  *
3771e9b5b23eSMatthew Wilcox (Oracle)  * Read one page into the page cache.  If it succeeds, the folio returned
3772e9b5b23eSMatthew Wilcox (Oracle)  * will contain @index, but it may not be the first page of the folio.
37730531b2aaSLinus Torvalds  *
3774e9b5b23eSMatthew Wilcox (Oracle)  * If the filler function returns an error, it will be returned to the
3775e9b5b23eSMatthew Wilcox (Oracle)  * caller.
3776a862f68aSMike Rapoport  *
3777e9b5b23eSMatthew Wilcox (Oracle)  * Context: May sleep.  Expects mapping->invalidate_lock to be held.
3778e9b5b23eSMatthew Wilcox (Oracle)  * Return: An uptodate folio on success, ERR_PTR() on failure.
37790531b2aaSLinus Torvalds  */
read_cache_folio(struct address_space * mapping,pgoff_t index,filler_t filler,struct file * file)3780539a3322SMatthew Wilcox (Oracle) struct folio *read_cache_folio(struct address_space *mapping, pgoff_t index,
3781e9b5b23eSMatthew Wilcox (Oracle) 		filler_t filler, struct file *file)
3782539a3322SMatthew Wilcox (Oracle) {
3783e9b5b23eSMatthew Wilcox (Oracle) 	return do_read_cache_folio(mapping, index, filler, file,
3784539a3322SMatthew Wilcox (Oracle) 			mapping_gfp_mask(mapping));
3785539a3322SMatthew Wilcox (Oracle) }
3786539a3322SMatthew Wilcox (Oracle) EXPORT_SYMBOL(read_cache_folio);
3787539a3322SMatthew Wilcox (Oracle) 
37883e629597SMatthew Wilcox (Oracle) /**
37893e629597SMatthew Wilcox (Oracle)  * mapping_read_folio_gfp - Read into page cache, using specified allocation flags.
37903e629597SMatthew Wilcox (Oracle)  * @mapping:	The address_space for the folio.
37913e629597SMatthew Wilcox (Oracle)  * @index:	The index that the allocated folio will contain.
37923e629597SMatthew Wilcox (Oracle)  * @gfp:	The page allocator flags to use if allocating.
37933e629597SMatthew Wilcox (Oracle)  *
37943e629597SMatthew Wilcox (Oracle)  * This is the same as "read_cache_folio(mapping, index, NULL, NULL)", but with
37953e629597SMatthew Wilcox (Oracle)  * any new memory allocations done using the specified allocation flags.
37963e629597SMatthew Wilcox (Oracle)  *
37973e629597SMatthew Wilcox (Oracle)  * The most likely error from this function is EIO, but ENOMEM is
37983e629597SMatthew Wilcox (Oracle)  * possible and so is EINTR.  If ->read_folio returns another error,
37993e629597SMatthew Wilcox (Oracle)  * that will be returned to the caller.
38003e629597SMatthew Wilcox (Oracle)  *
38013e629597SMatthew Wilcox (Oracle)  * The function expects mapping->invalidate_lock to be already held.
38023e629597SMatthew Wilcox (Oracle)  *
38033e629597SMatthew Wilcox (Oracle)  * Return: Uptodate folio on success, ERR_PTR() on failure.
38043e629597SMatthew Wilcox (Oracle)  */
mapping_read_folio_gfp(struct address_space * mapping,pgoff_t index,gfp_t gfp)38053e629597SMatthew Wilcox (Oracle) struct folio *mapping_read_folio_gfp(struct address_space *mapping,
38063e629597SMatthew Wilcox (Oracle) 		pgoff_t index, gfp_t gfp)
38073e629597SMatthew Wilcox (Oracle) {
38083e629597SMatthew Wilcox (Oracle) 	return do_read_cache_folio(mapping, index, NULL, NULL, gfp);
38093e629597SMatthew Wilcox (Oracle) }
38103e629597SMatthew Wilcox (Oracle) EXPORT_SYMBOL(mapping_read_folio_gfp);
38113e629597SMatthew Wilcox (Oracle) 
do_read_cache_page(struct address_space * mapping,pgoff_t index,filler_t * filler,struct file * file,gfp_t gfp)3812539a3322SMatthew Wilcox (Oracle) static struct page *do_read_cache_page(struct address_space *mapping,
3813e9b5b23eSMatthew Wilcox (Oracle) 		pgoff_t index, filler_t *filler, struct file *file, gfp_t gfp)
3814539a3322SMatthew Wilcox (Oracle) {
3815539a3322SMatthew Wilcox (Oracle) 	struct folio *folio;
3816539a3322SMatthew Wilcox (Oracle) 
3817e9b5b23eSMatthew Wilcox (Oracle) 	folio = do_read_cache_folio(mapping, index, filler, file, gfp);
3818539a3322SMatthew Wilcox (Oracle) 	if (IS_ERR(folio))
3819539a3322SMatthew Wilcox (Oracle) 		return &folio->page;
3820539a3322SMatthew Wilcox (Oracle) 	return folio_file_page(folio, index);
3821539a3322SMatthew Wilcox (Oracle) }
3822539a3322SMatthew Wilcox (Oracle) 
read_cache_page(struct address_space * mapping,pgoff_t index,filler_t * filler,struct file * file)382367f9fd91SSasha Levin struct page *read_cache_page(struct address_space *mapping,
3824e9b5b23eSMatthew Wilcox (Oracle) 			pgoff_t index, filler_t *filler, struct file *file)
38250531b2aaSLinus Torvalds {
3826e9b5b23eSMatthew Wilcox (Oracle) 	return do_read_cache_page(mapping, index, filler, file,
3827d322a8e5SChristoph Hellwig 			mapping_gfp_mask(mapping));
38280531b2aaSLinus Torvalds }
382967f9fd91SSasha Levin EXPORT_SYMBOL(read_cache_page);
38300531b2aaSLinus Torvalds 
38310531b2aaSLinus Torvalds /**
38320531b2aaSLinus Torvalds  * read_cache_page_gfp - read into page cache, using specified page allocation flags.
38330531b2aaSLinus Torvalds  * @mapping:	the page's address_space
38340531b2aaSLinus Torvalds  * @index:	the page index
38350531b2aaSLinus Torvalds  * @gfp:	the page allocator flags to use if allocating
38360531b2aaSLinus Torvalds  *
38370531b2aaSLinus Torvalds  * This is the same as "read_mapping_page(mapping, index, NULL)", but with
3838e6f67b8cSDave Kleikamp  * any new page allocations done using the specified allocation flags.
38390531b2aaSLinus Torvalds  *
38400531b2aaSLinus Torvalds  * If the page does not get brought uptodate, return -EIO.
3841a862f68aSMike Rapoport  *
3842730633f0SJan Kara  * The function expects mapping->invalidate_lock to be already held.
3843730633f0SJan Kara  *
3844a862f68aSMike Rapoport  * Return: up to date page on success, ERR_PTR() on failure.
38450531b2aaSLinus Torvalds  */
read_cache_page_gfp(struct address_space * mapping,pgoff_t index,gfp_t gfp)38460531b2aaSLinus Torvalds struct page *read_cache_page_gfp(struct address_space *mapping,
38470531b2aaSLinus Torvalds 				pgoff_t index,
38480531b2aaSLinus Torvalds 				gfp_t gfp)
38490531b2aaSLinus Torvalds {
38506c45b454SChristoph Hellwig 	return do_read_cache_page(mapping, index, NULL, NULL, gfp);
38510531b2aaSLinus Torvalds }
38520531b2aaSLinus Torvalds EXPORT_SYMBOL(read_cache_page_gfp);
38530531b2aaSLinus Torvalds 
3854a92853b6SKonstantin Khlebnikov /*
3855a92853b6SKonstantin Khlebnikov  * Warn about a page cache invalidation failure during a direct I/O write.
3856a92853b6SKonstantin Khlebnikov  */
dio_warn_stale_pagecache(struct file * filp)3857c402a9a9SChristoph Hellwig static void dio_warn_stale_pagecache(struct file *filp)
3858a92853b6SKonstantin Khlebnikov {
3859a92853b6SKonstantin Khlebnikov 	static DEFINE_RATELIMIT_STATE(_rs, 86400 * HZ, DEFAULT_RATELIMIT_BURST);
3860a92853b6SKonstantin Khlebnikov 	char pathname[128];
3861a92853b6SKonstantin Khlebnikov 	char *path;
3862a92853b6SKonstantin Khlebnikov 
38635df1a672SChristoph Hellwig 	errseq_set(&filp->f_mapping->wb_err, -EIO);
3864a92853b6SKonstantin Khlebnikov 	if (__ratelimit(&_rs)) {
3865a92853b6SKonstantin Khlebnikov 		path = file_path(filp, pathname, sizeof(pathname));
3866a92853b6SKonstantin Khlebnikov 		if (IS_ERR(path))
3867a92853b6SKonstantin Khlebnikov 			path = "(unknown)";
3868a92853b6SKonstantin Khlebnikov 		pr_crit("Page cache invalidation failure on direct I/O.  Possible data corruption due to collision with buffered I/O!\n");
3869a92853b6SKonstantin Khlebnikov 		pr_crit("File: %s PID: %d Comm: %.20s\n", path, current->pid,
3870a92853b6SKonstantin Khlebnikov 			current->comm);
3871a92853b6SKonstantin Khlebnikov 	}
3872a92853b6SKonstantin Khlebnikov }
3873a92853b6SKonstantin Khlebnikov 
kiocb_invalidate_post_direct_write(struct kiocb * iocb,size_t count)3874c402a9a9SChristoph Hellwig void kiocb_invalidate_post_direct_write(struct kiocb *iocb, size_t count)
3875c402a9a9SChristoph Hellwig {
3876c402a9a9SChristoph Hellwig 	struct address_space *mapping = iocb->ki_filp->f_mapping;
3877c402a9a9SChristoph Hellwig 
3878c402a9a9SChristoph Hellwig 	if (mapping->nrpages &&
3879c402a9a9SChristoph Hellwig 	    invalidate_inode_pages2_range(mapping,
3880c402a9a9SChristoph Hellwig 			iocb->ki_pos >> PAGE_SHIFT,
3881c402a9a9SChristoph Hellwig 			(iocb->ki_pos + count - 1) >> PAGE_SHIFT))
3882c402a9a9SChristoph Hellwig 		dio_warn_stale_pagecache(iocb->ki_filp);
3883c402a9a9SChristoph Hellwig }
3884c402a9a9SChristoph Hellwig 
38851da177e4SLinus Torvalds ssize_t
generic_file_direct_write(struct kiocb * iocb,struct iov_iter * from)38861af5bb49SChristoph Hellwig generic_file_direct_write(struct kiocb *iocb, struct iov_iter *from)
38871da177e4SLinus Torvalds {
3888c402a9a9SChristoph Hellwig 	struct address_space *mapping = iocb->ki_filp->f_mapping;
3889c402a9a9SChristoph Hellwig 	size_t write_len = iov_iter_count(from);
38901da177e4SLinus Torvalds 	ssize_t written;
38911da177e4SLinus Torvalds 
38926ccfa806SHisashi Hifumi 	/*
38936ccfa806SHisashi Hifumi 	 * If a page can not be invalidated, return 0 to fall back
38946ccfa806SHisashi Hifumi 	 * to buffered write.
38956ccfa806SHisashi Hifumi 	 */
3896e003f74aSChristoph Hellwig 	written = kiocb_invalidate_pages(iocb, write_len);
38976ccfa806SHisashi Hifumi 	if (written) {
38986ccfa806SHisashi Hifumi 		if (written == -EBUSY)
38996ccfa806SHisashi Hifumi 			return 0;
3900c402a9a9SChristoph Hellwig 		return written;
3901a969e903SChristoph Hellwig 	}
3902a969e903SChristoph Hellwig 
3903639a93a5SAl Viro 	written = mapping->a_ops->direct_IO(iocb, from);
3904a969e903SChristoph Hellwig 
3905a969e903SChristoph Hellwig 	/*
3906a969e903SChristoph Hellwig 	 * Finally, try again to invalidate clean pages which might have been
3907a969e903SChristoph Hellwig 	 * cached by non-direct readahead, or faulted in by get_user_pages()
3908a969e903SChristoph Hellwig 	 * if the source of the write was an mmap'ed region of the file
3909a969e903SChristoph Hellwig 	 * we're writing.  Either one is a pretty crazy thing to do,
3910a969e903SChristoph Hellwig 	 * so we don't support it 100%.  If this invalidation
3911a969e903SChristoph Hellwig 	 * fails, tough, the write still worked...
3912332391a9SLukas Czerner 	 *
3913332391a9SLukas Czerner 	 * Most of the time we do not need this since dio_complete() will do
3914332391a9SLukas Czerner 	 * the invalidation for us. However there are some file systems that
3915332391a9SLukas Czerner 	 * do not end up with dio_complete() being called, so let's not break
391680c1fe90SKonstantin Khlebnikov 	 * them by removing it completely.
391780c1fe90SKonstantin Khlebnikov 	 *
39189266a140SKonstantin Khlebnikov 	 * Noticeable example is a blkdev_direct_IO().
39199266a140SKonstantin Khlebnikov 	 *
392080c1fe90SKonstantin Khlebnikov 	 * Skip invalidation for async writes or if mapping has no pages.
3921a969e903SChristoph Hellwig 	 */
39221da177e4SLinus Torvalds 	if (written > 0) {
3923c402a9a9SChristoph Hellwig 		struct inode *inode = mapping->host;
3924c402a9a9SChristoph Hellwig 		loff_t pos = iocb->ki_pos;
3925c402a9a9SChristoph Hellwig 
3926c402a9a9SChristoph Hellwig 		kiocb_invalidate_post_direct_write(iocb, written);
39270116651cSNamhyung Kim 		pos += written;
3928639a93a5SAl Viro 		write_len -= written;
39290116651cSNamhyung Kim 		if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
39300116651cSNamhyung Kim 			i_size_write(inode, pos);
39311da177e4SLinus Torvalds 			mark_inode_dirty(inode);
39321da177e4SLinus Torvalds 		}
39335cb6c6c7SAl Viro 		iocb->ki_pos = pos;
39341da177e4SLinus Torvalds 	}
3935ab2125dfSPavel Begunkov 	if (written != -EIOCBQUEUED)
3936639a93a5SAl Viro 		iov_iter_revert(from, write_len - iov_iter_count(from));
39371da177e4SLinus Torvalds 	return written;
39381da177e4SLinus Torvalds }
39391da177e4SLinus Torvalds EXPORT_SYMBOL(generic_file_direct_write);
39401da177e4SLinus Torvalds 
generic_perform_write(struct kiocb * iocb,struct iov_iter * i)3941800ba295SMatthew Wilcox (Oracle) ssize_t generic_perform_write(struct kiocb *iocb, struct iov_iter *i)
3942afddba49SNick Piggin {
3943800ba295SMatthew Wilcox (Oracle) 	struct file *file = iocb->ki_filp;
3944800ba295SMatthew Wilcox (Oracle) 	loff_t pos = iocb->ki_pos;
3945afddba49SNick Piggin 	struct address_space *mapping = file->f_mapping;
3946afddba49SNick Piggin 	const struct address_space_operations *a_ops = mapping->a_ops;
3947afddba49SNick Piggin 	long status = 0;
3948afddba49SNick Piggin 	ssize_t written = 0;
3949674b892eSNick Piggin 
3950afddba49SNick Piggin 	do {
3951afddba49SNick Piggin 		struct page *page;
3952afddba49SNick Piggin 		unsigned long offset;	/* Offset into pagecache page */
3953afddba49SNick Piggin 		unsigned long bytes;	/* Bytes to write to page */
3954afddba49SNick Piggin 		size_t copied;		/* Bytes copied from user */
39551468c6f4SAlexander Potapenko 		void *fsdata = NULL;
3956afddba49SNick Piggin 
395709cbfeafSKirill A. Shutemov 		offset = (pos & (PAGE_SIZE - 1));
395809cbfeafSKirill A. Shutemov 		bytes = min_t(unsigned long, PAGE_SIZE - offset,
3959afddba49SNick Piggin 						iov_iter_count(i));
3960afddba49SNick Piggin 
3961afddba49SNick Piggin again:
396200a3d660SLinus Torvalds 		/*
396300a3d660SLinus Torvalds 		 * Bring in the user page that we will copy from _first_.
396400a3d660SLinus Torvalds 		 * Otherwise there's a nasty deadlock on copying from the
396500a3d660SLinus Torvalds 		 * same page as we're writing to, without it being marked
396600a3d660SLinus Torvalds 		 * up-to-date.
396700a3d660SLinus Torvalds 		 */
3968631f871fSAndreas Gruenbacher 		if (unlikely(fault_in_iov_iter_readable(i, bytes) == bytes)) {
396900a3d660SLinus Torvalds 			status = -EFAULT;
397000a3d660SLinus Torvalds 			break;
397100a3d660SLinus Torvalds 		}
397200a3d660SLinus Torvalds 
3973296291cdSJan Kara 		if (fatal_signal_pending(current)) {
3974296291cdSJan Kara 			status = -EINTR;
3975296291cdSJan Kara 			break;
3976296291cdSJan Kara 		}
3977296291cdSJan Kara 
39789d6b0cd7SMatthew Wilcox (Oracle) 		status = a_ops->write_begin(file, mapping, pos, bytes,
3979afddba49SNick Piggin 						&page, &fsdata);
39802457aec6SMel Gorman 		if (unlikely(status < 0))
3981afddba49SNick Piggin 			break;
3982afddba49SNick Piggin 
3983931e80e4Sanfei zhou 		if (mapping_writably_mapped(mapping))
3984931e80e4Sanfei zhou 			flush_dcache_page(page);
398500a3d660SLinus Torvalds 
3986f0b65f39SAl Viro 		copied = copy_page_from_iter_atomic(page, offset, bytes, i);
3987afddba49SNick Piggin 		flush_dcache_page(page);
3988afddba49SNick Piggin 
3989afddba49SNick Piggin 		status = a_ops->write_end(file, mapping, pos, bytes, copied,
3990afddba49SNick Piggin 						page, fsdata);
3991f0b65f39SAl Viro 		if (unlikely(status != copied)) {
3992f0b65f39SAl Viro 			iov_iter_revert(i, copied - max(status, 0L));
3993afddba49SNick Piggin 			if (unlikely(status < 0))
3994afddba49SNick Piggin 				break;
3995f0b65f39SAl Viro 		}
3996afddba49SNick Piggin 		cond_resched();
3997afddba49SNick Piggin 
3998bc1bb416SAl Viro 		if (unlikely(status == 0)) {
3999afddba49SNick Piggin 			/*
4000bc1bb416SAl Viro 			 * A short copy made ->write_end() reject the
4001bc1bb416SAl Viro 			 * thing entirely.  Might be memory poisoning
4002bc1bb416SAl Viro 			 * halfway through, might be a race with munmap,
4003bc1bb416SAl Viro 			 * might be severe memory pressure.
4004afddba49SNick Piggin 			 */
4005bc1bb416SAl Viro 			if (copied)
4006bc1bb416SAl Viro 				bytes = copied;
4007afddba49SNick Piggin 			goto again;
4008afddba49SNick Piggin 		}
4009f0b65f39SAl Viro 		pos += status;
4010f0b65f39SAl Viro 		written += status;
4011afddba49SNick Piggin 
4012afddba49SNick Piggin 		balance_dirty_pages_ratelimited(mapping);
4013afddba49SNick Piggin 	} while (iov_iter_count(i));
4014afddba49SNick Piggin 
4015182c25e9SChristoph Hellwig 	if (!written)
4016182c25e9SChristoph Hellwig 		return status;
4017182c25e9SChristoph Hellwig 	iocb->ki_pos += written;
4018182c25e9SChristoph Hellwig 	return written;
4019afddba49SNick Piggin }
40203b93f911SAl Viro EXPORT_SYMBOL(generic_perform_write);
40211da177e4SLinus Torvalds 
4022e4dd9de3SJan Kara /**
40238174202bSAl Viro  * __generic_file_write_iter - write data to a file
4024e4dd9de3SJan Kara  * @iocb:	IO state structure (file, offset, etc.)
40258174202bSAl Viro  * @from:	iov_iter with data to write
4026e4dd9de3SJan Kara  *
4027e4dd9de3SJan Kara  * This function does all the work needed for actually writing data to a
4028e4dd9de3SJan Kara  * file. It does all basic checks, removes SUID from the file, updates
4029e4dd9de3SJan Kara  * modification times and calls proper subroutines depending on whether we
4030e4dd9de3SJan Kara  * do direct IO or a standard buffered write.
4031e4dd9de3SJan Kara  *
40329608703eSJan Kara  * It expects i_rwsem to be grabbed unless we work on a block device or similar
4033e4dd9de3SJan Kara  * object which does not need locking at all.
4034e4dd9de3SJan Kara  *
4035e4dd9de3SJan Kara  * This function does *not* take care of syncing data in case of O_SYNC write.
4036e4dd9de3SJan Kara  * A caller has to handle it. This is mainly due to the fact that we want to
40379608703eSJan Kara  * avoid syncing under i_rwsem.
4038a862f68aSMike Rapoport  *
4039a862f68aSMike Rapoport  * Return:
4040a862f68aSMike Rapoport  * * number of bytes written, even for truncated writes
4041a862f68aSMike Rapoport  * * negative error code if no data has been written at all
4042e4dd9de3SJan Kara  */
__generic_file_write_iter(struct kiocb * iocb,struct iov_iter * from)40438174202bSAl Viro ssize_t __generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
40441da177e4SLinus Torvalds {
40451da177e4SLinus Torvalds 	struct file *file = iocb->ki_filp;
4046fb5527e6SJeff Moyer 	struct address_space *mapping = file->f_mapping;
40471da177e4SLinus Torvalds 	struct inode *inode = mapping->host;
404844fff0faSChristoph Hellwig 	ssize_t ret;
40491da177e4SLinus Torvalds 
405044fff0faSChristoph Hellwig 	ret = file_remove_privs(file);
405144fff0faSChristoph Hellwig 	if (ret)
405244fff0faSChristoph Hellwig 		return ret;
40531da177e4SLinus Torvalds 
405444fff0faSChristoph Hellwig 	ret = file_update_time(file);
405544fff0faSChristoph Hellwig 	if (ret)
405644fff0faSChristoph Hellwig 		return ret;
40571da177e4SLinus Torvalds 
40582ba48ce5SAl Viro 	if (iocb->ki_flags & IOCB_DIRECT) {
405944fff0faSChristoph Hellwig 		ret = generic_file_direct_write(iocb, from);
4060fbbbad4bSMatthew Wilcox 		/*
4061fbbbad4bSMatthew Wilcox 		 * If the write stopped short of completing, fall back to
4062fbbbad4bSMatthew Wilcox 		 * buffered writes.  Some filesystems do this for writes to
4063fbbbad4bSMatthew Wilcox 		 * holes, for example.  For DAX files, a buffered write will
4064fbbbad4bSMatthew Wilcox 		 * not succeed (even if it did, DAX does not handle dirty
4065fbbbad4bSMatthew Wilcox 		 * page-cache pages correctly).
4066fbbbad4bSMatthew Wilcox 		 */
406744fff0faSChristoph Hellwig 		if (ret < 0 || !iov_iter_count(from) || IS_DAX(inode))
406844fff0faSChristoph Hellwig 			return ret;
406944fff0faSChristoph Hellwig 		return direct_write_fallback(iocb, from, ret,
407044fff0faSChristoph Hellwig 				generic_perform_write(iocb, from));
407144fff0faSChristoph Hellwig 	}
40723b93f911SAl Viro 
407344fff0faSChristoph Hellwig 	return generic_perform_write(iocb, from);
40741da177e4SLinus Torvalds }
40758174202bSAl Viro EXPORT_SYMBOL(__generic_file_write_iter);
40761da177e4SLinus Torvalds 
4077e4dd9de3SJan Kara /**
40788174202bSAl Viro  * generic_file_write_iter - write data to a file
4079e4dd9de3SJan Kara  * @iocb:	IO state structure
40808174202bSAl Viro  * @from:	iov_iter with data to write
4081e4dd9de3SJan Kara  *
40828174202bSAl Viro  * This is a wrapper around __generic_file_write_iter() to be used by most
4083e4dd9de3SJan Kara  * filesystems. It takes care of syncing the file in case of O_SYNC file
40849608703eSJan Kara  * and acquires i_rwsem as needed.
4085a862f68aSMike Rapoport  * Return:
4086a862f68aSMike Rapoport  * * negative error code if no data has been written at all of
4087a862f68aSMike Rapoport  *   vfs_fsync_range() failed for a synchronous write
4088a862f68aSMike Rapoport  * * number of bytes written, even for truncated writes
4089e4dd9de3SJan Kara  */
generic_file_write_iter(struct kiocb * iocb,struct iov_iter * from)40908174202bSAl Viro ssize_t generic_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
40911da177e4SLinus Torvalds {
40921da177e4SLinus Torvalds 	struct file *file = iocb->ki_filp;
4093148f948bSJan Kara 	struct inode *inode = file->f_mapping->host;
40941da177e4SLinus Torvalds 	ssize_t ret;
40951da177e4SLinus Torvalds 
40965955102cSAl Viro 	inode_lock(inode);
40973309dd04SAl Viro 	ret = generic_write_checks(iocb, from);
40983309dd04SAl Viro 	if (ret > 0)
40998174202bSAl Viro 		ret = __generic_file_write_iter(iocb, from);
41005955102cSAl Viro 	inode_unlock(inode);
41011da177e4SLinus Torvalds 
4102e2592217SChristoph Hellwig 	if (ret > 0)
4103e2592217SChristoph Hellwig 		ret = generic_write_sync(iocb, ret);
41041da177e4SLinus Torvalds 	return ret;
41051da177e4SLinus Torvalds }
41068174202bSAl Viro EXPORT_SYMBOL(generic_file_write_iter);
41071da177e4SLinus Torvalds 
4108cf9a2ae8SDavid Howells /**
410982c50f8bSMatthew Wilcox (Oracle)  * filemap_release_folio() - Release fs-specific metadata on a folio.
411082c50f8bSMatthew Wilcox (Oracle)  * @folio: The folio which the kernel is trying to free.
411182c50f8bSMatthew Wilcox (Oracle)  * @gfp: Memory allocation flags (and I/O mode).
4112cf9a2ae8SDavid Howells  *
411382c50f8bSMatthew Wilcox (Oracle)  * The address_space is trying to release any data attached to a folio
411482c50f8bSMatthew Wilcox (Oracle)  * (presumably at folio->private).
4115cf9a2ae8SDavid Howells  *
411682c50f8bSMatthew Wilcox (Oracle)  * This will also be called if the private_2 flag is set on a page,
411782c50f8bSMatthew Wilcox (Oracle)  * indicating that the folio has other metadata associated with it.
4118cf9a2ae8SDavid Howells  *
411982c50f8bSMatthew Wilcox (Oracle)  * The @gfp argument specifies whether I/O may be performed to release
412082c50f8bSMatthew Wilcox (Oracle)  * this page (__GFP_IO), and whether the call may block
412182c50f8bSMatthew Wilcox (Oracle)  * (__GFP_RECLAIM & __GFP_FS).
4122266cf658SDavid Howells  *
412382c50f8bSMatthew Wilcox (Oracle)  * Return: %true if the release was successful, otherwise %false.
4124cf9a2ae8SDavid Howells  */
filemap_release_folio(struct folio * folio,gfp_t gfp)412582c50f8bSMatthew Wilcox (Oracle) bool filemap_release_folio(struct folio *folio, gfp_t gfp)
4126cf9a2ae8SDavid Howells {
412782c50f8bSMatthew Wilcox (Oracle) 	struct address_space * const mapping = folio->mapping;
4128cf9a2ae8SDavid Howells 
412982c50f8bSMatthew Wilcox (Oracle) 	BUG_ON(!folio_test_locked(folio));
41300201ebf2SDavid Howells 	if (!folio_needs_release(folio))
41310201ebf2SDavid Howells 		return true;
413282c50f8bSMatthew Wilcox (Oracle) 	if (folio_test_writeback(folio))
413382c50f8bSMatthew Wilcox (Oracle) 		return false;
4134cf9a2ae8SDavid Howells 
4135fa29000bSMatthew Wilcox (Oracle) 	if (mapping && mapping->a_ops->release_folio)
4136fa29000bSMatthew Wilcox (Oracle) 		return mapping->a_ops->release_folio(folio, gfp);
413768189fefSMatthew Wilcox (Oracle) 	return try_to_free_buffers(folio);
4138cf9a2ae8SDavid Howells }
413982c50f8bSMatthew Wilcox (Oracle) EXPORT_SYMBOL(filemap_release_folio);
4140cf264e13SNhat Pham 
4141cf264e13SNhat Pham #ifdef CONFIG_CACHESTAT_SYSCALL
4142cf264e13SNhat Pham /**
4143cf264e13SNhat Pham  * filemap_cachestat() - compute the page cache statistics of a mapping
4144cf264e13SNhat Pham  * @mapping:	The mapping to compute the statistics for.
4145cf264e13SNhat Pham  * @first_index:	The starting page cache index.
4146cf264e13SNhat Pham  * @last_index:	The final page index (inclusive).
4147cf264e13SNhat Pham  * @cs:	the cachestat struct to write the result to.
4148cf264e13SNhat Pham  *
4149cf264e13SNhat Pham  * This will query the page cache statistics of a mapping in the
4150cf264e13SNhat Pham  * page range of [first_index, last_index] (inclusive). The statistics
4151cf264e13SNhat Pham  * queried include: number of dirty pages, number of pages marked for
4152cf264e13SNhat Pham  * writeback, and the number of (recently) evicted pages.
4153cf264e13SNhat Pham  */
filemap_cachestat(struct address_space * mapping,pgoff_t first_index,pgoff_t last_index,struct cachestat * cs)4154cf264e13SNhat Pham static void filemap_cachestat(struct address_space *mapping,
4155cf264e13SNhat Pham 		pgoff_t first_index, pgoff_t last_index, struct cachestat *cs)
4156cf264e13SNhat Pham {
4157cf264e13SNhat Pham 	XA_STATE(xas, &mapping->i_pages, first_index);
4158cf264e13SNhat Pham 	struct folio *folio;
4159cf264e13SNhat Pham 
4160cf264e13SNhat Pham 	rcu_read_lock();
4161cf264e13SNhat Pham 	xas_for_each(&xas, folio, last_index) {
4162ba60fdf7SNhat Pham 		int order;
4163cf264e13SNhat Pham 		unsigned long nr_pages;
4164cf264e13SNhat Pham 		pgoff_t folio_first_index, folio_last_index;
4165cf264e13SNhat Pham 
4166ba60fdf7SNhat Pham 		/*
4167ba60fdf7SNhat Pham 		 * Don't deref the folio. It is not pinned, and might
4168ba60fdf7SNhat Pham 		 * get freed (and reused) underneath us.
4169ba60fdf7SNhat Pham 		 *
4170ba60fdf7SNhat Pham 		 * We *could* pin it, but that would be expensive for
4171ba60fdf7SNhat Pham 		 * what should be a fast and lightweight syscall.
4172ba60fdf7SNhat Pham 		 *
4173ba60fdf7SNhat Pham 		 * Instead, derive all information of interest from
4174ba60fdf7SNhat Pham 		 * the rcu-protected xarray.
4175ba60fdf7SNhat Pham 		 */
4176ba60fdf7SNhat Pham 
4177cf264e13SNhat Pham 		if (xas_retry(&xas, folio))
4178cf264e13SNhat Pham 			continue;
4179cf264e13SNhat Pham 
4180ba60fdf7SNhat Pham 		order = xa_get_order(xas.xa, xas.xa_index);
4181cf264e13SNhat Pham 		nr_pages = 1 << order;
4182cf264e13SNhat Pham 		folio_first_index = round_down(xas.xa_index, 1 << order);
4183cf264e13SNhat Pham 		folio_last_index = folio_first_index + nr_pages - 1;
4184cf264e13SNhat Pham 
4185cf264e13SNhat Pham 		/* Folios might straddle the range boundaries, only count covered pages */
4186cf264e13SNhat Pham 		if (folio_first_index < first_index)
4187cf264e13SNhat Pham 			nr_pages -= first_index - folio_first_index;
4188cf264e13SNhat Pham 
4189cf264e13SNhat Pham 		if (folio_last_index > last_index)
4190cf264e13SNhat Pham 			nr_pages -= folio_last_index - last_index;
4191cf264e13SNhat Pham 
4192ba60fdf7SNhat Pham 		if (xa_is_value(folio)) {
4193ba60fdf7SNhat Pham 			/* page is evicted */
4194ba60fdf7SNhat Pham 			void *shadow = (void *)folio;
4195ba60fdf7SNhat Pham 			bool workingset; /* not used */
4196ba60fdf7SNhat Pham 
4197cf264e13SNhat Pham 			cs->nr_evicted += nr_pages;
4198cf264e13SNhat Pham 
4199cf264e13SNhat Pham #ifdef CONFIG_SWAP /* implies CONFIG_MMU */
4200cf264e13SNhat Pham 			if (shmem_mapping(mapping)) {
4201cf264e13SNhat Pham 				/* shmem file - in swap cache */
4202cf264e13SNhat Pham 				swp_entry_t swp = radix_to_swp_entry(folio);
4203cf264e13SNhat Pham 
4204b79f9e1fSJohannes Weiner 				/* swapin error results in poisoned entry */
4205b79f9e1fSJohannes Weiner 				if (non_swap_entry(swp))
4206b79f9e1fSJohannes Weiner 					goto resched;
4207b79f9e1fSJohannes Weiner 
4208b79f9e1fSJohannes Weiner 				/*
4209b79f9e1fSJohannes Weiner 				 * Getting a swap entry from the shmem
4210b79f9e1fSJohannes Weiner 				 * inode means we beat
4211b79f9e1fSJohannes Weiner 				 * shmem_unuse(). rcu_read_lock()
4212b79f9e1fSJohannes Weiner 				 * ensures swapoff waits for us before
4213b79f9e1fSJohannes Weiner 				 * freeing the swapper space. However,
4214b79f9e1fSJohannes Weiner 				 * we can race with swapping and
4215b79f9e1fSJohannes Weiner 				 * invalidation, so there might not be
4216b79f9e1fSJohannes Weiner 				 * a shadow in the swapcache (yet).
4217b79f9e1fSJohannes Weiner 				 */
4218cf264e13SNhat Pham 				shadow = get_shadow_from_swap_cache(swp);
4219b79f9e1fSJohannes Weiner 				if (!shadow)
4220b79f9e1fSJohannes Weiner 					goto resched;
4221cf264e13SNhat Pham 			}
4222cf264e13SNhat Pham #endif
4223cf264e13SNhat Pham 			if (workingset_test_recent(shadow, true, &workingset))
4224cf264e13SNhat Pham 				cs->nr_recently_evicted += nr_pages;
4225cf264e13SNhat Pham 
4226cf264e13SNhat Pham 			goto resched;
4227cf264e13SNhat Pham 		}
4228cf264e13SNhat Pham 
4229cf264e13SNhat Pham 		/* page is in cache */
4230cf264e13SNhat Pham 		cs->nr_cache += nr_pages;
4231cf264e13SNhat Pham 
4232ba60fdf7SNhat Pham 		if (xas_get_mark(&xas, PAGECACHE_TAG_DIRTY))
4233cf264e13SNhat Pham 			cs->nr_dirty += nr_pages;
4234cf264e13SNhat Pham 
4235ba60fdf7SNhat Pham 		if (xas_get_mark(&xas, PAGECACHE_TAG_WRITEBACK))
4236cf264e13SNhat Pham 			cs->nr_writeback += nr_pages;
4237cf264e13SNhat Pham 
4238cf264e13SNhat Pham resched:
4239cf264e13SNhat Pham 		if (need_resched()) {
4240cf264e13SNhat Pham 			xas_pause(&xas);
4241cf264e13SNhat Pham 			cond_resched_rcu();
4242cf264e13SNhat Pham 		}
4243cf264e13SNhat Pham 	}
4244cf264e13SNhat Pham 	rcu_read_unlock();
4245cf264e13SNhat Pham }
4246cf264e13SNhat Pham 
4247cf264e13SNhat Pham /*
4248cf264e13SNhat Pham  * The cachestat(2) system call.
4249cf264e13SNhat Pham  *
4250cf264e13SNhat Pham  * cachestat() returns the page cache statistics of a file in the
4251cf264e13SNhat Pham  * bytes range specified by `off` and `len`: number of cached pages,
4252cf264e13SNhat Pham  * number of dirty pages, number of pages marked for writeback,
4253cf264e13SNhat Pham  * number of evicted pages, and number of recently evicted pages.
4254cf264e13SNhat Pham  *
4255cf264e13SNhat Pham  * An evicted page is a page that is previously in the page cache
4256cf264e13SNhat Pham  * but has been evicted since. A page is recently evicted if its last
4257cf264e13SNhat Pham  * eviction was recent enough that its reentry to the cache would
4258cf264e13SNhat Pham  * indicate that it is actively being used by the system, and that
4259cf264e13SNhat Pham  * there is memory pressure on the system.
4260cf264e13SNhat Pham  *
4261cf264e13SNhat Pham  * `off` and `len` must be non-negative integers. If `len` > 0,
4262cf264e13SNhat Pham  * the queried range is [`off`, `off` + `len`]. If `len` == 0,
4263cf264e13SNhat Pham  * we will query in the range from `off` to the end of the file.
4264cf264e13SNhat Pham  *
4265cf264e13SNhat Pham  * The `flags` argument is unused for now, but is included for future
4266cf264e13SNhat Pham  * extensibility. User should pass 0 (i.e no flag specified).
4267cf264e13SNhat Pham  *
4268cf264e13SNhat Pham  * Currently, hugetlbfs is not supported.
4269cf264e13SNhat Pham  *
4270cf264e13SNhat Pham  * Because the status of a page can change after cachestat() checks it
4271cf264e13SNhat Pham  * but before it returns to the application, the returned values may
4272cf264e13SNhat Pham  * contain stale information.
4273cf264e13SNhat Pham  *
4274cf264e13SNhat Pham  * return values:
4275cf264e13SNhat Pham  *  zero        - success
4276cf264e13SNhat Pham  *  -EFAULT     - cstat or cstat_range points to an illegal address
4277cf264e13SNhat Pham  *  -EINVAL     - invalid flags
4278cf264e13SNhat Pham  *  -EBADF      - invalid file descriptor
4279cf264e13SNhat Pham  *  -EOPNOTSUPP - file descriptor is of a hugetlbfs file
4280cf264e13SNhat Pham  */
SYSCALL_DEFINE4(cachestat,unsigned int,fd,struct cachestat_range __user *,cstat_range,struct cachestat __user *,cstat,unsigned int,flags)4281cf264e13SNhat Pham SYSCALL_DEFINE4(cachestat, unsigned int, fd,
4282cf264e13SNhat Pham 		struct cachestat_range __user *, cstat_range,
4283cf264e13SNhat Pham 		struct cachestat __user *, cstat, unsigned int, flags)
4284cf264e13SNhat Pham {
4285cf264e13SNhat Pham 	struct fd f = fdget(fd);
4286cf264e13SNhat Pham 	struct address_space *mapping;
4287cf264e13SNhat Pham 	struct cachestat_range csr;
4288cf264e13SNhat Pham 	struct cachestat cs;
4289cf264e13SNhat Pham 	pgoff_t first_index, last_index;
4290cf264e13SNhat Pham 
4291cf264e13SNhat Pham 	if (!f.file)
4292cf264e13SNhat Pham 		return -EBADF;
4293cf264e13SNhat Pham 
4294cf264e13SNhat Pham 	if (copy_from_user(&csr, cstat_range,
4295cf264e13SNhat Pham 			sizeof(struct cachestat_range))) {
4296cf264e13SNhat Pham 		fdput(f);
4297cf264e13SNhat Pham 		return -EFAULT;
4298cf264e13SNhat Pham 	}
4299cf264e13SNhat Pham 
4300cf264e13SNhat Pham 	/* hugetlbfs is not supported */
4301cf264e13SNhat Pham 	if (is_file_hugepages(f.file)) {
4302cf264e13SNhat Pham 		fdput(f);
4303cf264e13SNhat Pham 		return -EOPNOTSUPP;
4304cf264e13SNhat Pham 	}
4305cf264e13SNhat Pham 
4306cf264e13SNhat Pham 	if (flags != 0) {
4307cf264e13SNhat Pham 		fdput(f);
4308cf264e13SNhat Pham 		return -EINVAL;
4309cf264e13SNhat Pham 	}
4310cf264e13SNhat Pham 
4311cf264e13SNhat Pham 	first_index = csr.off >> PAGE_SHIFT;
4312cf264e13SNhat Pham 	last_index =
4313cf264e13SNhat Pham 		csr.len == 0 ? ULONG_MAX : (csr.off + csr.len - 1) >> PAGE_SHIFT;
4314cf264e13SNhat Pham 	memset(&cs, 0, sizeof(struct cachestat));
4315cf264e13SNhat Pham 	mapping = f.file->f_mapping;
4316cf264e13SNhat Pham 	filemap_cachestat(mapping, first_index, last_index, &cs);
4317cf264e13SNhat Pham 	fdput(f);
4318cf264e13SNhat Pham 
4319cf264e13SNhat Pham 	if (copy_to_user(cstat, &cs, sizeof(struct cachestat)))
4320cf264e13SNhat Pham 		return -EFAULT;
4321cf264e13SNhat Pham 
4322cf264e13SNhat Pham 	return 0;
4323cf264e13SNhat Pham }
4324cf264e13SNhat Pham #endif /* CONFIG_CACHESTAT_SYSCALL */
4325