xref: /linux/mm/rmap.c (revision 2e3468778dbe3ec389a10c21a703bb8e5be5cfbc)
11da177e4SLinus Torvalds /*
21da177e4SLinus Torvalds  * mm/rmap.c - physical to virtual reverse mappings
31da177e4SLinus Torvalds  *
41da177e4SLinus Torvalds  * Copyright 2001, Rik van Riel <riel@conectiva.com.br>
51da177e4SLinus Torvalds  * Released under the General Public License (GPL).
61da177e4SLinus Torvalds  *
71da177e4SLinus Torvalds  * Simple, low overhead reverse mapping scheme.
81da177e4SLinus Torvalds  * Please try to keep this thing as modular as possible.
91da177e4SLinus Torvalds  *
101da177e4SLinus Torvalds  * Provides methods for unmapping each kind of mapped page:
111da177e4SLinus Torvalds  * the anon methods track anonymous pages, and
121da177e4SLinus Torvalds  * the file methods track pages belonging to an inode.
131da177e4SLinus Torvalds  *
141da177e4SLinus Torvalds  * Original design by Rik van Riel <riel@conectiva.com.br> 2001
151da177e4SLinus Torvalds  * File methods by Dave McCracken <dmccr@us.ibm.com> 2003, 2004
161da177e4SLinus Torvalds  * Anonymous methods by Andrea Arcangeli <andrea@suse.de> 2004
1798f32602SHugh Dickins  * Contributions by Hugh Dickins 2003, 2004
181da177e4SLinus Torvalds  */
191da177e4SLinus Torvalds 
201da177e4SLinus Torvalds /*
211da177e4SLinus Torvalds  * Lock ordering in mm:
221da177e4SLinus Torvalds  *
239608703eSJan Kara  * inode->i_rwsem	(while writing or truncating, not reading or faulting)
24c1e8d7c6SMichel Lespinasse  *   mm->mmap_lock
25730633f0SJan Kara  *     mapping->invalidate_lock (in filemap_fault)
269608703eSJan Kara  *       page->flags PG_locked (lock_page)   * (see hugetlbfs below)
2788f306b6SKirill A. Shutemov  *         hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share)
28c8c06efaSDavidlohr Bueso  *           mapping->i_mmap_rwsem
29c0d0381aSMike Kravetz  *             hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
305a505085SIngo Molnar  *             anon_vma->rwsem
31b8072f09SHugh Dickins  *               mm->page_table_lock or pte_lock
325d337b91SHugh Dickins  *                 swap_lock (in swap_duplicate, swap_info_get)
331da177e4SLinus Torvalds  *                   mmlist_lock (in mmput, drain_mmlist and others)
34e621900aSMatthew Wilcox (Oracle)  *                   mapping->private_lock (in block_dirty_folio)
35e621900aSMatthew Wilcox (Oracle)  *                     folio_lock_memcg move_lock (in block_dirty_folio)
36b93b0163SMatthew Wilcox  *                       i_pages lock (widely used)
37e809c3feSMatthew Wilcox (Oracle)  *                         lruvec->lru_lock (in folio_lruvec_lock_irq)
38250df6edSDave Chinner  *                   inode->i_lock (in set_page_dirty's __mark_inode_dirty)
39f758eeabSChristoph Hellwig  *                   bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
401da177e4SLinus Torvalds  *                     sb_lock (within inode_lock in fs/fs-writeback.c)
41b93b0163SMatthew Wilcox  *                     i_pages lock (widely used, in set_page_dirty,
421da177e4SLinus Torvalds  *                               in arch-dependent flush_dcache_mmap_lock,
43f758eeabSChristoph Hellwig  *                               within bdi.wb->list_lock in __sync_single_inode)
446a46079cSAndi Kleen  *
459608703eSJan Kara  * anon_vma->rwsem,mapping->i_mmap_rwsem   (memory_failure, collect_procs_anon)
466a46079cSAndi Kleen  *   ->tasklist_lock
476a46079cSAndi Kleen  *     pte map lock
48c0d0381aSMike Kravetz  *
49c0d0381aSMike Kravetz  * * hugetlbfs PageHuge() pages take locks in this order:
50c0d0381aSMike Kravetz  *         mapping->i_mmap_rwsem
51c0d0381aSMike Kravetz  *           hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
52c0d0381aSMike Kravetz  *             page->flags PG_locked (lock_page)
531da177e4SLinus Torvalds  */
541da177e4SLinus Torvalds 
551da177e4SLinus Torvalds #include <linux/mm.h>
566e84f315SIngo Molnar #include <linux/sched/mm.h>
5729930025SIngo Molnar #include <linux/sched/task.h>
581da177e4SLinus Torvalds #include <linux/pagemap.h>
591da177e4SLinus Torvalds #include <linux/swap.h>
601da177e4SLinus Torvalds #include <linux/swapops.h>
611da177e4SLinus Torvalds #include <linux/slab.h>
621da177e4SLinus Torvalds #include <linux/init.h>
635ad64688SHugh Dickins #include <linux/ksm.h>
641da177e4SLinus Torvalds #include <linux/rmap.h>
651da177e4SLinus Torvalds #include <linux/rcupdate.h>
66b95f1b31SPaul Gortmaker #include <linux/export.h>
678a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
68cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
6964cdd548SKOSAKI Motohiro #include <linux/migrate.h>
700fe6e20bSNaoya Horiguchi #include <linux/hugetlb.h>
71444f84fdSBen Dooks #include <linux/huge_mm.h>
72ef5d437fSJan Kara #include <linux/backing-dev.h>
7333c3fc71SVladimir Davydov #include <linux/page_idle.h>
74a5430ddaSJérôme Glisse #include <linux/memremap.h>
75bce73e48SChristian Borntraeger #include <linux/userfaultfd_k.h>
76999dad82SPeter Xu #include <linux/mm_inline.h>
771da177e4SLinus Torvalds 
781da177e4SLinus Torvalds #include <asm/tlbflush.h>
791da177e4SLinus Torvalds 
804cc79b33SAnshuman Khandual #define CREATE_TRACE_POINTS
8172b252aeSMel Gorman #include <trace/events/tlb.h>
824cc79b33SAnshuman Khandual #include <trace/events/migrate.h>
8372b252aeSMel Gorman 
84b291f000SNick Piggin #include "internal.h"
85b291f000SNick Piggin 
86fdd2e5f8SAdrian Bunk static struct kmem_cache *anon_vma_cachep;
875beb4930SRik van Riel static struct kmem_cache *anon_vma_chain_cachep;
88fdd2e5f8SAdrian Bunk 
89fdd2e5f8SAdrian Bunk static inline struct anon_vma *anon_vma_alloc(void)
90fdd2e5f8SAdrian Bunk {
9101d8b20dSPeter Zijlstra 	struct anon_vma *anon_vma;
9201d8b20dSPeter Zijlstra 
9301d8b20dSPeter Zijlstra 	anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
9401d8b20dSPeter Zijlstra 	if (anon_vma) {
9501d8b20dSPeter Zijlstra 		atomic_set(&anon_vma->refcount, 1);
967a3ef208SKonstantin Khlebnikov 		anon_vma->degree = 1;	/* Reference for first vma */
977a3ef208SKonstantin Khlebnikov 		anon_vma->parent = anon_vma;
9801d8b20dSPeter Zijlstra 		/*
9901d8b20dSPeter Zijlstra 		 * Initialise the anon_vma root to point to itself. If called
10001d8b20dSPeter Zijlstra 		 * from fork, the root will be reset to the parents anon_vma.
10101d8b20dSPeter Zijlstra 		 */
10201d8b20dSPeter Zijlstra 		anon_vma->root = anon_vma;
103fdd2e5f8SAdrian Bunk 	}
104fdd2e5f8SAdrian Bunk 
10501d8b20dSPeter Zijlstra 	return anon_vma;
10601d8b20dSPeter Zijlstra }
10701d8b20dSPeter Zijlstra 
10801d8b20dSPeter Zijlstra static inline void anon_vma_free(struct anon_vma *anon_vma)
109fdd2e5f8SAdrian Bunk {
11001d8b20dSPeter Zijlstra 	VM_BUG_ON(atomic_read(&anon_vma->refcount));
11188c22088SPeter Zijlstra 
11288c22088SPeter Zijlstra 	/*
1132f031c6fSMatthew Wilcox (Oracle) 	 * Synchronize against folio_lock_anon_vma_read() such that
11488c22088SPeter Zijlstra 	 * we can safely hold the lock without the anon_vma getting
11588c22088SPeter Zijlstra 	 * freed.
11688c22088SPeter Zijlstra 	 *
11788c22088SPeter Zijlstra 	 * Relies on the full mb implied by the atomic_dec_and_test() from
11888c22088SPeter Zijlstra 	 * put_anon_vma() against the acquire barrier implied by
1192f031c6fSMatthew Wilcox (Oracle) 	 * down_read_trylock() from folio_lock_anon_vma_read(). This orders:
12088c22088SPeter Zijlstra 	 *
1212f031c6fSMatthew Wilcox (Oracle) 	 * folio_lock_anon_vma_read()	VS	put_anon_vma()
1224fc3f1d6SIngo Molnar 	 *   down_read_trylock()		  atomic_dec_and_test()
12388c22088SPeter Zijlstra 	 *   LOCK				  MB
1244fc3f1d6SIngo Molnar 	 *   atomic_read()			  rwsem_is_locked()
12588c22088SPeter Zijlstra 	 *
12688c22088SPeter Zijlstra 	 * LOCK should suffice since the actual taking of the lock must
12788c22088SPeter Zijlstra 	 * happen _before_ what follows.
12888c22088SPeter Zijlstra 	 */
1297f39dda9SHugh Dickins 	might_sleep();
1305a505085SIngo Molnar 	if (rwsem_is_locked(&anon_vma->root->rwsem)) {
1314fc3f1d6SIngo Molnar 		anon_vma_lock_write(anon_vma);
13208b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
13388c22088SPeter Zijlstra 	}
13488c22088SPeter Zijlstra 
135fdd2e5f8SAdrian Bunk 	kmem_cache_free(anon_vma_cachep, anon_vma);
136fdd2e5f8SAdrian Bunk }
1371da177e4SLinus Torvalds 
138dd34739cSLinus Torvalds static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
1395beb4930SRik van Riel {
140dd34739cSLinus Torvalds 	return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
1415beb4930SRik van Riel }
1425beb4930SRik van Riel 
143e574b5fdSNamhyung Kim static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
1445beb4930SRik van Riel {
1455beb4930SRik van Riel 	kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
1465beb4930SRik van Riel }
1475beb4930SRik van Riel 
1486583a843SKautuk Consul static void anon_vma_chain_link(struct vm_area_struct *vma,
1496583a843SKautuk Consul 				struct anon_vma_chain *avc,
1506583a843SKautuk Consul 				struct anon_vma *anon_vma)
1516583a843SKautuk Consul {
1526583a843SKautuk Consul 	avc->vma = vma;
1536583a843SKautuk Consul 	avc->anon_vma = anon_vma;
1546583a843SKautuk Consul 	list_add(&avc->same_vma, &vma->anon_vma_chain);
155bf181b9fSMichel Lespinasse 	anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
1566583a843SKautuk Consul }
1576583a843SKautuk Consul 
158d9d332e0SLinus Torvalds /**
159d5a187daSVlastimil Babka  * __anon_vma_prepare - attach an anon_vma to a memory region
160d9d332e0SLinus Torvalds  * @vma: the memory region in question
161d9d332e0SLinus Torvalds  *
162d9d332e0SLinus Torvalds  * This makes sure the memory mapping described by 'vma' has
163d9d332e0SLinus Torvalds  * an 'anon_vma' attached to it, so that we can associate the
164d9d332e0SLinus Torvalds  * anonymous pages mapped into it with that anon_vma.
165d9d332e0SLinus Torvalds  *
166d5a187daSVlastimil Babka  * The common case will be that we already have one, which
167d5a187daSVlastimil Babka  * is handled inline by anon_vma_prepare(). But if
16823a0790aSFigo.zhang  * not we either need to find an adjacent mapping that we
169d9d332e0SLinus Torvalds  * can re-use the anon_vma from (very common when the only
170d9d332e0SLinus Torvalds  * reason for splitting a vma has been mprotect()), or we
171d9d332e0SLinus Torvalds  * allocate a new one.
172d9d332e0SLinus Torvalds  *
173d9d332e0SLinus Torvalds  * Anon-vma allocations are very subtle, because we may have
1742f031c6fSMatthew Wilcox (Oracle)  * optimistically looked up an anon_vma in folio_lock_anon_vma_read()
175aaf1f990SMiaohe Lin  * and that may actually touch the rwsem even in the newly
176d9d332e0SLinus Torvalds  * allocated vma (it depends on RCU to make sure that the
177d9d332e0SLinus Torvalds  * anon_vma isn't actually destroyed).
178d9d332e0SLinus Torvalds  *
179d9d332e0SLinus Torvalds  * As a result, we need to do proper anon_vma locking even
180d9d332e0SLinus Torvalds  * for the new allocation. At the same time, we do not want
181d9d332e0SLinus Torvalds  * to do any locking for the common case of already having
182d9d332e0SLinus Torvalds  * an anon_vma.
183d9d332e0SLinus Torvalds  *
184c1e8d7c6SMichel Lespinasse  * This must be called with the mmap_lock held for reading.
185d9d332e0SLinus Torvalds  */
186d5a187daSVlastimil Babka int __anon_vma_prepare(struct vm_area_struct *vma)
1871da177e4SLinus Torvalds {
188d5a187daSVlastimil Babka 	struct mm_struct *mm = vma->vm_mm;
189d5a187daSVlastimil Babka 	struct anon_vma *anon_vma, *allocated;
1905beb4930SRik van Riel 	struct anon_vma_chain *avc;
1911da177e4SLinus Torvalds 
1921da177e4SLinus Torvalds 	might_sleep();
1931da177e4SLinus Torvalds 
194dd34739cSLinus Torvalds 	avc = anon_vma_chain_alloc(GFP_KERNEL);
1955beb4930SRik van Riel 	if (!avc)
1965beb4930SRik van Riel 		goto out_enomem;
1975beb4930SRik van Riel 
1981da177e4SLinus Torvalds 	anon_vma = find_mergeable_anon_vma(vma);
1991da177e4SLinus Torvalds 	allocated = NULL;
200d9d332e0SLinus Torvalds 	if (!anon_vma) {
2011da177e4SLinus Torvalds 		anon_vma = anon_vma_alloc();
2021da177e4SLinus Torvalds 		if (unlikely(!anon_vma))
2035beb4930SRik van Riel 			goto out_enomem_free_avc;
2041da177e4SLinus Torvalds 		allocated = anon_vma;
2051da177e4SLinus Torvalds 	}
2061da177e4SLinus Torvalds 
2074fc3f1d6SIngo Molnar 	anon_vma_lock_write(anon_vma);
2081da177e4SLinus Torvalds 	/* page_table_lock to protect against threads */
2091da177e4SLinus Torvalds 	spin_lock(&mm->page_table_lock);
2101da177e4SLinus Torvalds 	if (likely(!vma->anon_vma)) {
2111da177e4SLinus Torvalds 		vma->anon_vma = anon_vma;
2126583a843SKautuk Consul 		anon_vma_chain_link(vma, avc, anon_vma);
2137a3ef208SKonstantin Khlebnikov 		/* vma reference or self-parent link for new root */
2147a3ef208SKonstantin Khlebnikov 		anon_vma->degree++;
2151da177e4SLinus Torvalds 		allocated = NULL;
21631f2b0ebSOleg Nesterov 		avc = NULL;
2171da177e4SLinus Torvalds 	}
2181da177e4SLinus Torvalds 	spin_unlock(&mm->page_table_lock);
21908b52706SKonstantin Khlebnikov 	anon_vma_unlock_write(anon_vma);
22031f2b0ebSOleg Nesterov 
22131f2b0ebSOleg Nesterov 	if (unlikely(allocated))
22201d8b20dSPeter Zijlstra 		put_anon_vma(allocated);
22331f2b0ebSOleg Nesterov 	if (unlikely(avc))
2245beb4930SRik van Riel 		anon_vma_chain_free(avc);
225d5a187daSVlastimil Babka 
2261da177e4SLinus Torvalds 	return 0;
2275beb4930SRik van Riel 
2285beb4930SRik van Riel  out_enomem_free_avc:
2295beb4930SRik van Riel 	anon_vma_chain_free(avc);
2305beb4930SRik van Riel  out_enomem:
2315beb4930SRik van Riel 	return -ENOMEM;
2321da177e4SLinus Torvalds }
2331da177e4SLinus Torvalds 
234bb4aa396SLinus Torvalds /*
235bb4aa396SLinus Torvalds  * This is a useful helper function for locking the anon_vma root as
236bb4aa396SLinus Torvalds  * we traverse the vma->anon_vma_chain, looping over anon_vma's that
237bb4aa396SLinus Torvalds  * have the same vma.
238bb4aa396SLinus Torvalds  *
239bb4aa396SLinus Torvalds  * Such anon_vma's should have the same root, so you'd expect to see
240bb4aa396SLinus Torvalds  * just a single mutex_lock for the whole traversal.
241bb4aa396SLinus Torvalds  */
242bb4aa396SLinus Torvalds static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
243bb4aa396SLinus Torvalds {
244bb4aa396SLinus Torvalds 	struct anon_vma *new_root = anon_vma->root;
245bb4aa396SLinus Torvalds 	if (new_root != root) {
246bb4aa396SLinus Torvalds 		if (WARN_ON_ONCE(root))
2475a505085SIngo Molnar 			up_write(&root->rwsem);
248bb4aa396SLinus Torvalds 		root = new_root;
2495a505085SIngo Molnar 		down_write(&root->rwsem);
250bb4aa396SLinus Torvalds 	}
251bb4aa396SLinus Torvalds 	return root;
252bb4aa396SLinus Torvalds }
253bb4aa396SLinus Torvalds 
254bb4aa396SLinus Torvalds static inline void unlock_anon_vma_root(struct anon_vma *root)
255bb4aa396SLinus Torvalds {
256bb4aa396SLinus Torvalds 	if (root)
2575a505085SIngo Molnar 		up_write(&root->rwsem);
258bb4aa396SLinus Torvalds }
259bb4aa396SLinus Torvalds 
2605beb4930SRik van Riel /*
2615beb4930SRik van Riel  * Attach the anon_vmas from src to dst.
2625beb4930SRik van Riel  * Returns 0 on success, -ENOMEM on failure.
2637a3ef208SKonstantin Khlebnikov  *
264cb152a1aSShijie Luo  * anon_vma_clone() is called by __vma_adjust(), __split_vma(), copy_vma() and
26547b390d2SWei Yang  * anon_vma_fork(). The first three want an exact copy of src, while the last
26647b390d2SWei Yang  * one, anon_vma_fork(), may try to reuse an existing anon_vma to prevent
26747b390d2SWei Yang  * endless growth of anon_vma. Since dst->anon_vma is set to NULL before call,
26847b390d2SWei Yang  * we can identify this case by checking (!dst->anon_vma && src->anon_vma).
26947b390d2SWei Yang  *
27047b390d2SWei Yang  * If (!dst->anon_vma && src->anon_vma) is true, this function tries to find
27147b390d2SWei Yang  * and reuse existing anon_vma which has no vmas and only one child anon_vma.
27247b390d2SWei Yang  * This prevents degradation of anon_vma hierarchy to endless linear chain in
27347b390d2SWei Yang  * case of constantly forking task. On the other hand, an anon_vma with more
27447b390d2SWei Yang  * than one child isn't reused even if there was no alive vma, thus rmap
27547b390d2SWei Yang  * walker has a good chance of avoiding scanning the whole hierarchy when it
27647b390d2SWei Yang  * searches where page is mapped.
2775beb4930SRik van Riel  */
2785beb4930SRik van Riel int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
2795beb4930SRik van Riel {
2805beb4930SRik van Riel 	struct anon_vma_chain *avc, *pavc;
281bb4aa396SLinus Torvalds 	struct anon_vma *root = NULL;
2825beb4930SRik van Riel 
283646d87b4SLinus Torvalds 	list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
284bb4aa396SLinus Torvalds 		struct anon_vma *anon_vma;
285bb4aa396SLinus Torvalds 
286dd34739cSLinus Torvalds 		avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
287dd34739cSLinus Torvalds 		if (unlikely(!avc)) {
288dd34739cSLinus Torvalds 			unlock_anon_vma_root(root);
289dd34739cSLinus Torvalds 			root = NULL;
290dd34739cSLinus Torvalds 			avc = anon_vma_chain_alloc(GFP_KERNEL);
2915beb4930SRik van Riel 			if (!avc)
2925beb4930SRik van Riel 				goto enomem_failure;
293dd34739cSLinus Torvalds 		}
294bb4aa396SLinus Torvalds 		anon_vma = pavc->anon_vma;
295bb4aa396SLinus Torvalds 		root = lock_anon_vma_root(root, anon_vma);
296bb4aa396SLinus Torvalds 		anon_vma_chain_link(dst, avc, anon_vma);
2977a3ef208SKonstantin Khlebnikov 
2987a3ef208SKonstantin Khlebnikov 		/*
2997a3ef208SKonstantin Khlebnikov 		 * Reuse existing anon_vma if its degree lower than two,
3007a3ef208SKonstantin Khlebnikov 		 * that means it has no vma and only one anon_vma child.
3017a3ef208SKonstantin Khlebnikov 		 *
302dd062302SAdrian Huang 		 * Do not choose parent anon_vma, otherwise first child
3037a3ef208SKonstantin Khlebnikov 		 * will always reuse it. Root anon_vma is never reused:
3047a3ef208SKonstantin Khlebnikov 		 * it has self-parent reference and at least one child.
3057a3ef208SKonstantin Khlebnikov 		 */
30647b390d2SWei Yang 		if (!dst->anon_vma && src->anon_vma &&
30747b390d2SWei Yang 		    anon_vma != src->anon_vma && anon_vma->degree < 2)
3087a3ef208SKonstantin Khlebnikov 			dst->anon_vma = anon_vma;
3095beb4930SRik van Riel 	}
3107a3ef208SKonstantin Khlebnikov 	if (dst->anon_vma)
3117a3ef208SKonstantin Khlebnikov 		dst->anon_vma->degree++;
312bb4aa396SLinus Torvalds 	unlock_anon_vma_root(root);
3135beb4930SRik van Riel 	return 0;
3145beb4930SRik van Riel 
3155beb4930SRik van Riel  enomem_failure:
3163fe89b3eSLeon Yu 	/*
3173fe89b3eSLeon Yu 	 * dst->anon_vma is dropped here otherwise its degree can be incorrectly
3183fe89b3eSLeon Yu 	 * decremented in unlink_anon_vmas().
3193fe89b3eSLeon Yu 	 * We can safely do this because callers of anon_vma_clone() don't care
3203fe89b3eSLeon Yu 	 * about dst->anon_vma if anon_vma_clone() failed.
3213fe89b3eSLeon Yu 	 */
3223fe89b3eSLeon Yu 	dst->anon_vma = NULL;
3235beb4930SRik van Riel 	unlink_anon_vmas(dst);
3245beb4930SRik van Riel 	return -ENOMEM;
3251da177e4SLinus Torvalds }
3261da177e4SLinus Torvalds 
3275beb4930SRik van Riel /*
3285beb4930SRik van Riel  * Attach vma to its own anon_vma, as well as to the anon_vmas that
3295beb4930SRik van Riel  * the corresponding VMA in the parent process is attached to.
3305beb4930SRik van Riel  * Returns 0 on success, non-zero on failure.
3315beb4930SRik van Riel  */
3325beb4930SRik van Riel int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
3331da177e4SLinus Torvalds {
3345beb4930SRik van Riel 	struct anon_vma_chain *avc;
3355beb4930SRik van Riel 	struct anon_vma *anon_vma;
336c4ea95d7SDaniel Forrest 	int error;
3375beb4930SRik van Riel 
3385beb4930SRik van Riel 	/* Don't bother if the parent process has no anon_vma here. */
3395beb4930SRik van Riel 	if (!pvma->anon_vma)
3405beb4930SRik van Riel 		return 0;
3415beb4930SRik van Riel 
3427a3ef208SKonstantin Khlebnikov 	/* Drop inherited anon_vma, we'll reuse existing or allocate new. */
3437a3ef208SKonstantin Khlebnikov 	vma->anon_vma = NULL;
3447a3ef208SKonstantin Khlebnikov 
3455beb4930SRik van Riel 	/*
3465beb4930SRik van Riel 	 * First, attach the new VMA to the parent VMA's anon_vmas,
3475beb4930SRik van Riel 	 * so rmap can find non-COWed pages in child processes.
3485beb4930SRik van Riel 	 */
349c4ea95d7SDaniel Forrest 	error = anon_vma_clone(vma, pvma);
350c4ea95d7SDaniel Forrest 	if (error)
351c4ea95d7SDaniel Forrest 		return error;
3525beb4930SRik van Riel 
3537a3ef208SKonstantin Khlebnikov 	/* An existing anon_vma has been reused, all done then. */
3547a3ef208SKonstantin Khlebnikov 	if (vma->anon_vma)
3557a3ef208SKonstantin Khlebnikov 		return 0;
3567a3ef208SKonstantin Khlebnikov 
3575beb4930SRik van Riel 	/* Then add our own anon_vma. */
3585beb4930SRik van Riel 	anon_vma = anon_vma_alloc();
3595beb4930SRik van Riel 	if (!anon_vma)
3605beb4930SRik van Riel 		goto out_error;
361dd34739cSLinus Torvalds 	avc = anon_vma_chain_alloc(GFP_KERNEL);
3625beb4930SRik van Riel 	if (!avc)
3635beb4930SRik van Riel 		goto out_error_free_anon_vma;
3645c341ee1SRik van Riel 
3655c341ee1SRik van Riel 	/*
366aaf1f990SMiaohe Lin 	 * The root anon_vma's rwsem is the lock actually used when we
3675c341ee1SRik van Riel 	 * lock any of the anon_vmas in this anon_vma tree.
3685c341ee1SRik van Riel 	 */
3695c341ee1SRik van Riel 	anon_vma->root = pvma->anon_vma->root;
3707a3ef208SKonstantin Khlebnikov 	anon_vma->parent = pvma->anon_vma;
37176545066SRik van Riel 	/*
37201d8b20dSPeter Zijlstra 	 * With refcounts, an anon_vma can stay around longer than the
37301d8b20dSPeter Zijlstra 	 * process it belongs to. The root anon_vma needs to be pinned until
37401d8b20dSPeter Zijlstra 	 * this anon_vma is freed, because the lock lives in the root.
37576545066SRik van Riel 	 */
37676545066SRik van Riel 	get_anon_vma(anon_vma->root);
3775beb4930SRik van Riel 	/* Mark this anon_vma as the one where our new (COWed) pages go. */
3785beb4930SRik van Riel 	vma->anon_vma = anon_vma;
3794fc3f1d6SIngo Molnar 	anon_vma_lock_write(anon_vma);
3805c341ee1SRik van Riel 	anon_vma_chain_link(vma, avc, anon_vma);
3817a3ef208SKonstantin Khlebnikov 	anon_vma->parent->degree++;
38208b52706SKonstantin Khlebnikov 	anon_vma_unlock_write(anon_vma);
3835beb4930SRik van Riel 
3845beb4930SRik van Riel 	return 0;
3855beb4930SRik van Riel 
3865beb4930SRik van Riel  out_error_free_anon_vma:
38701d8b20dSPeter Zijlstra 	put_anon_vma(anon_vma);
3885beb4930SRik van Riel  out_error:
3894946d54cSRik van Riel 	unlink_anon_vmas(vma);
3905beb4930SRik van Riel 	return -ENOMEM;
3915beb4930SRik van Riel }
3925beb4930SRik van Riel 
3935beb4930SRik van Riel void unlink_anon_vmas(struct vm_area_struct *vma)
3945beb4930SRik van Riel {
3955beb4930SRik van Riel 	struct anon_vma_chain *avc, *next;
396eee2acbaSPeter Zijlstra 	struct anon_vma *root = NULL;
3975beb4930SRik van Riel 
3985c341ee1SRik van Riel 	/*
3995c341ee1SRik van Riel 	 * Unlink each anon_vma chained to the VMA.  This list is ordered
4005c341ee1SRik van Riel 	 * from newest to oldest, ensuring the root anon_vma gets freed last.
4015c341ee1SRik van Riel 	 */
4025beb4930SRik van Riel 	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
403eee2acbaSPeter Zijlstra 		struct anon_vma *anon_vma = avc->anon_vma;
404eee2acbaSPeter Zijlstra 
405eee2acbaSPeter Zijlstra 		root = lock_anon_vma_root(root, anon_vma);
406bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
407eee2acbaSPeter Zijlstra 
408eee2acbaSPeter Zijlstra 		/*
409eee2acbaSPeter Zijlstra 		 * Leave empty anon_vmas on the list - we'll need
410eee2acbaSPeter Zijlstra 		 * to free them outside the lock.
411eee2acbaSPeter Zijlstra 		 */
412f808c13fSDavidlohr Bueso 		if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
4137a3ef208SKonstantin Khlebnikov 			anon_vma->parent->degree--;
414eee2acbaSPeter Zijlstra 			continue;
4157a3ef208SKonstantin Khlebnikov 		}
416eee2acbaSPeter Zijlstra 
417eee2acbaSPeter Zijlstra 		list_del(&avc->same_vma);
418eee2acbaSPeter Zijlstra 		anon_vma_chain_free(avc);
419eee2acbaSPeter Zijlstra 	}
420ee8ab190SLi Xinhai 	if (vma->anon_vma) {
4217a3ef208SKonstantin Khlebnikov 		vma->anon_vma->degree--;
422ee8ab190SLi Xinhai 
423ee8ab190SLi Xinhai 		/*
424ee8ab190SLi Xinhai 		 * vma would still be needed after unlink, and anon_vma will be prepared
425ee8ab190SLi Xinhai 		 * when handle fault.
426ee8ab190SLi Xinhai 		 */
427ee8ab190SLi Xinhai 		vma->anon_vma = NULL;
428ee8ab190SLi Xinhai 	}
429eee2acbaSPeter Zijlstra 	unlock_anon_vma_root(root);
430eee2acbaSPeter Zijlstra 
431eee2acbaSPeter Zijlstra 	/*
432eee2acbaSPeter Zijlstra 	 * Iterate the list once more, it now only contains empty and unlinked
433eee2acbaSPeter Zijlstra 	 * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
4345a505085SIngo Molnar 	 * needing to write-acquire the anon_vma->root->rwsem.
435eee2acbaSPeter Zijlstra 	 */
436eee2acbaSPeter Zijlstra 	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
437eee2acbaSPeter Zijlstra 		struct anon_vma *anon_vma = avc->anon_vma;
438eee2acbaSPeter Zijlstra 
439e4c5800aSKonstantin Khlebnikov 		VM_WARN_ON(anon_vma->degree);
440eee2acbaSPeter Zijlstra 		put_anon_vma(anon_vma);
441eee2acbaSPeter Zijlstra 
4425beb4930SRik van Riel 		list_del(&avc->same_vma);
4435beb4930SRik van Riel 		anon_vma_chain_free(avc);
4445beb4930SRik van Riel 	}
4455beb4930SRik van Riel }
4465beb4930SRik van Riel 
44751cc5068SAlexey Dobriyan static void anon_vma_ctor(void *data)
4481da177e4SLinus Torvalds {
4491da177e4SLinus Torvalds 	struct anon_vma *anon_vma = data;
4501da177e4SLinus Torvalds 
4515a505085SIngo Molnar 	init_rwsem(&anon_vma->rwsem);
45283813267SPeter Zijlstra 	atomic_set(&anon_vma->refcount, 0);
453f808c13fSDavidlohr Bueso 	anon_vma->rb_root = RB_ROOT_CACHED;
4541da177e4SLinus Torvalds }
4551da177e4SLinus Torvalds 
4561da177e4SLinus Torvalds void __init anon_vma_init(void)
4571da177e4SLinus Torvalds {
4581da177e4SLinus Torvalds 	anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
4595f0d5a3aSPaul E. McKenney 			0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
4605d097056SVladimir Davydov 			anon_vma_ctor);
4615d097056SVladimir Davydov 	anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
4625d097056SVladimir Davydov 			SLAB_PANIC|SLAB_ACCOUNT);
4631da177e4SLinus Torvalds }
4641da177e4SLinus Torvalds 
4651da177e4SLinus Torvalds /*
4666111e4caSPeter Zijlstra  * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
4676111e4caSPeter Zijlstra  *
4686111e4caSPeter Zijlstra  * Since there is no serialization what so ever against page_remove_rmap()
469ad8a20cfSMiaohe Lin  * the best this function can do is return a refcount increased anon_vma
470ad8a20cfSMiaohe Lin  * that might have been relevant to this page.
4716111e4caSPeter Zijlstra  *
4726111e4caSPeter Zijlstra  * The page might have been remapped to a different anon_vma or the anon_vma
4736111e4caSPeter Zijlstra  * returned may already be freed (and even reused).
4746111e4caSPeter Zijlstra  *
475bc658c96SPeter Zijlstra  * In case it was remapped to a different anon_vma, the new anon_vma will be a
476bc658c96SPeter Zijlstra  * child of the old anon_vma, and the anon_vma lifetime rules will therefore
477bc658c96SPeter Zijlstra  * ensure that any anon_vma obtained from the page will still be valid for as
478bc658c96SPeter Zijlstra  * long as we observe page_mapped() [ hence all those page_mapped() tests ].
479bc658c96SPeter Zijlstra  *
4806111e4caSPeter Zijlstra  * All users of this function must be very careful when walking the anon_vma
4816111e4caSPeter Zijlstra  * chain and verify that the page in question is indeed mapped in it
4826111e4caSPeter Zijlstra  * [ something equivalent to page_mapped_in_vma() ].
4836111e4caSPeter Zijlstra  *
484091e4299SMiles Chen  * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
485091e4299SMiles Chen  * page_remove_rmap() that the anon_vma pointer from page->mapping is valid
486091e4299SMiles Chen  * if there is a mapcount, we can dereference the anon_vma after observing
487091e4299SMiles Chen  * those.
4881da177e4SLinus Torvalds  */
489746b18d4SPeter Zijlstra struct anon_vma *page_get_anon_vma(struct page *page)
4901da177e4SLinus Torvalds {
491746b18d4SPeter Zijlstra 	struct anon_vma *anon_vma = NULL;
4921da177e4SLinus Torvalds 	unsigned long anon_mapping;
4931da177e4SLinus Torvalds 
4941da177e4SLinus Torvalds 	rcu_read_lock();
4954db0c3c2SJason Low 	anon_mapping = (unsigned long)READ_ONCE(page->mapping);
4963ca7b3c5SHugh Dickins 	if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
4971da177e4SLinus Torvalds 		goto out;
4981da177e4SLinus Torvalds 	if (!page_mapped(page))
4991da177e4SLinus Torvalds 		goto out;
5001da177e4SLinus Torvalds 
5011da177e4SLinus Torvalds 	anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
502746b18d4SPeter Zijlstra 	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
503746b18d4SPeter Zijlstra 		anon_vma = NULL;
504746b18d4SPeter Zijlstra 		goto out;
505746b18d4SPeter Zijlstra 	}
506f1819427SHugh Dickins 
507f1819427SHugh Dickins 	/*
508f1819427SHugh Dickins 	 * If this page is still mapped, then its anon_vma cannot have been
509746b18d4SPeter Zijlstra 	 * freed.  But if it has been unmapped, we have no security against the
510746b18d4SPeter Zijlstra 	 * anon_vma structure being freed and reused (for another anon_vma:
5115f0d5a3aSPaul E. McKenney 	 * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
512746b18d4SPeter Zijlstra 	 * above cannot corrupt).
513f1819427SHugh Dickins 	 */
514746b18d4SPeter Zijlstra 	if (!page_mapped(page)) {
5157f39dda9SHugh Dickins 		rcu_read_unlock();
516746b18d4SPeter Zijlstra 		put_anon_vma(anon_vma);
5177f39dda9SHugh Dickins 		return NULL;
518746b18d4SPeter Zijlstra 	}
5191da177e4SLinus Torvalds out:
5201da177e4SLinus Torvalds 	rcu_read_unlock();
521746b18d4SPeter Zijlstra 
522746b18d4SPeter Zijlstra 	return anon_vma;
523746b18d4SPeter Zijlstra }
524746b18d4SPeter Zijlstra 
52588c22088SPeter Zijlstra /*
52688c22088SPeter Zijlstra  * Similar to page_get_anon_vma() except it locks the anon_vma.
52788c22088SPeter Zijlstra  *
52888c22088SPeter Zijlstra  * Its a little more complex as it tries to keep the fast path to a single
52988c22088SPeter Zijlstra  * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
5306d4675e6SMinchan Kim  * reference like with page_get_anon_vma() and then block on the mutex
5316d4675e6SMinchan Kim  * on !rwc->try_lock case.
53288c22088SPeter Zijlstra  */
5336d4675e6SMinchan Kim struct anon_vma *folio_lock_anon_vma_read(struct folio *folio,
5346d4675e6SMinchan Kim 					  struct rmap_walk_control *rwc)
535746b18d4SPeter Zijlstra {
53688c22088SPeter Zijlstra 	struct anon_vma *anon_vma = NULL;
537eee0f252SHugh Dickins 	struct anon_vma *root_anon_vma;
53888c22088SPeter Zijlstra 	unsigned long anon_mapping;
539746b18d4SPeter Zijlstra 
54088c22088SPeter Zijlstra 	rcu_read_lock();
5419595d769SMatthew Wilcox (Oracle) 	anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
54288c22088SPeter Zijlstra 	if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
54388c22088SPeter Zijlstra 		goto out;
5449595d769SMatthew Wilcox (Oracle) 	if (!folio_mapped(folio))
54588c22088SPeter Zijlstra 		goto out;
54688c22088SPeter Zijlstra 
54788c22088SPeter Zijlstra 	anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
5484db0c3c2SJason Low 	root_anon_vma = READ_ONCE(anon_vma->root);
5494fc3f1d6SIngo Molnar 	if (down_read_trylock(&root_anon_vma->rwsem)) {
55088c22088SPeter Zijlstra 		/*
5519595d769SMatthew Wilcox (Oracle) 		 * If the folio is still mapped, then this anon_vma is still
552eee0f252SHugh Dickins 		 * its anon_vma, and holding the mutex ensures that it will
553bc658c96SPeter Zijlstra 		 * not go away, see anon_vma_free().
55488c22088SPeter Zijlstra 		 */
5559595d769SMatthew Wilcox (Oracle) 		if (!folio_mapped(folio)) {
5564fc3f1d6SIngo Molnar 			up_read(&root_anon_vma->rwsem);
55788c22088SPeter Zijlstra 			anon_vma = NULL;
55888c22088SPeter Zijlstra 		}
55988c22088SPeter Zijlstra 		goto out;
56088c22088SPeter Zijlstra 	}
56188c22088SPeter Zijlstra 
5626d4675e6SMinchan Kim 	if (rwc && rwc->try_lock) {
5636d4675e6SMinchan Kim 		anon_vma = NULL;
5646d4675e6SMinchan Kim 		rwc->contended = true;
5656d4675e6SMinchan Kim 		goto out;
5666d4675e6SMinchan Kim 	}
5676d4675e6SMinchan Kim 
56888c22088SPeter Zijlstra 	/* trylock failed, we got to sleep */
56988c22088SPeter Zijlstra 	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
57088c22088SPeter Zijlstra 		anon_vma = NULL;
57188c22088SPeter Zijlstra 		goto out;
57288c22088SPeter Zijlstra 	}
57388c22088SPeter Zijlstra 
5749595d769SMatthew Wilcox (Oracle) 	if (!folio_mapped(folio)) {
5757f39dda9SHugh Dickins 		rcu_read_unlock();
57688c22088SPeter Zijlstra 		put_anon_vma(anon_vma);
5777f39dda9SHugh Dickins 		return NULL;
57888c22088SPeter Zijlstra 	}
57988c22088SPeter Zijlstra 
58088c22088SPeter Zijlstra 	/* we pinned the anon_vma, its safe to sleep */
58188c22088SPeter Zijlstra 	rcu_read_unlock();
5824fc3f1d6SIngo Molnar 	anon_vma_lock_read(anon_vma);
583746b18d4SPeter Zijlstra 
58488c22088SPeter Zijlstra 	if (atomic_dec_and_test(&anon_vma->refcount)) {
58588c22088SPeter Zijlstra 		/*
58688c22088SPeter Zijlstra 		 * Oops, we held the last refcount, release the lock
58788c22088SPeter Zijlstra 		 * and bail -- can't simply use put_anon_vma() because
5884fc3f1d6SIngo Molnar 		 * we'll deadlock on the anon_vma_lock_write() recursion.
58988c22088SPeter Zijlstra 		 */
5904fc3f1d6SIngo Molnar 		anon_vma_unlock_read(anon_vma);
59188c22088SPeter Zijlstra 		__put_anon_vma(anon_vma);
59288c22088SPeter Zijlstra 		anon_vma = NULL;
59388c22088SPeter Zijlstra 	}
59488c22088SPeter Zijlstra 
59588c22088SPeter Zijlstra 	return anon_vma;
59688c22088SPeter Zijlstra 
59788c22088SPeter Zijlstra out:
59888c22088SPeter Zijlstra 	rcu_read_unlock();
599746b18d4SPeter Zijlstra 	return anon_vma;
60034bbd704SOleg Nesterov }
60134bbd704SOleg Nesterov 
6024fc3f1d6SIngo Molnar void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
60334bbd704SOleg Nesterov {
6044fc3f1d6SIngo Molnar 	anon_vma_unlock_read(anon_vma);
6051da177e4SLinus Torvalds }
6061da177e4SLinus Torvalds 
60772b252aeSMel Gorman #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
60872b252aeSMel Gorman /*
60972b252aeSMel Gorman  * Flush TLB entries for recently unmapped pages from remote CPUs. It is
61072b252aeSMel Gorman  * important if a PTE was dirty when it was unmapped that it's flushed
61172b252aeSMel Gorman  * before any IO is initiated on the page to prevent lost writes. Similarly,
61272b252aeSMel Gorman  * it must be flushed before freeing to prevent data leakage.
61372b252aeSMel Gorman  */
61472b252aeSMel Gorman void try_to_unmap_flush(void)
61572b252aeSMel Gorman {
61672b252aeSMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
61772b252aeSMel Gorman 
61872b252aeSMel Gorman 	if (!tlb_ubc->flush_required)
61972b252aeSMel Gorman 		return;
62072b252aeSMel Gorman 
621e73ad5ffSAndy Lutomirski 	arch_tlbbatch_flush(&tlb_ubc->arch);
62272b252aeSMel Gorman 	tlb_ubc->flush_required = false;
623d950c947SMel Gorman 	tlb_ubc->writable = false;
62472b252aeSMel Gorman }
62572b252aeSMel Gorman 
626d950c947SMel Gorman /* Flush iff there are potentially writable TLB entries that can race with IO */
627d950c947SMel Gorman void try_to_unmap_flush_dirty(void)
628d950c947SMel Gorman {
629d950c947SMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
630d950c947SMel Gorman 
631d950c947SMel Gorman 	if (tlb_ubc->writable)
632d950c947SMel Gorman 		try_to_unmap_flush();
633d950c947SMel Gorman }
634d950c947SMel Gorman 
6355ee2fa2fSHuang Ying /*
6365ee2fa2fSHuang Ying  * Bits 0-14 of mm->tlb_flush_batched record pending generations.
6375ee2fa2fSHuang Ying  * Bits 16-30 of mm->tlb_flush_batched bit record flushed generations.
6385ee2fa2fSHuang Ying  */
6395ee2fa2fSHuang Ying #define TLB_FLUSH_BATCH_FLUSHED_SHIFT	16
6405ee2fa2fSHuang Ying #define TLB_FLUSH_BATCH_PENDING_MASK			\
6415ee2fa2fSHuang Ying 	((1 << (TLB_FLUSH_BATCH_FLUSHED_SHIFT - 1)) - 1)
6425ee2fa2fSHuang Ying #define TLB_FLUSH_BATCH_PENDING_LARGE			\
6435ee2fa2fSHuang Ying 	(TLB_FLUSH_BATCH_PENDING_MASK / 2)
6445ee2fa2fSHuang Ying 
645c7ab0d2fSKirill A. Shutemov static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
64672b252aeSMel Gorman {
64772b252aeSMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
6485ee2fa2fSHuang Ying 	int batch, nbatch;
64972b252aeSMel Gorman 
650e73ad5ffSAndy Lutomirski 	arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
65172b252aeSMel Gorman 	tlb_ubc->flush_required = true;
652d950c947SMel Gorman 
653d950c947SMel Gorman 	/*
6543ea27719SMel Gorman 	 * Ensure compiler does not re-order the setting of tlb_flush_batched
6553ea27719SMel Gorman 	 * before the PTE is cleared.
6563ea27719SMel Gorman 	 */
6573ea27719SMel Gorman 	barrier();
6585ee2fa2fSHuang Ying 	batch = atomic_read(&mm->tlb_flush_batched);
6595ee2fa2fSHuang Ying retry:
6605ee2fa2fSHuang Ying 	if ((batch & TLB_FLUSH_BATCH_PENDING_MASK) > TLB_FLUSH_BATCH_PENDING_LARGE) {
6615ee2fa2fSHuang Ying 		/*
6625ee2fa2fSHuang Ying 		 * Prevent `pending' from catching up with `flushed' because of
6635ee2fa2fSHuang Ying 		 * overflow.  Reset `pending' and `flushed' to be 1 and 0 if
6645ee2fa2fSHuang Ying 		 * `pending' becomes large.
6655ee2fa2fSHuang Ying 		 */
6665ee2fa2fSHuang Ying 		nbatch = atomic_cmpxchg(&mm->tlb_flush_batched, batch, 1);
6675ee2fa2fSHuang Ying 		if (nbatch != batch) {
6685ee2fa2fSHuang Ying 			batch = nbatch;
6695ee2fa2fSHuang Ying 			goto retry;
6705ee2fa2fSHuang Ying 		}
6715ee2fa2fSHuang Ying 	} else {
6725ee2fa2fSHuang Ying 		atomic_inc(&mm->tlb_flush_batched);
6735ee2fa2fSHuang Ying 	}
6743ea27719SMel Gorman 
6753ea27719SMel Gorman 	/*
676d950c947SMel Gorman 	 * If the PTE was dirty then it's best to assume it's writable. The
677d950c947SMel Gorman 	 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
678d950c947SMel Gorman 	 * before the page is queued for IO.
679d950c947SMel Gorman 	 */
680d950c947SMel Gorman 	if (writable)
681d950c947SMel Gorman 		tlb_ubc->writable = true;
68272b252aeSMel Gorman }
68372b252aeSMel Gorman 
68472b252aeSMel Gorman /*
68572b252aeSMel Gorman  * Returns true if the TLB flush should be deferred to the end of a batch of
68672b252aeSMel Gorman  * unmap operations to reduce IPIs.
68772b252aeSMel Gorman  */
68872b252aeSMel Gorman static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
68972b252aeSMel Gorman {
69072b252aeSMel Gorman 	bool should_defer = false;
69172b252aeSMel Gorman 
69272b252aeSMel Gorman 	if (!(flags & TTU_BATCH_FLUSH))
69372b252aeSMel Gorman 		return false;
69472b252aeSMel Gorman 
69572b252aeSMel Gorman 	/* If remote CPUs need to be flushed then defer batch the flush */
69672b252aeSMel Gorman 	if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
69772b252aeSMel Gorman 		should_defer = true;
69872b252aeSMel Gorman 	put_cpu();
69972b252aeSMel Gorman 
70072b252aeSMel Gorman 	return should_defer;
70172b252aeSMel Gorman }
7023ea27719SMel Gorman 
7033ea27719SMel Gorman /*
7043ea27719SMel Gorman  * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
7053ea27719SMel Gorman  * releasing the PTL if TLB flushes are batched. It's possible for a parallel
7063ea27719SMel Gorman  * operation such as mprotect or munmap to race between reclaim unmapping
7073ea27719SMel Gorman  * the page and flushing the page. If this race occurs, it potentially allows
7083ea27719SMel Gorman  * access to data via a stale TLB entry. Tracking all mm's that have TLB
7093ea27719SMel Gorman  * batching in flight would be expensive during reclaim so instead track
7103ea27719SMel Gorman  * whether TLB batching occurred in the past and if so then do a flush here
7113ea27719SMel Gorman  * if required. This will cost one additional flush per reclaim cycle paid
7123ea27719SMel Gorman  * by the first operation at risk such as mprotect and mumap.
7133ea27719SMel Gorman  *
7143ea27719SMel Gorman  * This must be called under the PTL so that an access to tlb_flush_batched
7153ea27719SMel Gorman  * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
7163ea27719SMel Gorman  * via the PTL.
7173ea27719SMel Gorman  */
7183ea27719SMel Gorman void flush_tlb_batched_pending(struct mm_struct *mm)
7193ea27719SMel Gorman {
7205ee2fa2fSHuang Ying 	int batch = atomic_read(&mm->tlb_flush_batched);
7215ee2fa2fSHuang Ying 	int pending = batch & TLB_FLUSH_BATCH_PENDING_MASK;
7225ee2fa2fSHuang Ying 	int flushed = batch >> TLB_FLUSH_BATCH_FLUSHED_SHIFT;
7233ea27719SMel Gorman 
7245ee2fa2fSHuang Ying 	if (pending != flushed) {
7255ee2fa2fSHuang Ying 		flush_tlb_mm(mm);
7263ea27719SMel Gorman 		/*
7275ee2fa2fSHuang Ying 		 * If the new TLB flushing is pending during flushing, leave
7285ee2fa2fSHuang Ying 		 * mm->tlb_flush_batched as is, to avoid losing flushing.
7293ea27719SMel Gorman 		 */
7305ee2fa2fSHuang Ying 		atomic_cmpxchg(&mm->tlb_flush_batched, batch,
7315ee2fa2fSHuang Ying 			       pending | (pending << TLB_FLUSH_BATCH_FLUSHED_SHIFT));
7323ea27719SMel Gorman 	}
7333ea27719SMel Gorman }
73472b252aeSMel Gorman #else
735c7ab0d2fSKirill A. Shutemov static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
73672b252aeSMel Gorman {
73772b252aeSMel Gorman }
73872b252aeSMel Gorman 
73972b252aeSMel Gorman static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
74072b252aeSMel Gorman {
74172b252aeSMel Gorman 	return false;
74272b252aeSMel Gorman }
74372b252aeSMel Gorman #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
74472b252aeSMel Gorman 
7451da177e4SLinus Torvalds /*
746bf89c8c8SHuang Shijie  * At what user virtual address is page expected in vma?
747ab941e0fSNaoya Horiguchi  * Caller should check the page is actually part of the vma.
7481da177e4SLinus Torvalds  */
7491da177e4SLinus Torvalds unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
7501da177e4SLinus Torvalds {
751e05b3453SMatthew Wilcox (Oracle) 	struct folio *folio = page_folio(page);
752e05b3453SMatthew Wilcox (Oracle) 	if (folio_test_anon(folio)) {
753e05b3453SMatthew Wilcox (Oracle) 		struct anon_vma *page__anon_vma = folio_anon_vma(folio);
7544829b906SHugh Dickins 		/*
7554829b906SHugh Dickins 		 * Note: swapoff's unuse_vma() is more efficient with this
7564829b906SHugh Dickins 		 * check, and needs it to match anon_vma when KSM is active.
7574829b906SHugh Dickins 		 */
7584829b906SHugh Dickins 		if (!vma->anon_vma || !page__anon_vma ||
7594829b906SHugh Dickins 		    vma->anon_vma->root != page__anon_vma->root)
76021d0d443SAndrea Arcangeli 			return -EFAULT;
76131657170SJue Wang 	} else if (!vma->vm_file) {
7621da177e4SLinus Torvalds 		return -EFAULT;
763e05b3453SMatthew Wilcox (Oracle) 	} else if (vma->vm_file->f_mapping != folio->mapping) {
7641da177e4SLinus Torvalds 		return -EFAULT;
76531657170SJue Wang 	}
766494334e4SHugh Dickins 
767494334e4SHugh Dickins 	return vma_address(page, vma);
7681da177e4SLinus Torvalds }
7691da177e4SLinus Torvalds 
77050722804SZach O'Keefe /*
77150722804SZach O'Keefe  * Returns the actual pmd_t* where we expect 'address' to be mapped from, or
77250722804SZach O'Keefe  * NULL if it doesn't exist.  No guarantees / checks on what the pmd_t*
77350722804SZach O'Keefe  * represents.
77450722804SZach O'Keefe  */
7756219049aSBob Liu pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
7766219049aSBob Liu {
7776219049aSBob Liu 	pgd_t *pgd;
778c2febafcSKirill A. Shutemov 	p4d_t *p4d;
7796219049aSBob Liu 	pud_t *pud;
7806219049aSBob Liu 	pmd_t *pmd = NULL;
7816219049aSBob Liu 
7826219049aSBob Liu 	pgd = pgd_offset(mm, address);
7836219049aSBob Liu 	if (!pgd_present(*pgd))
7846219049aSBob Liu 		goto out;
7856219049aSBob Liu 
786c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, address);
787c2febafcSKirill A. Shutemov 	if (!p4d_present(*p4d))
788c2febafcSKirill A. Shutemov 		goto out;
789c2febafcSKirill A. Shutemov 
790c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, address);
7916219049aSBob Liu 	if (!pud_present(*pud))
7926219049aSBob Liu 		goto out;
7936219049aSBob Liu 
7946219049aSBob Liu 	pmd = pmd_offset(pud, address);
7956219049aSBob Liu out:
7966219049aSBob Liu 	return pmd;
7976219049aSBob Liu }
7986219049aSBob Liu 
799b3ac0413SMatthew Wilcox (Oracle) struct folio_referenced_arg {
8009f32624bSJoonsoo Kim 	int mapcount;
8019f32624bSJoonsoo Kim 	int referenced;
8029f32624bSJoonsoo Kim 	unsigned long vm_flags;
8039f32624bSJoonsoo Kim 	struct mem_cgroup *memcg;
8049f32624bSJoonsoo Kim };
80581b4082dSNikita Danilov /*
806b3ac0413SMatthew Wilcox (Oracle)  * arg: folio_referenced_arg will be passed
8071da177e4SLinus Torvalds  */
8082f031c6fSMatthew Wilcox (Oracle) static bool folio_referenced_one(struct folio *folio,
8092f031c6fSMatthew Wilcox (Oracle) 		struct vm_area_struct *vma, unsigned long address, void *arg)
8101da177e4SLinus Torvalds {
811b3ac0413SMatthew Wilcox (Oracle) 	struct folio_referenced_arg *pra = arg;
812b3ac0413SMatthew Wilcox (Oracle) 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
8138749cfeaSVladimir Davydov 	int referenced = 0;
8142da28bfdSAndrea Arcangeli 
8158eaededeSKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
8168eaededeSKirill A. Shutemov 		address = pvmw.address;
8172da28bfdSAndrea Arcangeli 
81847d4f3eeSHugh Dickins 		if ((vma->vm_flags & VM_LOCKED) &&
819b3ac0413SMatthew Wilcox (Oracle) 		    (!folio_test_large(folio) || !pvmw.pte)) {
82047d4f3eeSHugh Dickins 			/* Restore the mlock which got missed */
821b3ac0413SMatthew Wilcox (Oracle) 			mlock_vma_folio(folio, vma, !pvmw.pte);
8228eaededeSKirill A. Shutemov 			page_vma_mapped_walk_done(&pvmw);
8239f32624bSJoonsoo Kim 			pra->vm_flags |= VM_LOCKED;
824e4b82222SMinchan Kim 			return false; /* To break the loop */
8252da28bfdSAndrea Arcangeli 		}
8262da28bfdSAndrea Arcangeli 
8278eaededeSKirill A. Shutemov 		if (pvmw.pte) {
8288eaededeSKirill A. Shutemov 			if (ptep_clear_flush_young_notify(vma, address,
8298eaededeSKirill A. Shutemov 						pvmw.pte)) {
8304917e5d0SJohannes Weiner 				/*
8318eaededeSKirill A. Shutemov 				 * Don't treat a reference through
8328eaededeSKirill A. Shutemov 				 * a sequentially read mapping as such.
833b3ac0413SMatthew Wilcox (Oracle) 				 * If the folio has been used in another mapping,
8348eaededeSKirill A. Shutemov 				 * we will catch it; if this other mapping is
8358eaededeSKirill A. Shutemov 				 * already gone, the unmap path will have set
836b3ac0413SMatthew Wilcox (Oracle) 				 * the referenced flag or activated the folio.
8374917e5d0SJohannes Weiner 				 */
83864363aadSJoe Perches 				if (likely(!(vma->vm_flags & VM_SEQ_READ)))
8391da177e4SLinus Torvalds 					referenced++;
8404917e5d0SJohannes Weiner 			}
8418749cfeaSVladimir Davydov 		} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
8428eaededeSKirill A. Shutemov 			if (pmdp_clear_flush_young_notify(vma, address,
8438eaededeSKirill A. Shutemov 						pvmw.pmd))
8448749cfeaSVladimir Davydov 				referenced++;
8458749cfeaSVladimir Davydov 		} else {
846b3ac0413SMatthew Wilcox (Oracle) 			/* unexpected pmd-mapped folio? */
8478749cfeaSVladimir Davydov 			WARN_ON_ONCE(1);
8488749cfeaSVladimir Davydov 		}
8498eaededeSKirill A. Shutemov 
8508eaededeSKirill A. Shutemov 		pra->mapcount--;
8518eaededeSKirill A. Shutemov 	}
85271e3aac0SAndrea Arcangeli 
85333c3fc71SVladimir Davydov 	if (referenced)
854b3ac0413SMatthew Wilcox (Oracle) 		folio_clear_idle(folio);
855b3ac0413SMatthew Wilcox (Oracle) 	if (folio_test_clear_young(folio))
85633c3fc71SVladimir Davydov 		referenced++;
85733c3fc71SVladimir Davydov 
8589f32624bSJoonsoo Kim 	if (referenced) {
8599f32624bSJoonsoo Kim 		pra->referenced++;
86047d4f3eeSHugh Dickins 		pra->vm_flags |= vma->vm_flags & ~VM_LOCKED;
8611da177e4SLinus Torvalds 	}
8621da177e4SLinus Torvalds 
8639f32624bSJoonsoo Kim 	if (!pra->mapcount)
864e4b82222SMinchan Kim 		return false; /* To break the loop */
8659f32624bSJoonsoo Kim 
866e4b82222SMinchan Kim 	return true;
8679f32624bSJoonsoo Kim }
8689f32624bSJoonsoo Kim 
869b3ac0413SMatthew Wilcox (Oracle) static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
8701da177e4SLinus Torvalds {
871b3ac0413SMatthew Wilcox (Oracle) 	struct folio_referenced_arg *pra = arg;
8729f32624bSJoonsoo Kim 	struct mem_cgroup *memcg = pra->memcg;
8731da177e4SLinus Torvalds 
8749f32624bSJoonsoo Kim 	if (!mm_match_cgroup(vma->vm_mm, memcg))
8759f32624bSJoonsoo Kim 		return true;
8761da177e4SLinus Torvalds 
8779f32624bSJoonsoo Kim 	return false;
8781da177e4SLinus Torvalds }
8791da177e4SLinus Torvalds 
8801da177e4SLinus Torvalds /**
881b3ac0413SMatthew Wilcox (Oracle)  * folio_referenced() - Test if the folio was referenced.
882b3ac0413SMatthew Wilcox (Oracle)  * @folio: The folio to test.
883b3ac0413SMatthew Wilcox (Oracle)  * @is_locked: Caller holds lock on the folio.
88472835c86SJohannes Weiner  * @memcg: target memory cgroup
885b3ac0413SMatthew Wilcox (Oracle)  * @vm_flags: A combination of all the vma->vm_flags which referenced the folio.
8861da177e4SLinus Torvalds  *
887b3ac0413SMatthew Wilcox (Oracle)  * Quick test_and_clear_referenced for all mappings of a folio,
888b3ac0413SMatthew Wilcox (Oracle)  *
8896d4675e6SMinchan Kim  * Return: The number of mappings which referenced the folio. Return -1 if
8906d4675e6SMinchan Kim  * the function bailed out due to rmap lock contention.
8911da177e4SLinus Torvalds  */
892b3ac0413SMatthew Wilcox (Oracle) int folio_referenced(struct folio *folio, int is_locked,
893b3ac0413SMatthew Wilcox (Oracle) 		     struct mem_cgroup *memcg, unsigned long *vm_flags)
8941da177e4SLinus Torvalds {
8955ad64688SHugh Dickins 	int we_locked = 0;
896b3ac0413SMatthew Wilcox (Oracle) 	struct folio_referenced_arg pra = {
897b3ac0413SMatthew Wilcox (Oracle) 		.mapcount = folio_mapcount(folio),
8989f32624bSJoonsoo Kim 		.memcg = memcg,
8999f32624bSJoonsoo Kim 	};
9009f32624bSJoonsoo Kim 	struct rmap_walk_control rwc = {
901b3ac0413SMatthew Wilcox (Oracle) 		.rmap_one = folio_referenced_one,
9029f32624bSJoonsoo Kim 		.arg = (void *)&pra,
9032f031c6fSMatthew Wilcox (Oracle) 		.anon_lock = folio_lock_anon_vma_read,
9046d4675e6SMinchan Kim 		.try_lock = true,
9059f32624bSJoonsoo Kim 	};
9061da177e4SLinus Torvalds 
9076fe6b7e3SWu Fengguang 	*vm_flags = 0;
908059d8442SHuang Shijie 	if (!pra.mapcount)
9099f32624bSJoonsoo Kim 		return 0;
9109f32624bSJoonsoo Kim 
911b3ac0413SMatthew Wilcox (Oracle) 	if (!folio_raw_mapping(folio))
9129f32624bSJoonsoo Kim 		return 0;
9139f32624bSJoonsoo Kim 
914b3ac0413SMatthew Wilcox (Oracle) 	if (!is_locked && (!folio_test_anon(folio) || folio_test_ksm(folio))) {
915b3ac0413SMatthew Wilcox (Oracle) 		we_locked = folio_trylock(folio);
9169f32624bSJoonsoo Kim 		if (!we_locked)
9179f32624bSJoonsoo Kim 			return 1;
9185ad64688SHugh Dickins 	}
9199f32624bSJoonsoo Kim 
9209f32624bSJoonsoo Kim 	/*
9219f32624bSJoonsoo Kim 	 * If we are reclaiming on behalf of a cgroup, skip
9229f32624bSJoonsoo Kim 	 * counting on behalf of references from different
9239f32624bSJoonsoo Kim 	 * cgroups
9249f32624bSJoonsoo Kim 	 */
9259f32624bSJoonsoo Kim 	if (memcg) {
926b3ac0413SMatthew Wilcox (Oracle) 		rwc.invalid_vma = invalid_folio_referenced_vma;
9275ad64688SHugh Dickins 	}
9289f32624bSJoonsoo Kim 
9292f031c6fSMatthew Wilcox (Oracle) 	rmap_walk(folio, &rwc);
9309f32624bSJoonsoo Kim 	*vm_flags = pra.vm_flags;
9319f32624bSJoonsoo Kim 
9325ad64688SHugh Dickins 	if (we_locked)
933b3ac0413SMatthew Wilcox (Oracle) 		folio_unlock(folio);
9349f32624bSJoonsoo Kim 
9356d4675e6SMinchan Kim 	return rwc.contended ? -1 : pra.referenced;
9361da177e4SLinus Torvalds }
9371da177e4SLinus Torvalds 
9386a8e0596SMuchun Song static int page_vma_mkclean_one(struct page_vma_mapped_walk *pvmw)
939d08b3851SPeter Zijlstra {
9406a8e0596SMuchun Song 	int cleaned = 0;
9416a8e0596SMuchun Song 	struct vm_area_struct *vma = pvmw->vma;
942ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
9436a8e0596SMuchun Song 	unsigned long address = pvmw->address;
944d08b3851SPeter Zijlstra 
945369ea824SJérôme Glisse 	/*
946369ea824SJérôme Glisse 	 * We have to assume the worse case ie pmd for invalidation. Note that
947e83c09a2SMatthew Wilcox (Oracle) 	 * the folio can not be freed from this function.
948369ea824SJérôme Glisse 	 */
9497269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
9507269f999SJérôme Glisse 				0, vma, vma->vm_mm, address,
9516a8e0596SMuchun Song 				vma_address_end(pvmw));
952ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
953369ea824SJérôme Glisse 
9546a8e0596SMuchun Song 	while (page_vma_mapped_walk(pvmw)) {
955f27176cfSKirill A. Shutemov 		int ret = 0;
956369ea824SJérôme Glisse 
9576a8e0596SMuchun Song 		address = pvmw->address;
9586a8e0596SMuchun Song 		if (pvmw->pte) {
959c2fda5feSPeter Zijlstra 			pte_t entry;
9606a8e0596SMuchun Song 			pte_t *pte = pvmw->pte;
961f27176cfSKirill A. Shutemov 
962f27176cfSKirill A. Shutemov 			if (!pte_dirty(*pte) && !pte_write(*pte))
963f27176cfSKirill A. Shutemov 				continue;
964d08b3851SPeter Zijlstra 
965785373b4SLinus Torvalds 			flush_cache_page(vma, address, pte_pfn(*pte));
966785373b4SLinus Torvalds 			entry = ptep_clear_flush(vma, address, pte);
967d08b3851SPeter Zijlstra 			entry = pte_wrprotect(entry);
968c2fda5feSPeter Zijlstra 			entry = pte_mkclean(entry);
969785373b4SLinus Torvalds 			set_pte_at(vma->vm_mm, address, pte, entry);
970d08b3851SPeter Zijlstra 			ret = 1;
971f27176cfSKirill A. Shutemov 		} else {
972396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
9736a8e0596SMuchun Song 			pmd_t *pmd = pvmw->pmd;
974f27176cfSKirill A. Shutemov 			pmd_t entry;
975d08b3851SPeter Zijlstra 
976f27176cfSKirill A. Shutemov 			if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
977f27176cfSKirill A. Shutemov 				continue;
978f27176cfSKirill A. Shutemov 
9797f9c9b60SMuchun Song 			flush_cache_range(vma, address,
9807f9c9b60SMuchun Song 					  address + HPAGE_PMD_SIZE);
981024eee0eSAneesh Kumar K.V 			entry = pmdp_invalidate(vma, address, pmd);
982f27176cfSKirill A. Shutemov 			entry = pmd_wrprotect(entry);
983f27176cfSKirill A. Shutemov 			entry = pmd_mkclean(entry);
984785373b4SLinus Torvalds 			set_pmd_at(vma->vm_mm, address, pmd, entry);
985f27176cfSKirill A. Shutemov 			ret = 1;
986f27176cfSKirill A. Shutemov #else
987e83c09a2SMatthew Wilcox (Oracle) 			/* unexpected pmd-mapped folio? */
988f27176cfSKirill A. Shutemov 			WARN_ON_ONCE(1);
989f27176cfSKirill A. Shutemov #endif
990f27176cfSKirill A. Shutemov 		}
9912ec74c3eSSagi Grimberg 
9920f10851eSJérôme Glisse 		/*
9930f10851eSJérôme Glisse 		 * No need to call mmu_notifier_invalidate_range() as we are
9940f10851eSJérôme Glisse 		 * downgrading page table protection not changing it to point
9950f10851eSJérôme Glisse 		 * to a new page.
9960f10851eSJérôme Glisse 		 *
997ee65728eSMike Rapoport 		 * See Documentation/mm/mmu_notifier.rst
9980f10851eSJérôme Glisse 		 */
9990f10851eSJérôme Glisse 		if (ret)
10006a8e0596SMuchun Song 			cleaned++;
10019853a407SJoonsoo Kim 	}
1002f27176cfSKirill A. Shutemov 
1003ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
1004369ea824SJérôme Glisse 
10056a8e0596SMuchun Song 	return cleaned;
10066a8e0596SMuchun Song }
10076a8e0596SMuchun Song 
10086a8e0596SMuchun Song static bool page_mkclean_one(struct folio *folio, struct vm_area_struct *vma,
10096a8e0596SMuchun Song 			     unsigned long address, void *arg)
10106a8e0596SMuchun Song {
10116a8e0596SMuchun Song 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, PVMW_SYNC);
10126a8e0596SMuchun Song 	int *cleaned = arg;
10136a8e0596SMuchun Song 
10146a8e0596SMuchun Song 	*cleaned += page_vma_mkclean_one(&pvmw);
10156a8e0596SMuchun Song 
1016e4b82222SMinchan Kim 	return true;
1017d08b3851SPeter Zijlstra }
1018d08b3851SPeter Zijlstra 
10199853a407SJoonsoo Kim static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
1020d08b3851SPeter Zijlstra {
10219853a407SJoonsoo Kim 	if (vma->vm_flags & VM_SHARED)
1022871beb8cSFengguang Wu 		return false;
1023d08b3851SPeter Zijlstra 
1024871beb8cSFengguang Wu 	return true;
1025d08b3851SPeter Zijlstra }
1026d08b3851SPeter Zijlstra 
1027d9c08e22SMatthew Wilcox (Oracle) int folio_mkclean(struct folio *folio)
1028d08b3851SPeter Zijlstra {
10299853a407SJoonsoo Kim 	int cleaned = 0;
10309853a407SJoonsoo Kim 	struct address_space *mapping;
10319853a407SJoonsoo Kim 	struct rmap_walk_control rwc = {
10329853a407SJoonsoo Kim 		.arg = (void *)&cleaned,
10339853a407SJoonsoo Kim 		.rmap_one = page_mkclean_one,
10349853a407SJoonsoo Kim 		.invalid_vma = invalid_mkclean_vma,
10359853a407SJoonsoo Kim 	};
1036d08b3851SPeter Zijlstra 
1037d9c08e22SMatthew Wilcox (Oracle) 	BUG_ON(!folio_test_locked(folio));
1038d08b3851SPeter Zijlstra 
1039d9c08e22SMatthew Wilcox (Oracle) 	if (!folio_mapped(folio))
10409853a407SJoonsoo Kim 		return 0;
1041d08b3851SPeter Zijlstra 
1042d9c08e22SMatthew Wilcox (Oracle) 	mapping = folio_mapping(folio);
10439853a407SJoonsoo Kim 	if (!mapping)
10449853a407SJoonsoo Kim 		return 0;
10459853a407SJoonsoo Kim 
10462f031c6fSMatthew Wilcox (Oracle) 	rmap_walk(folio, &rwc);
10479853a407SJoonsoo Kim 
10489853a407SJoonsoo Kim 	return cleaned;
1049d08b3851SPeter Zijlstra }
1050d9c08e22SMatthew Wilcox (Oracle) EXPORT_SYMBOL_GPL(folio_mkclean);
1051d08b3851SPeter Zijlstra 
10521da177e4SLinus Torvalds /**
10536a8e0596SMuchun Song  * pfn_mkclean_range - Cleans the PTEs (including PMDs) mapped with range of
10546a8e0596SMuchun Song  *                     [@pfn, @pfn + @nr_pages) at the specific offset (@pgoff)
10556a8e0596SMuchun Song  *                     within the @vma of shared mappings. And since clean PTEs
10566a8e0596SMuchun Song  *                     should also be readonly, write protects them too.
10576a8e0596SMuchun Song  * @pfn: start pfn.
10586a8e0596SMuchun Song  * @nr_pages: number of physically contiguous pages srarting with @pfn.
10596a8e0596SMuchun Song  * @pgoff: page offset that the @pfn mapped with.
10606a8e0596SMuchun Song  * @vma: vma that @pfn mapped within.
10616a8e0596SMuchun Song  *
10626a8e0596SMuchun Song  * Returns the number of cleaned PTEs (including PMDs).
10636a8e0596SMuchun Song  */
10646a8e0596SMuchun Song int pfn_mkclean_range(unsigned long pfn, unsigned long nr_pages, pgoff_t pgoff,
10656a8e0596SMuchun Song 		      struct vm_area_struct *vma)
10666a8e0596SMuchun Song {
10676a8e0596SMuchun Song 	struct page_vma_mapped_walk pvmw = {
10686a8e0596SMuchun Song 		.pfn		= pfn,
10696a8e0596SMuchun Song 		.nr_pages	= nr_pages,
10706a8e0596SMuchun Song 		.pgoff		= pgoff,
10716a8e0596SMuchun Song 		.vma		= vma,
10726a8e0596SMuchun Song 		.flags		= PVMW_SYNC,
10736a8e0596SMuchun Song 	};
10746a8e0596SMuchun Song 
10756a8e0596SMuchun Song 	if (invalid_mkclean_vma(vma, NULL))
10766a8e0596SMuchun Song 		return 0;
10776a8e0596SMuchun Song 
10786a8e0596SMuchun Song 	pvmw.address = vma_pgoff_address(pgoff, nr_pages, vma);
10796a8e0596SMuchun Song 	VM_BUG_ON_VMA(pvmw.address == -EFAULT, vma);
10806a8e0596SMuchun Song 
10816a8e0596SMuchun Song 	return page_vma_mkclean_one(&pvmw);
10826a8e0596SMuchun Song }
10836a8e0596SMuchun Song 
10846a8e0596SMuchun Song /**
1085c44b6743SRik van Riel  * page_move_anon_rmap - move a page to our anon_vma
1086c44b6743SRik van Riel  * @page:	the page to move to our anon_vma
1087c44b6743SRik van Riel  * @vma:	the vma the page belongs to
1088c44b6743SRik van Riel  *
1089c44b6743SRik van Riel  * When a page belongs exclusively to one process after a COW event,
1090c44b6743SRik van Riel  * that page can be moved into the anon_vma that belongs to just that
1091c44b6743SRik van Riel  * process, so the rmap code will not search the parent or sibling
1092c44b6743SRik van Riel  * processes.
1093c44b6743SRik van Riel  */
10945a49973dSHugh Dickins void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
1095c44b6743SRik van Riel {
1096c44b6743SRik van Riel 	struct anon_vma *anon_vma = vma->anon_vma;
10976c287605SDavid Hildenbrand 	struct page *subpage = page;
1098c44b6743SRik van Riel 
10995a49973dSHugh Dickins 	page = compound_head(page);
11005a49973dSHugh Dickins 
1101309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
110281d1b09cSSasha Levin 	VM_BUG_ON_VMA(!anon_vma, vma);
1103c44b6743SRik van Riel 
1104c44b6743SRik van Riel 	anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
1105414e2fb8SVladimir Davydov 	/*
1106414e2fb8SVladimir Davydov 	 * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
1107b3ac0413SMatthew Wilcox (Oracle) 	 * simultaneously, so a concurrent reader (eg folio_referenced()'s
1108b3ac0413SMatthew Wilcox (Oracle) 	 * folio_test_anon()) will not see one without the other.
1109414e2fb8SVladimir Davydov 	 */
1110414e2fb8SVladimir Davydov 	WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
11116c287605SDavid Hildenbrand 	SetPageAnonExclusive(subpage);
1112c44b6743SRik van Riel }
1113c44b6743SRik van Riel 
1114c44b6743SRik van Riel /**
111543d8eac4SRandy Dunlap  * __page_set_anon_rmap - set up new anonymous rmap
1116451b9514SKirill Tkhai  * @page:	Page or Hugepage to add to rmap
11174e1c1975SAndi Kleen  * @vma:	VM area to add page to.
11184e1c1975SAndi Kleen  * @address:	User virtual address of the mapping
1119e8a03febSRik van Riel  * @exclusive:	the page is exclusively owned by the current process
11201da177e4SLinus Torvalds  */
11219617d95eSNick Piggin static void __page_set_anon_rmap(struct page *page,
1122e8a03febSRik van Riel 	struct vm_area_struct *vma, unsigned long address, int exclusive)
11231da177e4SLinus Torvalds {
1124e8a03febSRik van Riel 	struct anon_vma *anon_vma = vma->anon_vma;
11252822c1aaSNick Piggin 
1126e8a03febSRik van Riel 	BUG_ON(!anon_vma);
1127ea90002bSLinus Torvalds 
11284e1c1975SAndi Kleen 	if (PageAnon(page))
11296c287605SDavid Hildenbrand 		goto out;
11304e1c1975SAndi Kleen 
1131ea90002bSLinus Torvalds 	/*
1132e8a03febSRik van Riel 	 * If the page isn't exclusively mapped into this vma,
1133e8a03febSRik van Riel 	 * we must use the _oldest_ possible anon_vma for the
1134e8a03febSRik van Riel 	 * page mapping!
1135ea90002bSLinus Torvalds 	 */
11364e1c1975SAndi Kleen 	if (!exclusive)
1137288468c3SAndrea Arcangeli 		anon_vma = anon_vma->root;
1138ea90002bSLinus Torvalds 
113916f5e707SAlex Shi 	/*
114016f5e707SAlex Shi 	 * page_idle does a lockless/optimistic rmap scan on page->mapping.
114116f5e707SAlex Shi 	 * Make sure the compiler doesn't split the stores of anon_vma and
114216f5e707SAlex Shi 	 * the PAGE_MAPPING_ANON type identifier, otherwise the rmap code
114316f5e707SAlex Shi 	 * could mistake the mapping for a struct address_space and crash.
114416f5e707SAlex Shi 	 */
11451da177e4SLinus Torvalds 	anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
114616f5e707SAlex Shi 	WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
11474d7670e0SNick Piggin 	page->index = linear_page_index(vma, address);
11486c287605SDavid Hildenbrand out:
11496c287605SDavid Hildenbrand 	if (exclusive)
11506c287605SDavid Hildenbrand 		SetPageAnonExclusive(page);
11511da177e4SLinus Torvalds }
11529617d95eSNick Piggin 
11539617d95eSNick Piggin /**
115443d8eac4SRandy Dunlap  * __page_check_anon_rmap - sanity check anonymous rmap addition
1155c97a9e10SNick Piggin  * @page:	the page to add the mapping to
1156c97a9e10SNick Piggin  * @vma:	the vm area in which the mapping is added
1157c97a9e10SNick Piggin  * @address:	the user virtual address mapped
1158c97a9e10SNick Piggin  */
1159c97a9e10SNick Piggin static void __page_check_anon_rmap(struct page *page,
1160c97a9e10SNick Piggin 	struct vm_area_struct *vma, unsigned long address)
1161c97a9e10SNick Piggin {
1162e05b3453SMatthew Wilcox (Oracle) 	struct folio *folio = page_folio(page);
1163c97a9e10SNick Piggin 	/*
1164c97a9e10SNick Piggin 	 * The page's anon-rmap details (mapping and index) are guaranteed to
1165c97a9e10SNick Piggin 	 * be set up correctly at this point.
1166c97a9e10SNick Piggin 	 *
1167c97a9e10SNick Piggin 	 * We have exclusion against page_add_anon_rmap because the caller
116890aaca85SMiaohe Lin 	 * always holds the page locked.
1169c97a9e10SNick Piggin 	 *
1170c97a9e10SNick Piggin 	 * We have exclusion against page_add_new_anon_rmap because those pages
1171c97a9e10SNick Piggin 	 * are initially only visible via the pagetables, and the pte is locked
1172c97a9e10SNick Piggin 	 * over the call to page_add_new_anon_rmap.
1173c97a9e10SNick Piggin 	 */
1174e05b3453SMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(folio_anon_vma(folio)->root != vma->anon_vma->root,
1175e05b3453SMatthew Wilcox (Oracle) 			folio);
117630c46382SYang Shi 	VM_BUG_ON_PAGE(page_to_pgoff(page) != linear_page_index(vma, address),
117730c46382SYang Shi 		       page);
1178c97a9e10SNick Piggin }
1179c97a9e10SNick Piggin 
1180c97a9e10SNick Piggin /**
11819617d95eSNick Piggin  * page_add_anon_rmap - add pte mapping to an anonymous page
11829617d95eSNick Piggin  * @page:	the page to add the mapping to
11839617d95eSNick Piggin  * @vma:	the vm area in which the mapping is added
11849617d95eSNick Piggin  * @address:	the user virtual address mapped
1185f1e2db12SDavid Hildenbrand  * @flags:	the rmap flags
11869617d95eSNick Piggin  *
11875ad64688SHugh Dickins  * The caller needs to hold the pte lock, and the page must be locked in
118880e14822SHugh Dickins  * the anon_vma case: to serialize mapping,index checking after setting,
118980e14822SHugh Dickins  * and to ensure that PageAnon is not being upgraded racily to PageKsm
119080e14822SHugh Dickins  * (but PageKsm is never downgraded to PageAnon).
11919617d95eSNick Piggin  */
11929617d95eSNick Piggin void page_add_anon_rmap(struct page *page,
119314f9135dSDavid Hildenbrand 	struct vm_area_struct *vma, unsigned long address, rmap_t flags)
1194ad8c2ee8SRik van Riel {
1195d281ee61SKirill A. Shutemov 	bool compound = flags & RMAP_COMPOUND;
119653f9263bSKirill A. Shutemov 	bool first;
119753f9263bSKirill A. Shutemov 
1198be5d0a74SJohannes Weiner 	if (unlikely(PageKsm(page)))
1199be5d0a74SJohannes Weiner 		lock_page_memcg(page);
1200be5d0a74SJohannes Weiner 	else
1201be5d0a74SJohannes Weiner 		VM_BUG_ON_PAGE(!PageLocked(page), page);
1202be5d0a74SJohannes Weiner 
120353f9263bSKirill A. Shutemov 	if (compound) {
120453f9263bSKirill A. Shutemov 		atomic_t *mapcount;
1205e9b61f19SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
120653f9263bSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageTransHuge(page), page);
120753f9263bSKirill A. Shutemov 		mapcount = compound_mapcount_ptr(page);
120853f9263bSKirill A. Shutemov 		first = atomic_inc_and_test(mapcount);
120953f9263bSKirill A. Shutemov 	} else {
121053f9263bSKirill A. Shutemov 		first = atomic_inc_and_test(&page->_mapcount);
121153f9263bSKirill A. Shutemov 	}
12126c287605SDavid Hildenbrand 	VM_BUG_ON_PAGE(!first && (flags & RMAP_EXCLUSIVE), page);
12136c287605SDavid Hildenbrand 	VM_BUG_ON_PAGE(!first && PageAnonExclusive(page), page);
121453f9263bSKirill A. Shutemov 
121553f9263bSKirill A. Shutemov 	if (first) {
12166c357848SMatthew Wilcox (Oracle) 		int nr = compound ? thp_nr_pages(page) : 1;
1217bea04b07SJianyu Zhan 		/*
1218bea04b07SJianyu Zhan 		 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1219bea04b07SJianyu Zhan 		 * these counters are not modified in interrupt context, and
1220bea04b07SJianyu Zhan 		 * pte lock(a spinlock) is held, which implies preemption
1221bea04b07SJianyu Zhan 		 * disabled.
1222bea04b07SJianyu Zhan 		 */
122365c45377SKirill A. Shutemov 		if (compound)
122469473e5dSMuchun Song 			__mod_lruvec_page_state(page, NR_ANON_THPS, nr);
1225be5d0a74SJohannes Weiner 		__mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
122679134171SAndrea Arcangeli 	}
12275ad64688SHugh Dickins 
1228cea86fe2SHugh Dickins 	if (unlikely(PageKsm(page)))
1229be5d0a74SJohannes Weiner 		unlock_page_memcg(page);
123053f9263bSKirill A. Shutemov 
12315dbe0af4SHugh Dickins 	/* address might be in next vma when migration races vma_adjust */
1232cea86fe2SHugh Dickins 	else if (first)
1233d281ee61SKirill A. Shutemov 		__page_set_anon_rmap(page, vma, address,
123414f9135dSDavid Hildenbrand 				     !!(flags & RMAP_EXCLUSIVE));
123569029cd5SKAMEZAWA Hiroyuki 	else
1236c97a9e10SNick Piggin 		__page_check_anon_rmap(page, vma, address);
1237cea86fe2SHugh Dickins 
1238cea86fe2SHugh Dickins 	mlock_vma_page(page, vma, compound);
12391da177e4SLinus Torvalds }
12401da177e4SLinus Torvalds 
124143d8eac4SRandy Dunlap /**
124240f2bbf7SDavid Hildenbrand  * page_add_new_anon_rmap - add mapping to a new anonymous page
12439617d95eSNick Piggin  * @page:	the page to add the mapping to
12449617d95eSNick Piggin  * @vma:	the vm area in which the mapping is added
12459617d95eSNick Piggin  * @address:	the user virtual address mapped
124640f2bbf7SDavid Hildenbrand  *
124740f2bbf7SDavid Hildenbrand  * If it's a compound page, it is accounted as a compound page. As the page
124840f2bbf7SDavid Hildenbrand  * is new, it's assume to get mapped exclusively by a single process.
12499617d95eSNick Piggin  *
12509617d95eSNick Piggin  * Same as page_add_anon_rmap but must only be called on *new* pages.
12519617d95eSNick Piggin  * This means the inc-and-test can be bypassed.
1252c97a9e10SNick Piggin  * Page does not have to be locked.
12539617d95eSNick Piggin  */
12549617d95eSNick Piggin void page_add_new_anon_rmap(struct page *page,
125540f2bbf7SDavid Hildenbrand 	struct vm_area_struct *vma, unsigned long address)
12569617d95eSNick Piggin {
125740f2bbf7SDavid Hildenbrand 	const bool compound = PageCompound(page);
12586c357848SMatthew Wilcox (Oracle) 	int nr = compound ? thp_nr_pages(page) : 1;
1259d281ee61SKirill A. Shutemov 
126081d1b09cSSasha Levin 	VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
1261fa9949daSHugh Dickins 	__SetPageSwapBacked(page);
1262d281ee61SKirill A. Shutemov 	if (compound) {
1263d281ee61SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageTransHuge(page), page);
126453f9263bSKirill A. Shutemov 		/* increment count (starts at -1) */
126553f9263bSKirill A. Shutemov 		atomic_set(compound_mapcount_ptr(page), 0);
126647e29d32SJohn Hubbard 		atomic_set(compound_pincount_ptr(page), 0);
126747e29d32SJohn Hubbard 
126869473e5dSMuchun Song 		__mod_lruvec_page_state(page, NR_ANON_THPS, nr);
126953f9263bSKirill A. Shutemov 	} else {
127053f9263bSKirill A. Shutemov 		/* increment count (starts at -1) */
127153f9263bSKirill A. Shutemov 		atomic_set(&page->_mapcount, 0);
1272d281ee61SKirill A. Shutemov 	}
1273be5d0a74SJohannes Weiner 	__mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
1274e8a03febSRik van Riel 	__page_set_anon_rmap(page, vma, address, 1);
12759617d95eSNick Piggin }
12769617d95eSNick Piggin 
12771da177e4SLinus Torvalds /**
12781da177e4SLinus Torvalds  * page_add_file_rmap - add pte mapping to a file page
12791da177e4SLinus Torvalds  * @page:	the page to add the mapping to
1280cea86fe2SHugh Dickins  * @vma:	the vm area in which the mapping is added
1281e8b098fcSMike Rapoport  * @compound:	charge the page as compound or small page
12821da177e4SLinus Torvalds  *
1283b8072f09SHugh Dickins  * The caller needs to hold the pte lock.
12841da177e4SLinus Torvalds  */
1285cea86fe2SHugh Dickins void page_add_file_rmap(struct page *page,
1286cea86fe2SHugh Dickins 	struct vm_area_struct *vma, bool compound)
12871da177e4SLinus Torvalds {
12885d543f13SHugh Dickins 	int i, nr = 0;
1289dd78feddSKirill A. Shutemov 
1290dd78feddSKirill A. Shutemov 	VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
129162cccb8cSJohannes Weiner 	lock_page_memcg(page);
1292dd78feddSKirill A. Shutemov 	if (compound && PageTransHuge(page)) {
1293a1528e21SMuchun Song 		int nr_pages = thp_nr_pages(page);
1294a1528e21SMuchun Song 
12955d543f13SHugh Dickins 		for (i = 0; i < nr_pages; i++) {
1296dd78feddSKirill A. Shutemov 			if (atomic_inc_and_test(&page[i]._mapcount))
1297dd78feddSKirill A. Shutemov 				nr++;
1298d69b042fSBalbir Singh 		}
1299dd78feddSKirill A. Shutemov 		if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
1300dd78feddSKirill A. Shutemov 			goto out;
1301bd55b0c2SHugh Dickins 
1302bd55b0c2SHugh Dickins 		/*
1303bd55b0c2SHugh Dickins 		 * It is racy to ClearPageDoubleMap in page_remove_file_rmap();
1304bd55b0c2SHugh Dickins 		 * but page lock is held by all page_add_file_rmap() compound
1305bd55b0c2SHugh Dickins 		 * callers, and SetPageDoubleMap below warns if !PageLocked:
1306bd55b0c2SHugh Dickins 		 * so here is a place that DoubleMap can be safely cleared.
1307bd55b0c2SHugh Dickins 		 */
1308bd55b0c2SHugh Dickins 		VM_WARN_ON_ONCE(!PageLocked(page));
1309bd55b0c2SHugh Dickins 		if (nr == nr_pages && PageDoubleMap(page))
1310bd55b0c2SHugh Dickins 			ClearPageDoubleMap(page);
1311bd55b0c2SHugh Dickins 
131299cb0dbdSSong Liu 		if (PageSwapBacked(page))
1313a1528e21SMuchun Song 			__mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1314a1528e21SMuchun Song 						nr_pages);
131599cb0dbdSSong Liu 		else
1316380780e7SMuchun Song 			__mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1317380780e7SMuchun Song 						nr_pages);
1318dd78feddSKirill A. Shutemov 	} else {
1319c8efc390SKirill A. Shutemov 		if (PageTransCompound(page) && page_mapping(page)) {
1320c8efc390SKirill A. Shutemov 			VM_WARN_ON_ONCE(!PageLocked(page));
1321cea86fe2SHugh Dickins 			SetPageDoubleMap(compound_head(page));
13229a73f61bSKirill A. Shutemov 		}
13235d543f13SHugh Dickins 		if (atomic_inc_and_test(&page->_mapcount))
13245d543f13SHugh Dickins 			nr++;
1325dd78feddSKirill A. Shutemov 	}
1326dd78feddSKirill A. Shutemov out:
13275d543f13SHugh Dickins 	if (nr)
13285d543f13SHugh Dickins 		__mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
132962cccb8cSJohannes Weiner 	unlock_page_memcg(page);
1330cea86fe2SHugh Dickins 
1331cea86fe2SHugh Dickins 	mlock_vma_page(page, vma, compound);
13321da177e4SLinus Torvalds }
13331da177e4SLinus Torvalds 
1334dd78feddSKirill A. Shutemov static void page_remove_file_rmap(struct page *page, bool compound)
13358186eb6aSJohannes Weiner {
13365d543f13SHugh Dickins 	int i, nr = 0;
1337dd78feddSKirill A. Shutemov 
133857dea93aSSteve Capper 	VM_BUG_ON_PAGE(compound && !PageHead(page), page);
13398186eb6aSJohannes Weiner 
134053f9263bSKirill A. Shutemov 	/* Hugepages are not counted in NR_FILE_MAPPED for now. */
134153f9263bSKirill A. Shutemov 	if (unlikely(PageHuge(page))) {
134253f9263bSKirill A. Shutemov 		/* hugetlb pages are always mapped with pmds */
134353f9263bSKirill A. Shutemov 		atomic_dec(compound_mapcount_ptr(page));
1344be5d0a74SJohannes Weiner 		return;
134553f9263bSKirill A. Shutemov 	}
134653f9263bSKirill A. Shutemov 
13478186eb6aSJohannes Weiner 	/* page still mapped by someone else? */
1348dd78feddSKirill A. Shutemov 	if (compound && PageTransHuge(page)) {
1349a1528e21SMuchun Song 		int nr_pages = thp_nr_pages(page);
1350a1528e21SMuchun Song 
13515d543f13SHugh Dickins 		for (i = 0; i < nr_pages; i++) {
1352dd78feddSKirill A. Shutemov 			if (atomic_add_negative(-1, &page[i]._mapcount))
1353dd78feddSKirill A. Shutemov 				nr++;
1354dd78feddSKirill A. Shutemov 		}
1355dd78feddSKirill A. Shutemov 		if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
13565d543f13SHugh Dickins 			goto out;
135799cb0dbdSSong Liu 		if (PageSwapBacked(page))
1358a1528e21SMuchun Song 			__mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1359a1528e21SMuchun Song 						-nr_pages);
136099cb0dbdSSong Liu 		else
1361380780e7SMuchun Song 			__mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1362380780e7SMuchun Song 						-nr_pages);
1363dd78feddSKirill A. Shutemov 	} else {
13645d543f13SHugh Dickins 		if (atomic_add_negative(-1, &page->_mapcount))
13655d543f13SHugh Dickins 			nr++;
1366dd78feddSKirill A. Shutemov 	}
13675d543f13SHugh Dickins out:
13685d543f13SHugh Dickins 	if (nr)
136900f3ca2cSJohannes Weiner 		__mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
13708186eb6aSJohannes Weiner }
13718186eb6aSJohannes Weiner 
137253f9263bSKirill A. Shutemov static void page_remove_anon_compound_rmap(struct page *page)
137353f9263bSKirill A. Shutemov {
137453f9263bSKirill A. Shutemov 	int i, nr;
137553f9263bSKirill A. Shutemov 
137653f9263bSKirill A. Shutemov 	if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
137753f9263bSKirill A. Shutemov 		return;
137853f9263bSKirill A. Shutemov 
137953f9263bSKirill A. Shutemov 	/* Hugepages are not counted in NR_ANON_PAGES for now. */
138053f9263bSKirill A. Shutemov 	if (unlikely(PageHuge(page)))
138153f9263bSKirill A. Shutemov 		return;
138253f9263bSKirill A. Shutemov 
138353f9263bSKirill A. Shutemov 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
138453f9263bSKirill A. Shutemov 		return;
138553f9263bSKirill A. Shutemov 
138669473e5dSMuchun Song 	__mod_lruvec_page_state(page, NR_ANON_THPS, -thp_nr_pages(page));
138753f9263bSKirill A. Shutemov 
138853f9263bSKirill A. Shutemov 	if (TestClearPageDoubleMap(page)) {
138953f9263bSKirill A. Shutemov 		/*
139053f9263bSKirill A. Shutemov 		 * Subpages can be mapped with PTEs too. Check how many of
1391f1fe80d4SKirill A. Shutemov 		 * them are still mapped.
139253f9263bSKirill A. Shutemov 		 */
13935eaf35abSMatthew Wilcox (Oracle) 		for (i = 0, nr = 0; i < thp_nr_pages(page); i++) {
139453f9263bSKirill A. Shutemov 			if (atomic_add_negative(-1, &page[i]._mapcount))
139553f9263bSKirill A. Shutemov 				nr++;
139653f9263bSKirill A. Shutemov 		}
1397f1fe80d4SKirill A. Shutemov 
1398f1fe80d4SKirill A. Shutemov 		/*
1399f1fe80d4SKirill A. Shutemov 		 * Queue the page for deferred split if at least one small
1400f1fe80d4SKirill A. Shutemov 		 * page of the compound page is unmapped, but at least one
1401f1fe80d4SKirill A. Shutemov 		 * small page is still mapped.
1402f1fe80d4SKirill A. Shutemov 		 */
14035eaf35abSMatthew Wilcox (Oracle) 		if (nr && nr < thp_nr_pages(page))
1404f1fe80d4SKirill A. Shutemov 			deferred_split_huge_page(page);
140553f9263bSKirill A. Shutemov 	} else {
14065eaf35abSMatthew Wilcox (Oracle) 		nr = thp_nr_pages(page);
140753f9263bSKirill A. Shutemov 	}
140853f9263bSKirill A. Shutemov 
1409f1fe80d4SKirill A. Shutemov 	if (nr)
1410be5d0a74SJohannes Weiner 		__mod_lruvec_page_state(page, NR_ANON_MAPPED, -nr);
141153f9263bSKirill A. Shutemov }
141253f9263bSKirill A. Shutemov 
14131da177e4SLinus Torvalds /**
14141da177e4SLinus Torvalds  * page_remove_rmap - take down pte mapping from a page
14151da177e4SLinus Torvalds  * @page:	page to remove mapping from
1416cea86fe2SHugh Dickins  * @vma:	the vm area from which the mapping is removed
1417d281ee61SKirill A. Shutemov  * @compound:	uncharge the page as compound or small page
14181da177e4SLinus Torvalds  *
1419b8072f09SHugh Dickins  * The caller needs to hold the pte lock.
14201da177e4SLinus Torvalds  */
1421cea86fe2SHugh Dickins void page_remove_rmap(struct page *page,
1422cea86fe2SHugh Dickins 	struct vm_area_struct *vma, bool compound)
14231da177e4SLinus Torvalds {
1424be5d0a74SJohannes Weiner 	lock_page_memcg(page);
142589c06bd5SKAMEZAWA Hiroyuki 
1426be5d0a74SJohannes Weiner 	if (!PageAnon(page)) {
1427be5d0a74SJohannes Weiner 		page_remove_file_rmap(page, compound);
1428be5d0a74SJohannes Weiner 		goto out;
1429be5d0a74SJohannes Weiner 	}
1430be5d0a74SJohannes Weiner 
1431be5d0a74SJohannes Weiner 	if (compound) {
1432be5d0a74SJohannes Weiner 		page_remove_anon_compound_rmap(page);
1433be5d0a74SJohannes Weiner 		goto out;
1434be5d0a74SJohannes Weiner 	}
143553f9263bSKirill A. Shutemov 
1436b904dcfeSKOSAKI Motohiro 	/* page still mapped by someone else? */
1437b904dcfeSKOSAKI Motohiro 	if (!atomic_add_negative(-1, &page->_mapcount))
1438be5d0a74SJohannes Weiner 		goto out;
14398186eb6aSJohannes Weiner 
14401da177e4SLinus Torvalds 	/*
1441bea04b07SJianyu Zhan 	 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1442bea04b07SJianyu Zhan 	 * these counters are not modified in interrupt context, and
1443bea04b07SJianyu Zhan 	 * pte lock(a spinlock) is held, which implies preemption disabled.
14440fe6e20bSNaoya Horiguchi 	 */
1445be5d0a74SJohannes Weiner 	__dec_lruvec_page_state(page, NR_ANON_MAPPED);
14468186eb6aSJohannes Weiner 
14479a982250SKirill A. Shutemov 	if (PageTransCompound(page))
14489a982250SKirill A. Shutemov 		deferred_split_huge_page(compound_head(page));
14499a982250SKirill A. Shutemov 
145016f8c5b2SHugh Dickins 	/*
14511da177e4SLinus Torvalds 	 * It would be tidy to reset the PageAnon mapping here,
14521da177e4SLinus Torvalds 	 * but that might overwrite a racing page_add_anon_rmap
14531da177e4SLinus Torvalds 	 * which increments mapcount after us but sets mapping
14542d4894b5SMel Gorman 	 * before us: so leave the reset to free_unref_page,
14551da177e4SLinus Torvalds 	 * and remember that it's only reliable while mapped.
14561da177e4SLinus Torvalds 	 * Leaving it set also helps swapoff to reinstate ptes
14571da177e4SLinus Torvalds 	 * faster for those pages still in swapcache.
14581da177e4SLinus Torvalds 	 */
1459be5d0a74SJohannes Weiner out:
1460be5d0a74SJohannes Weiner 	unlock_page_memcg(page);
1461cea86fe2SHugh Dickins 
1462cea86fe2SHugh Dickins 	munlock_vma_page(page, vma, compound);
14631da177e4SLinus Torvalds }
14641da177e4SLinus Torvalds 
14651da177e4SLinus Torvalds /*
146652629506SJoonsoo Kim  * @arg: enum ttu_flags will be passed to this argument
14671da177e4SLinus Torvalds  */
14682f031c6fSMatthew Wilcox (Oracle) static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
146952629506SJoonsoo Kim 		     unsigned long address, void *arg)
14701da177e4SLinus Torvalds {
14711da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
1472869f7ee6SMatthew Wilcox (Oracle) 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
14731da177e4SLinus Torvalds 	pte_t pteval;
1474c7ab0d2fSKirill A. Shutemov 	struct page *subpage;
14756c287605SDavid Hildenbrand 	bool anon_exclusive, ret = true;
1476ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
14774708f318SPalmer Dabbelt 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
14781da177e4SLinus Torvalds 
1479732ed558SHugh Dickins 	/*
1480732ed558SHugh Dickins 	 * When racing against e.g. zap_pte_range() on another cpu,
1481732ed558SHugh Dickins 	 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
14821fb08ac6SYang Shi 	 * try_to_unmap() may return before page_mapped() has become false,
1483732ed558SHugh Dickins 	 * if page table locking is skipped: use TTU_SYNC to wait for that.
1484732ed558SHugh Dickins 	 */
1485732ed558SHugh Dickins 	if (flags & TTU_SYNC)
1486732ed558SHugh Dickins 		pvmw.flags = PVMW_SYNC;
1487732ed558SHugh Dickins 
1488a98a2f0cSAlistair Popple 	if (flags & TTU_SPLIT_HUGE_PMD)
1489af28a988SMatthew Wilcox (Oracle) 		split_huge_pmd_address(vma, address, false, folio);
1490fec89c10SKirill A. Shutemov 
1491369ea824SJérôme Glisse 	/*
1492017b1660SMike Kravetz 	 * For THP, we have to assume the worse case ie pmd for invalidation.
1493017b1660SMike Kravetz 	 * For hugetlb, it could be much worse if we need to do pud
1494017b1660SMike Kravetz 	 * invalidation in the case of pmd sharing.
1495017b1660SMike Kravetz 	 *
1496869f7ee6SMatthew Wilcox (Oracle) 	 * Note that the folio can not be freed in this function as call of
1497869f7ee6SMatthew Wilcox (Oracle) 	 * try_to_unmap() must hold a reference on the folio.
1498369ea824SJérôme Glisse 	 */
14992aff7a47SMatthew Wilcox (Oracle) 	range.end = vma_address_end(&pvmw);
15007269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1501494334e4SHugh Dickins 				address, range.end);
1502869f7ee6SMatthew Wilcox (Oracle) 	if (folio_test_hugetlb(folio)) {
1503017b1660SMike Kravetz 		/*
1504017b1660SMike Kravetz 		 * If sharing is possible, start and end will be adjusted
1505017b1660SMike Kravetz 		 * accordingly.
1506017b1660SMike Kravetz 		 */
1507ac46d4f3SJérôme Glisse 		adjust_range_if_pmd_sharing_possible(vma, &range.start,
1508ac46d4f3SJérôme Glisse 						     &range.end);
1509017b1660SMike Kravetz 	}
1510ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
1511369ea824SJérôme Glisse 
1512c7ab0d2fSKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
1513cea86fe2SHugh Dickins 		/* Unexpected PMD-mapped THP? */
1514869f7ee6SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!pvmw.pte, folio);
1515cea86fe2SHugh Dickins 
15161da177e4SLinus Torvalds 		/*
1517869f7ee6SMatthew Wilcox (Oracle) 		 * If the folio is in an mlock()d vma, we must not swap it out.
15181da177e4SLinus Torvalds 		 */
1519efdb6720SHugh Dickins 		if (!(flags & TTU_IGNORE_MLOCK) &&
1520efdb6720SHugh Dickins 		    (vma->vm_flags & VM_LOCKED)) {
1521cea86fe2SHugh Dickins 			/* Restore the mlock which got missed */
1522869f7ee6SMatthew Wilcox (Oracle) 			mlock_vma_folio(folio, vma, false);
1523c7ab0d2fSKirill A. Shutemov 			page_vma_mapped_walk_done(&pvmw);
1524efdb6720SHugh Dickins 			ret = false;
1525c7ab0d2fSKirill A. Shutemov 			break;
1526b87537d9SHugh Dickins 		}
1527c7ab0d2fSKirill A. Shutemov 
1528869f7ee6SMatthew Wilcox (Oracle) 		subpage = folio_page(folio,
1529869f7ee6SMatthew Wilcox (Oracle) 					pte_pfn(*pvmw.pte) - folio_pfn(folio));
1530785373b4SLinus Torvalds 		address = pvmw.address;
15316c287605SDavid Hildenbrand 		anon_exclusive = folio_test_anon(folio) &&
15326c287605SDavid Hildenbrand 				 PageAnonExclusive(subpage);
1533785373b4SLinus Torvalds 
1534dfc7ab57SBaolin Wang 		if (folio_test_hugetlb(folio)) {
15350506c31dSBaolin Wang 			bool anon = folio_test_anon(folio);
15360506c31dSBaolin Wang 
1537017b1660SMike Kravetz 			/*
1538a00a8759SBaolin Wang 			 * The try_to_unmap() is only passed a hugetlb page
1539a00a8759SBaolin Wang 			 * in the case where the hugetlb page is poisoned.
1540a00a8759SBaolin Wang 			 */
1541a00a8759SBaolin Wang 			VM_BUG_ON_PAGE(!PageHWPoison(subpage), subpage);
1542a00a8759SBaolin Wang 			/*
154354205e9cSBaolin Wang 			 * huge_pmd_unshare may unmap an entire PMD page.
154454205e9cSBaolin Wang 			 * There is no way of knowing exactly which PMDs may
154554205e9cSBaolin Wang 			 * be cached for this mm, so we must flush them all.
154654205e9cSBaolin Wang 			 * start/end were already adjusted above to cover this
154754205e9cSBaolin Wang 			 * range.
1548017b1660SMike Kravetz 			 */
1549ac46d4f3SJérôme Glisse 			flush_cache_range(vma, range.start, range.end);
155054205e9cSBaolin Wang 
1551dfc7ab57SBaolin Wang 			/*
1552dfc7ab57SBaolin Wang 			 * To call huge_pmd_unshare, i_mmap_rwsem must be
1553dfc7ab57SBaolin Wang 			 * held in write mode.  Caller needs to explicitly
1554dfc7ab57SBaolin Wang 			 * do this outside rmap routines.
1555dfc7ab57SBaolin Wang 			 */
15560506c31dSBaolin Wang 			VM_BUG_ON(!anon && !(flags & TTU_RMAP_LOCKED));
15574ddb4d91SMike Kravetz 			if (!anon && huge_pmd_unshare(mm, vma, address, pvmw.pte)) {
1558ac46d4f3SJérôme Glisse 				flush_tlb_range(vma, range.start, range.end);
1559ac46d4f3SJérôme Glisse 				mmu_notifier_invalidate_range(mm, range.start,
1560ac46d4f3SJérôme Glisse 							      range.end);
1561017b1660SMike Kravetz 
1562017b1660SMike Kravetz 				/*
1563017b1660SMike Kravetz 				 * The ref count of the PMD page was dropped
1564017b1660SMike Kravetz 				 * which is part of the way map counting
1565017b1660SMike Kravetz 				 * is done for shared PMDs.  Return 'true'
1566017b1660SMike Kravetz 				 * here.  When there is no other sharing,
1567017b1660SMike Kravetz 				 * huge_pmd_unshare returns false and we will
1568017b1660SMike Kravetz 				 * unmap the actual page and drop map count
1569017b1660SMike Kravetz 				 * to zero.
1570017b1660SMike Kravetz 				 */
1571017b1660SMike Kravetz 				page_vma_mapped_walk_done(&pvmw);
1572017b1660SMike Kravetz 				break;
1573017b1660SMike Kravetz 			}
1574a00a8759SBaolin Wang 			pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
157554205e9cSBaolin Wang 		} else {
157654205e9cSBaolin Wang 			flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
1577088b8aa5SDavid Hildenbrand 			/* Nuke the page table entry. */
1578088b8aa5SDavid Hildenbrand 			if (should_defer_flush(mm, flags)) {
157972b252aeSMel Gorman 				/*
1580c7ab0d2fSKirill A. Shutemov 				 * We clear the PTE but do not flush so potentially
1581869f7ee6SMatthew Wilcox (Oracle) 				 * a remote CPU could still be writing to the folio.
1582c7ab0d2fSKirill A. Shutemov 				 * If the entry was previously clean then the
1583c7ab0d2fSKirill A. Shutemov 				 * architecture must guarantee that a clear->dirty
1584c7ab0d2fSKirill A. Shutemov 				 * transition on a cached TLB entry is written through
1585c7ab0d2fSKirill A. Shutemov 				 * and traps if the PTE is unmapped.
158672b252aeSMel Gorman 				 */
1587785373b4SLinus Torvalds 				pteval = ptep_get_and_clear(mm, address, pvmw.pte);
158872b252aeSMel Gorman 
1589c7ab0d2fSKirill A. Shutemov 				set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
159072b252aeSMel Gorman 			} else {
1591785373b4SLinus Torvalds 				pteval = ptep_clear_flush(vma, address, pvmw.pte);
159272b252aeSMel Gorman 			}
1593a00a8759SBaolin Wang 		}
15941da177e4SLinus Torvalds 
1595999dad82SPeter Xu 		/*
1596999dad82SPeter Xu 		 * Now the pte is cleared. If this pte was uffd-wp armed,
1597999dad82SPeter Xu 		 * we may want to replace a none pte with a marker pte if
1598999dad82SPeter Xu 		 * it's file-backed, so we don't lose the tracking info.
1599999dad82SPeter Xu 		 */
1600999dad82SPeter Xu 		pte_install_uffd_wp_if_needed(vma, address, pvmw.pte, pteval);
1601999dad82SPeter Xu 
1602869f7ee6SMatthew Wilcox (Oracle) 		/* Set the dirty flag on the folio now the pte is gone. */
16031da177e4SLinus Torvalds 		if (pte_dirty(pteval))
1604869f7ee6SMatthew Wilcox (Oracle) 			folio_mark_dirty(folio);
16051da177e4SLinus Torvalds 
1606365e9c87SHugh Dickins 		/* Update high watermark before we lower rss */
1607365e9c87SHugh Dickins 		update_hiwater_rss(mm);
1608365e9c87SHugh Dickins 
1609da358d5cSMatthew Wilcox (Oracle) 		if (PageHWPoison(subpage) && !(flags & TTU_IGNORE_HWPOISON)) {
16105fd27b8eSPunit Agrawal 			pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
1611869f7ee6SMatthew Wilcox (Oracle) 			if (folio_test_hugetlb(folio)) {
1612869f7ee6SMatthew Wilcox (Oracle) 				hugetlb_count_sub(folio_nr_pages(folio), mm);
161318f39629SQi Zheng 				set_huge_pte_at(mm, address, pvmw.pte, pteval);
16145d317b2bSNaoya Horiguchi 			} else {
1615869f7ee6SMatthew Wilcox (Oracle) 				dec_mm_counter(mm, mm_counter(&folio->page));
1616785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
16175f24ae58SNaoya Horiguchi 			}
1618c7ab0d2fSKirill A. Shutemov 
1619bce73e48SChristian Borntraeger 		} else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
162045961722SKonstantin Weitz 			/*
162145961722SKonstantin Weitz 			 * The guest indicated that the page content is of no
162245961722SKonstantin Weitz 			 * interest anymore. Simply discard the pte, vmscan
162345961722SKonstantin Weitz 			 * will take care of the rest.
1624bce73e48SChristian Borntraeger 			 * A future reference will then fault in a new zero
1625bce73e48SChristian Borntraeger 			 * page. When userfaultfd is active, we must not drop
1626bce73e48SChristian Borntraeger 			 * this page though, as its main user (postcopy
1627bce73e48SChristian Borntraeger 			 * migration) will not expect userfaults on already
1628bce73e48SChristian Borntraeger 			 * copied pages.
162945961722SKonstantin Weitz 			 */
1630869f7ee6SMatthew Wilcox (Oracle) 			dec_mm_counter(mm, mm_counter(&folio->page));
16310f10851eSJérôme Glisse 			/* We have to invalidate as we cleared the pte */
16320f10851eSJérôme Glisse 			mmu_notifier_invalidate_range(mm, address,
16330f10851eSJérôme Glisse 						      address + PAGE_SIZE);
1634869f7ee6SMatthew Wilcox (Oracle) 		} else if (folio_test_anon(folio)) {
1635c7ab0d2fSKirill A. Shutemov 			swp_entry_t entry = { .val = page_private(subpage) };
1636179ef71cSCyrill Gorcunov 			pte_t swp_pte;
16371da177e4SLinus Torvalds 			/*
16381da177e4SLinus Torvalds 			 * Store the swap location in the pte.
16391da177e4SLinus Torvalds 			 * See handle_pte_fault() ...
16401da177e4SLinus Torvalds 			 */
1641869f7ee6SMatthew Wilcox (Oracle) 			if (unlikely(folio_test_swapbacked(folio) !=
1642869f7ee6SMatthew Wilcox (Oracle) 					folio_test_swapcache(folio))) {
1643eb94a878SMinchan Kim 				WARN_ON_ONCE(1);
164483612a94SMinchan Kim 				ret = false;
1645369ea824SJérôme Glisse 				/* We have to invalidate as we cleared the pte */
16460f10851eSJérôme Glisse 				mmu_notifier_invalidate_range(mm, address,
16470f10851eSJérôme Glisse 							address + PAGE_SIZE);
1648eb94a878SMinchan Kim 				page_vma_mapped_walk_done(&pvmw);
1649eb94a878SMinchan Kim 				break;
1650eb94a878SMinchan Kim 			}
1651854e9ed0SMinchan Kim 
1652802a3a92SShaohua Li 			/* MADV_FREE page check */
1653869f7ee6SMatthew Wilcox (Oracle) 			if (!folio_test_swapbacked(folio)) {
16546c8e2a25SMauricio Faria de Oliveira 				int ref_count, map_count;
16556c8e2a25SMauricio Faria de Oliveira 
16566c8e2a25SMauricio Faria de Oliveira 				/*
16576c8e2a25SMauricio Faria de Oliveira 				 * Synchronize with gup_pte_range():
16586c8e2a25SMauricio Faria de Oliveira 				 * - clear PTE; barrier; read refcount
16596c8e2a25SMauricio Faria de Oliveira 				 * - inc refcount; barrier; read PTE
16606c8e2a25SMauricio Faria de Oliveira 				 */
16616c8e2a25SMauricio Faria de Oliveira 				smp_mb();
16626c8e2a25SMauricio Faria de Oliveira 
16636c8e2a25SMauricio Faria de Oliveira 				ref_count = folio_ref_count(folio);
16646c8e2a25SMauricio Faria de Oliveira 				map_count = folio_mapcount(folio);
16656c8e2a25SMauricio Faria de Oliveira 
16666c8e2a25SMauricio Faria de Oliveira 				/*
16676c8e2a25SMauricio Faria de Oliveira 				 * Order reads for page refcount and dirty flag
16686c8e2a25SMauricio Faria de Oliveira 				 * (see comments in __remove_mapping()).
16696c8e2a25SMauricio Faria de Oliveira 				 */
16706c8e2a25SMauricio Faria de Oliveira 				smp_rmb();
16716c8e2a25SMauricio Faria de Oliveira 
16726c8e2a25SMauricio Faria de Oliveira 				/*
16736c8e2a25SMauricio Faria de Oliveira 				 * The only page refs must be one from isolation
16746c8e2a25SMauricio Faria de Oliveira 				 * plus the rmap(s) (dropped by discard:).
16756c8e2a25SMauricio Faria de Oliveira 				 */
16766c8e2a25SMauricio Faria de Oliveira 				if (ref_count == 1 + map_count &&
16776c8e2a25SMauricio Faria de Oliveira 				    !folio_test_dirty(folio)) {
16780f10851eSJérôme Glisse 					/* Invalidate as we cleared the pte */
16790f10851eSJérôme Glisse 					mmu_notifier_invalidate_range(mm,
16800f10851eSJérôme Glisse 						address, address + PAGE_SIZE);
1681854e9ed0SMinchan Kim 					dec_mm_counter(mm, MM_ANONPAGES);
1682854e9ed0SMinchan Kim 					goto discard;
1683854e9ed0SMinchan Kim 				}
1684854e9ed0SMinchan Kim 
1685802a3a92SShaohua Li 				/*
1686869f7ee6SMatthew Wilcox (Oracle) 				 * If the folio was redirtied, it cannot be
1687802a3a92SShaohua Li 				 * discarded. Remap the page to page table.
1688802a3a92SShaohua Li 				 */
1689785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
1690869f7ee6SMatthew Wilcox (Oracle) 				folio_set_swapbacked(folio);
1691e4b82222SMinchan Kim 				ret = false;
1692802a3a92SShaohua Li 				page_vma_mapped_walk_done(&pvmw);
1693802a3a92SShaohua Li 				break;
1694802a3a92SShaohua Li 			}
1695802a3a92SShaohua Li 
1696570a335bSHugh Dickins 			if (swap_duplicate(entry) < 0) {
1697785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
1698e4b82222SMinchan Kim 				ret = false;
1699c7ab0d2fSKirill A. Shutemov 				page_vma_mapped_walk_done(&pvmw);
1700c7ab0d2fSKirill A. Shutemov 				break;
1701570a335bSHugh Dickins 			}
1702ca827d55SKhalid Aziz 			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1703322842eaSDavid Hildenbrand 				swap_free(entry);
1704ca827d55SKhalid Aziz 				set_pte_at(mm, address, pvmw.pte, pteval);
1705ca827d55SKhalid Aziz 				ret = false;
1706ca827d55SKhalid Aziz 				page_vma_mapped_walk_done(&pvmw);
1707ca827d55SKhalid Aziz 				break;
1708ca827d55SKhalid Aziz 			}
1709088b8aa5SDavid Hildenbrand 
1710088b8aa5SDavid Hildenbrand 			/* See page_try_share_anon_rmap(): clear PTE first. */
17116c287605SDavid Hildenbrand 			if (anon_exclusive &&
17126c287605SDavid Hildenbrand 			    page_try_share_anon_rmap(subpage)) {
17136c287605SDavid Hildenbrand 				swap_free(entry);
17146c287605SDavid Hildenbrand 				set_pte_at(mm, address, pvmw.pte, pteval);
17156c287605SDavid Hildenbrand 				ret = false;
17166c287605SDavid Hildenbrand 				page_vma_mapped_walk_done(&pvmw);
17176c287605SDavid Hildenbrand 				break;
17186c287605SDavid Hildenbrand 			}
17196c287605SDavid Hildenbrand 			/*
17201493a191SDavid Hildenbrand 			 * Note: We *don't* remember if the page was mapped
17211493a191SDavid Hildenbrand 			 * exclusively in the swap pte if the architecture
17221493a191SDavid Hildenbrand 			 * doesn't support __HAVE_ARCH_PTE_SWP_EXCLUSIVE. In
17231493a191SDavid Hildenbrand 			 * that case, swapin code has to re-determine that
17241493a191SDavid Hildenbrand 			 * manually and might detect the page as possibly
17251493a191SDavid Hildenbrand 			 * shared, for example, if there are other references on
17261493a191SDavid Hildenbrand 			 * the page or if the page is under writeback. We made
17271493a191SDavid Hildenbrand 			 * sure that there are no GUP pins on the page that
17281493a191SDavid Hildenbrand 			 * would rely on it, so for GUP pins this is fine.
17296c287605SDavid Hildenbrand 			 */
17301da177e4SLinus Torvalds 			if (list_empty(&mm->mmlist)) {
17311da177e4SLinus Torvalds 				spin_lock(&mmlist_lock);
1732f412ac08SHugh Dickins 				if (list_empty(&mm->mmlist))
17331da177e4SLinus Torvalds 					list_add(&mm->mmlist, &init_mm.mmlist);
17341da177e4SLinus Torvalds 				spin_unlock(&mmlist_lock);
17351da177e4SLinus Torvalds 			}
1736d559db08SKAMEZAWA Hiroyuki 			dec_mm_counter(mm, MM_ANONPAGES);
1737b084d435SKAMEZAWA Hiroyuki 			inc_mm_counter(mm, MM_SWAPENTS);
1738179ef71cSCyrill Gorcunov 			swp_pte = swp_entry_to_pte(entry);
17391493a191SDavid Hildenbrand 			if (anon_exclusive)
17401493a191SDavid Hildenbrand 				swp_pte = pte_swp_mkexclusive(swp_pte);
1741179ef71cSCyrill Gorcunov 			if (pte_soft_dirty(pteval))
1742179ef71cSCyrill Gorcunov 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1743f45ec5ffSPeter Xu 			if (pte_uffd_wp(pteval))
1744f45ec5ffSPeter Xu 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
1745785373b4SLinus Torvalds 			set_pte_at(mm, address, pvmw.pte, swp_pte);
17460f10851eSJérôme Glisse 			/* Invalidate as we cleared the pte */
1747369ea824SJérôme Glisse 			mmu_notifier_invalidate_range(mm, address,
1748369ea824SJérôme Glisse 						      address + PAGE_SIZE);
17490f10851eSJérôme Glisse 		} else {
17500f10851eSJérôme Glisse 			/*
1751869f7ee6SMatthew Wilcox (Oracle) 			 * This is a locked file-backed folio,
1752869f7ee6SMatthew Wilcox (Oracle) 			 * so it cannot be removed from the page
1753869f7ee6SMatthew Wilcox (Oracle) 			 * cache and replaced by a new folio before
1754869f7ee6SMatthew Wilcox (Oracle) 			 * mmu_notifier_invalidate_range_end, so no
1755869f7ee6SMatthew Wilcox (Oracle) 			 * concurrent thread might update its page table
1756869f7ee6SMatthew Wilcox (Oracle) 			 * to point at a new folio while a device is
1757869f7ee6SMatthew Wilcox (Oracle) 			 * still using this folio.
17580f10851eSJérôme Glisse 			 *
1759ee65728eSMike Rapoport 			 * See Documentation/mm/mmu_notifier.rst
17600f10851eSJérôme Glisse 			 */
1761869f7ee6SMatthew Wilcox (Oracle) 			dec_mm_counter(mm, mm_counter_file(&folio->page));
17620f10851eSJérôme Glisse 		}
17630f10851eSJérôme Glisse discard:
17640f10851eSJérôme Glisse 		/*
17650f10851eSJérôme Glisse 		 * No need to call mmu_notifier_invalidate_range() it has be
17660f10851eSJérôme Glisse 		 * done above for all cases requiring it to happen under page
17670f10851eSJérôme Glisse 		 * table lock before mmu_notifier_invalidate_range_end()
17680f10851eSJérôme Glisse 		 *
1769ee65728eSMike Rapoport 		 * See Documentation/mm/mmu_notifier.rst
17700f10851eSJérôme Glisse 		 */
1771869f7ee6SMatthew Wilcox (Oracle) 		page_remove_rmap(subpage, vma, folio_test_hugetlb(folio));
1772b7435507SHugh Dickins 		if (vma->vm_flags & VM_LOCKED)
1773adb11e78SSebastian Andrzej Siewior 			mlock_page_drain_local();
1774869f7ee6SMatthew Wilcox (Oracle) 		folio_put(folio);
1775c7ab0d2fSKirill A. Shutemov 	}
1776369ea824SJérôme Glisse 
1777ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
1778369ea824SJérôme Glisse 
1779caed0f48SKOSAKI Motohiro 	return ret;
17801da177e4SLinus Torvalds }
17811da177e4SLinus Torvalds 
178252629506SJoonsoo Kim static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
178352629506SJoonsoo Kim {
1784222100eeSAnshuman Khandual 	return vma_is_temporary_stack(vma);
178552629506SJoonsoo Kim }
178652629506SJoonsoo Kim 
17872f031c6fSMatthew Wilcox (Oracle) static int page_not_mapped(struct folio *folio)
178852629506SJoonsoo Kim {
17892f031c6fSMatthew Wilcox (Oracle) 	return !folio_mapped(folio);
17902a52bcbcSKirill A. Shutemov }
179152629506SJoonsoo Kim 
17921da177e4SLinus Torvalds /**
1793869f7ee6SMatthew Wilcox (Oracle)  * try_to_unmap - Try to remove all page table mappings to a folio.
1794869f7ee6SMatthew Wilcox (Oracle)  * @folio: The folio to unmap.
179514fa31b8SAndi Kleen  * @flags: action and flags
17961da177e4SLinus Torvalds  *
17971da177e4SLinus Torvalds  * Tries to remove all the page table entries which are mapping this
1798869f7ee6SMatthew Wilcox (Oracle)  * folio.  It is the caller's responsibility to check if the folio is
1799869f7ee6SMatthew Wilcox (Oracle)  * still mapped if needed (use TTU_SYNC to prevent accounting races).
18001da177e4SLinus Torvalds  *
1801869f7ee6SMatthew Wilcox (Oracle)  * Context: Caller must hold the folio lock.
18021da177e4SLinus Torvalds  */
1803869f7ee6SMatthew Wilcox (Oracle) void try_to_unmap(struct folio *folio, enum ttu_flags flags)
18041da177e4SLinus Torvalds {
180552629506SJoonsoo Kim 	struct rmap_walk_control rwc = {
180652629506SJoonsoo Kim 		.rmap_one = try_to_unmap_one,
1807802a3a92SShaohua Li 		.arg = (void *)flags,
1808b7e188ecSMiaohe Lin 		.done = page_not_mapped,
18092f031c6fSMatthew Wilcox (Oracle) 		.anon_lock = folio_lock_anon_vma_read,
181052629506SJoonsoo Kim 	};
18111da177e4SLinus Torvalds 
1812a98a2f0cSAlistair Popple 	if (flags & TTU_RMAP_LOCKED)
18132f031c6fSMatthew Wilcox (Oracle) 		rmap_walk_locked(folio, &rwc);
1814a98a2f0cSAlistair Popple 	else
18152f031c6fSMatthew Wilcox (Oracle) 		rmap_walk(folio, &rwc);
1816a98a2f0cSAlistair Popple }
1817a98a2f0cSAlistair Popple 
1818a98a2f0cSAlistair Popple /*
1819a98a2f0cSAlistair Popple  * @arg: enum ttu_flags will be passed to this argument.
1820a98a2f0cSAlistair Popple  *
1821a98a2f0cSAlistair Popple  * If TTU_SPLIT_HUGE_PMD is specified any PMD mappings will be split into PTEs
182264b586d1SHugh Dickins  * containing migration entries.
1823a98a2f0cSAlistair Popple  */
18242f031c6fSMatthew Wilcox (Oracle) static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,
1825a98a2f0cSAlistair Popple 		     unsigned long address, void *arg)
1826a98a2f0cSAlistair Popple {
1827a98a2f0cSAlistair Popple 	struct mm_struct *mm = vma->vm_mm;
18284b8554c5SMatthew Wilcox (Oracle) 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
1829a98a2f0cSAlistair Popple 	pte_t pteval;
1830a98a2f0cSAlistair Popple 	struct page *subpage;
18316c287605SDavid Hildenbrand 	bool anon_exclusive, ret = true;
1832a98a2f0cSAlistair Popple 	struct mmu_notifier_range range;
1833a98a2f0cSAlistair Popple 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
1834a98a2f0cSAlistair Popple 
1835a98a2f0cSAlistair Popple 	/*
1836a98a2f0cSAlistair Popple 	 * When racing against e.g. zap_pte_range() on another cpu,
1837a98a2f0cSAlistair Popple 	 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
1838a98a2f0cSAlistair Popple 	 * try_to_migrate() may return before page_mapped() has become false,
1839a98a2f0cSAlistair Popple 	 * if page table locking is skipped: use TTU_SYNC to wait for that.
1840a98a2f0cSAlistair Popple 	 */
1841a98a2f0cSAlistair Popple 	if (flags & TTU_SYNC)
1842a98a2f0cSAlistair Popple 		pvmw.flags = PVMW_SYNC;
1843a98a2f0cSAlistair Popple 
1844a98a2f0cSAlistair Popple 	/*
1845a98a2f0cSAlistair Popple 	 * unmap_page() in mm/huge_memory.c is the only user of migration with
1846a98a2f0cSAlistair Popple 	 * TTU_SPLIT_HUGE_PMD and it wants to freeze.
1847a98a2f0cSAlistair Popple 	 */
1848a98a2f0cSAlistair Popple 	if (flags & TTU_SPLIT_HUGE_PMD)
1849af28a988SMatthew Wilcox (Oracle) 		split_huge_pmd_address(vma, address, true, folio);
1850a98a2f0cSAlistair Popple 
1851a98a2f0cSAlistair Popple 	/*
1852a98a2f0cSAlistair Popple 	 * For THP, we have to assume the worse case ie pmd for invalidation.
1853a98a2f0cSAlistair Popple 	 * For hugetlb, it could be much worse if we need to do pud
1854a98a2f0cSAlistair Popple 	 * invalidation in the case of pmd sharing.
1855a98a2f0cSAlistair Popple 	 *
1856a98a2f0cSAlistair Popple 	 * Note that the page can not be free in this function as call of
1857a98a2f0cSAlistair Popple 	 * try_to_unmap() must hold a reference on the page.
1858a98a2f0cSAlistair Popple 	 */
18592aff7a47SMatthew Wilcox (Oracle) 	range.end = vma_address_end(&pvmw);
1860a98a2f0cSAlistair Popple 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1861a98a2f0cSAlistair Popple 				address, range.end);
18624b8554c5SMatthew Wilcox (Oracle) 	if (folio_test_hugetlb(folio)) {
1863a98a2f0cSAlistair Popple 		/*
1864a98a2f0cSAlistair Popple 		 * If sharing is possible, start and end will be adjusted
1865a98a2f0cSAlistair Popple 		 * accordingly.
1866a98a2f0cSAlistair Popple 		 */
1867a98a2f0cSAlistair Popple 		adjust_range_if_pmd_sharing_possible(vma, &range.start,
1868a98a2f0cSAlistair Popple 						     &range.end);
1869a98a2f0cSAlistair Popple 	}
1870a98a2f0cSAlistair Popple 	mmu_notifier_invalidate_range_start(&range);
1871a98a2f0cSAlistair Popple 
1872a98a2f0cSAlistair Popple 	while (page_vma_mapped_walk(&pvmw)) {
1873a98a2f0cSAlistair Popple #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1874a98a2f0cSAlistair Popple 		/* PMD-mapped THP migration entry */
1875a98a2f0cSAlistair Popple 		if (!pvmw.pte) {
18764b8554c5SMatthew Wilcox (Oracle) 			subpage = folio_page(folio,
18774b8554c5SMatthew Wilcox (Oracle) 				pmd_pfn(*pvmw.pmd) - folio_pfn(folio));
18784b8554c5SMatthew Wilcox (Oracle) 			VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
18794b8554c5SMatthew Wilcox (Oracle) 					!folio_test_pmd_mappable(folio), folio);
1880a98a2f0cSAlistair Popple 
18817f5abe60SDavid Hildenbrand 			if (set_pmd_migration_entry(&pvmw, subpage)) {
18827f5abe60SDavid Hildenbrand 				ret = false;
18837f5abe60SDavid Hildenbrand 				page_vma_mapped_walk_done(&pvmw);
18847f5abe60SDavid Hildenbrand 				break;
18857f5abe60SDavid Hildenbrand 			}
1886a98a2f0cSAlistair Popple 			continue;
1887a98a2f0cSAlistair Popple 		}
1888a98a2f0cSAlistair Popple #endif
1889a98a2f0cSAlistair Popple 
1890a98a2f0cSAlistair Popple 		/* Unexpected PMD-mapped THP? */
18914b8554c5SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!pvmw.pte, folio);
1892a98a2f0cSAlistair Popple 
18931118234eSDavid Hildenbrand 		if (folio_is_zone_device(folio)) {
18941118234eSDavid Hildenbrand 			/*
18951118234eSDavid Hildenbrand 			 * Our PTE is a non-present device exclusive entry and
18961118234eSDavid Hildenbrand 			 * calculating the subpage as for the common case would
18971118234eSDavid Hildenbrand 			 * result in an invalid pointer.
18981118234eSDavid Hildenbrand 			 *
18991118234eSDavid Hildenbrand 			 * Since only PAGE_SIZE pages can currently be
19001118234eSDavid Hildenbrand 			 * migrated, just set it to page. This will need to be
19011118234eSDavid Hildenbrand 			 * changed when hugepage migrations to device private
19021118234eSDavid Hildenbrand 			 * memory are supported.
19031118234eSDavid Hildenbrand 			 */
19041118234eSDavid Hildenbrand 			VM_BUG_ON_FOLIO(folio_nr_pages(folio) > 1, folio);
19051118234eSDavid Hildenbrand 			subpage = &folio->page;
19061118234eSDavid Hildenbrand 		} else {
19074b8554c5SMatthew Wilcox (Oracle) 			subpage = folio_page(folio,
19084b8554c5SMatthew Wilcox (Oracle) 					pte_pfn(*pvmw.pte) - folio_pfn(folio));
19091118234eSDavid Hildenbrand 		}
1910a98a2f0cSAlistair Popple 		address = pvmw.address;
19116c287605SDavid Hildenbrand 		anon_exclusive = folio_test_anon(folio) &&
19126c287605SDavid Hildenbrand 				 PageAnonExclusive(subpage);
1913a98a2f0cSAlistair Popple 
1914dfc7ab57SBaolin Wang 		if (folio_test_hugetlb(folio)) {
19150506c31dSBaolin Wang 			bool anon = folio_test_anon(folio);
19160506c31dSBaolin Wang 
1917a98a2f0cSAlistair Popple 			/*
191854205e9cSBaolin Wang 			 * huge_pmd_unshare may unmap an entire PMD page.
191954205e9cSBaolin Wang 			 * There is no way of knowing exactly which PMDs may
192054205e9cSBaolin Wang 			 * be cached for this mm, so we must flush them all.
192154205e9cSBaolin Wang 			 * start/end were already adjusted above to cover this
192254205e9cSBaolin Wang 			 * range.
1923a98a2f0cSAlistair Popple 			 */
1924a98a2f0cSAlistair Popple 			flush_cache_range(vma, range.start, range.end);
192554205e9cSBaolin Wang 
1926dfc7ab57SBaolin Wang 			/*
1927dfc7ab57SBaolin Wang 			 * To call huge_pmd_unshare, i_mmap_rwsem must be
1928dfc7ab57SBaolin Wang 			 * held in write mode.  Caller needs to explicitly
1929dfc7ab57SBaolin Wang 			 * do this outside rmap routines.
1930dfc7ab57SBaolin Wang 			 */
19310506c31dSBaolin Wang 			VM_BUG_ON(!anon && !(flags & TTU_RMAP_LOCKED));
19324ddb4d91SMike Kravetz 			if (!anon && huge_pmd_unshare(mm, vma, address, pvmw.pte)) {
1933a98a2f0cSAlistair Popple 				flush_tlb_range(vma, range.start, range.end);
1934a98a2f0cSAlistair Popple 				mmu_notifier_invalidate_range(mm, range.start,
1935a98a2f0cSAlistair Popple 							      range.end);
1936a98a2f0cSAlistair Popple 
1937a98a2f0cSAlistair Popple 				/*
1938a98a2f0cSAlistair Popple 				 * The ref count of the PMD page was dropped
1939a98a2f0cSAlistair Popple 				 * which is part of the way map counting
1940a98a2f0cSAlistair Popple 				 * is done for shared PMDs.  Return 'true'
1941a98a2f0cSAlistair Popple 				 * here.  When there is no other sharing,
1942a98a2f0cSAlistair Popple 				 * huge_pmd_unshare returns false and we will
1943a98a2f0cSAlistair Popple 				 * unmap the actual page and drop map count
1944a98a2f0cSAlistair Popple 				 * to zero.
1945a98a2f0cSAlistair Popple 				 */
1946a98a2f0cSAlistair Popple 				page_vma_mapped_walk_done(&pvmw);
1947a98a2f0cSAlistair Popple 				break;
1948a98a2f0cSAlistair Popple 			}
19495d4af619SBaolin Wang 
19505d4af619SBaolin Wang 			/* Nuke the hugetlb page table entry */
19515d4af619SBaolin Wang 			pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
195254205e9cSBaolin Wang 		} else {
195354205e9cSBaolin Wang 			flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
1954a98a2f0cSAlistair Popple 			/* Nuke the page table entry. */
1955a98a2f0cSAlistair Popple 			pteval = ptep_clear_flush(vma, address, pvmw.pte);
19565d4af619SBaolin Wang 		}
1957a98a2f0cSAlistair Popple 
19584b8554c5SMatthew Wilcox (Oracle) 		/* Set the dirty flag on the folio now the pte is gone. */
1959a98a2f0cSAlistair Popple 		if (pte_dirty(pteval))
19604b8554c5SMatthew Wilcox (Oracle) 			folio_mark_dirty(folio);
1961a98a2f0cSAlistair Popple 
1962a98a2f0cSAlistair Popple 		/* Update high watermark before we lower rss */
1963a98a2f0cSAlistair Popple 		update_hiwater_rss(mm);
1964a98a2f0cSAlistair Popple 
1965f25cbb7aSAlex Sierra 		if (folio_is_device_private(folio)) {
19664b8554c5SMatthew Wilcox (Oracle) 			unsigned long pfn = folio_pfn(folio);
1967a98a2f0cSAlistair Popple 			swp_entry_t entry;
1968a98a2f0cSAlistair Popple 			pte_t swp_pte;
1969a98a2f0cSAlistair Popple 
19706c287605SDavid Hildenbrand 			if (anon_exclusive)
19716c287605SDavid Hildenbrand 				BUG_ON(page_try_share_anon_rmap(subpage));
19726c287605SDavid Hildenbrand 
1973a98a2f0cSAlistair Popple 			/*
1974a98a2f0cSAlistair Popple 			 * Store the pfn of the page in a special migration
1975a98a2f0cSAlistair Popple 			 * pte. do_swap_page() will wait until the migration
1976a98a2f0cSAlistair Popple 			 * pte is removed and then restart fault handling.
1977a98a2f0cSAlistair Popple 			 */
19783d88705cSAlistair Popple 			entry = pte_to_swp_entry(pteval);
19793d88705cSAlistair Popple 			if (is_writable_device_private_entry(entry))
19803d88705cSAlistair Popple 				entry = make_writable_migration_entry(pfn);
19816c287605SDavid Hildenbrand 			else if (anon_exclusive)
19826c287605SDavid Hildenbrand 				entry = make_readable_exclusive_migration_entry(pfn);
19833d88705cSAlistair Popple 			else
19843d88705cSAlistair Popple 				entry = make_readable_migration_entry(pfn);
1985a98a2f0cSAlistair Popple 			swp_pte = swp_entry_to_pte(entry);
1986a98a2f0cSAlistair Popple 
1987a98a2f0cSAlistair Popple 			/*
1988a98a2f0cSAlistair Popple 			 * pteval maps a zone device page and is therefore
1989a98a2f0cSAlistair Popple 			 * a swap pte.
1990a98a2f0cSAlistair Popple 			 */
1991a98a2f0cSAlistair Popple 			if (pte_swp_soft_dirty(pteval))
1992a98a2f0cSAlistair Popple 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1993a98a2f0cSAlistair Popple 			if (pte_swp_uffd_wp(pteval))
1994a98a2f0cSAlistair Popple 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
1995a98a2f0cSAlistair Popple 			set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
19964cc79b33SAnshuman Khandual 			trace_set_migration_pte(pvmw.address, pte_val(swp_pte),
19974cc79b33SAnshuman Khandual 						compound_order(&folio->page));
1998a98a2f0cSAlistair Popple 			/*
1999a98a2f0cSAlistair Popple 			 * No need to invalidate here it will synchronize on
2000a98a2f0cSAlistair Popple 			 * against the special swap migration pte.
2001a98a2f0cSAlistair Popple 			 */
2002da358d5cSMatthew Wilcox (Oracle) 		} else if (PageHWPoison(subpage)) {
2003a98a2f0cSAlistair Popple 			pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
20044b8554c5SMatthew Wilcox (Oracle) 			if (folio_test_hugetlb(folio)) {
20054b8554c5SMatthew Wilcox (Oracle) 				hugetlb_count_sub(folio_nr_pages(folio), mm);
200618f39629SQi Zheng 				set_huge_pte_at(mm, address, pvmw.pte, pteval);
2007a98a2f0cSAlistair Popple 			} else {
20084b8554c5SMatthew Wilcox (Oracle) 				dec_mm_counter(mm, mm_counter(&folio->page));
2009a98a2f0cSAlistair Popple 				set_pte_at(mm, address, pvmw.pte, pteval);
2010a98a2f0cSAlistair Popple 			}
2011a98a2f0cSAlistair Popple 
2012a98a2f0cSAlistair Popple 		} else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
2013a98a2f0cSAlistair Popple 			/*
2014a98a2f0cSAlistair Popple 			 * The guest indicated that the page content is of no
2015a98a2f0cSAlistair Popple 			 * interest anymore. Simply discard the pte, vmscan
2016a98a2f0cSAlistair Popple 			 * will take care of the rest.
2017a98a2f0cSAlistair Popple 			 * A future reference will then fault in a new zero
2018a98a2f0cSAlistair Popple 			 * page. When userfaultfd is active, we must not drop
2019a98a2f0cSAlistair Popple 			 * this page though, as its main user (postcopy
2020a98a2f0cSAlistair Popple 			 * migration) will not expect userfaults on already
2021a98a2f0cSAlistair Popple 			 * copied pages.
2022a98a2f0cSAlistair Popple 			 */
20234b8554c5SMatthew Wilcox (Oracle) 			dec_mm_counter(mm, mm_counter(&folio->page));
2024a98a2f0cSAlistair Popple 			/* We have to invalidate as we cleared the pte */
2025a98a2f0cSAlistair Popple 			mmu_notifier_invalidate_range(mm, address,
2026a98a2f0cSAlistair Popple 						      address + PAGE_SIZE);
2027a98a2f0cSAlistair Popple 		} else {
2028a98a2f0cSAlistair Popple 			swp_entry_t entry;
2029a98a2f0cSAlistair Popple 			pte_t swp_pte;
2030a98a2f0cSAlistair Popple 
2031a98a2f0cSAlistair Popple 			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
20325d4af619SBaolin Wang 				if (folio_test_hugetlb(folio))
20335d4af619SBaolin Wang 					set_huge_pte_at(mm, address, pvmw.pte, pteval);
20345d4af619SBaolin Wang 				else
2035a98a2f0cSAlistair Popple 					set_pte_at(mm, address, pvmw.pte, pteval);
2036a98a2f0cSAlistair Popple 				ret = false;
2037a98a2f0cSAlistair Popple 				page_vma_mapped_walk_done(&pvmw);
2038a98a2f0cSAlistair Popple 				break;
2039a98a2f0cSAlistair Popple 			}
20406c287605SDavid Hildenbrand 			VM_BUG_ON_PAGE(pte_write(pteval) && folio_test_anon(folio) &&
20416c287605SDavid Hildenbrand 				       !anon_exclusive, subpage);
2042088b8aa5SDavid Hildenbrand 
2043088b8aa5SDavid Hildenbrand 			/* See page_try_share_anon_rmap(): clear PTE first. */
20446c287605SDavid Hildenbrand 			if (anon_exclusive &&
20456c287605SDavid Hildenbrand 			    page_try_share_anon_rmap(subpage)) {
20465d4af619SBaolin Wang 				if (folio_test_hugetlb(folio))
20475d4af619SBaolin Wang 					set_huge_pte_at(mm, address, pvmw.pte, pteval);
20485d4af619SBaolin Wang 				else
20496c287605SDavid Hildenbrand 					set_pte_at(mm, address, pvmw.pte, pteval);
20506c287605SDavid Hildenbrand 				ret = false;
20516c287605SDavid Hildenbrand 				page_vma_mapped_walk_done(&pvmw);
20526c287605SDavid Hildenbrand 				break;
20536c287605SDavid Hildenbrand 			}
2054a98a2f0cSAlistair Popple 
2055a98a2f0cSAlistair Popple 			/*
2056a98a2f0cSAlistair Popple 			 * Store the pfn of the page in a special migration
2057a98a2f0cSAlistair Popple 			 * pte. do_swap_page() will wait until the migration
2058a98a2f0cSAlistair Popple 			 * pte is removed and then restart fault handling.
2059a98a2f0cSAlistair Popple 			 */
2060a98a2f0cSAlistair Popple 			if (pte_write(pteval))
2061a98a2f0cSAlistair Popple 				entry = make_writable_migration_entry(
2062a98a2f0cSAlistair Popple 							page_to_pfn(subpage));
20636c287605SDavid Hildenbrand 			else if (anon_exclusive)
20646c287605SDavid Hildenbrand 				entry = make_readable_exclusive_migration_entry(
20656c287605SDavid Hildenbrand 							page_to_pfn(subpage));
2066a98a2f0cSAlistair Popple 			else
2067a98a2f0cSAlistair Popple 				entry = make_readable_migration_entry(
2068a98a2f0cSAlistair Popple 							page_to_pfn(subpage));
2069*2e346877SPeter Xu 			if (pte_young(pteval))
2070*2e346877SPeter Xu 				entry = make_migration_entry_young(entry);
2071*2e346877SPeter Xu 			if (pte_dirty(pteval))
2072*2e346877SPeter Xu 				entry = make_migration_entry_dirty(entry);
2073a98a2f0cSAlistair Popple 			swp_pte = swp_entry_to_pte(entry);
2074a98a2f0cSAlistair Popple 			if (pte_soft_dirty(pteval))
2075a98a2f0cSAlistair Popple 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
2076a98a2f0cSAlistair Popple 			if (pte_uffd_wp(pteval))
2077a98a2f0cSAlistair Popple 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
20785d4af619SBaolin Wang 			if (folio_test_hugetlb(folio))
207918f39629SQi Zheng 				set_huge_pte_at(mm, address, pvmw.pte, swp_pte);
20805d4af619SBaolin Wang 			else
2081a98a2f0cSAlistair Popple 				set_pte_at(mm, address, pvmw.pte, swp_pte);
20824cc79b33SAnshuman Khandual 			trace_set_migration_pte(address, pte_val(swp_pte),
20834cc79b33SAnshuman Khandual 						compound_order(&folio->page));
2084a98a2f0cSAlistair Popple 			/*
2085a98a2f0cSAlistair Popple 			 * No need to invalidate here it will synchronize on
2086a98a2f0cSAlistair Popple 			 * against the special swap migration pte.
2087a98a2f0cSAlistair Popple 			 */
2088a98a2f0cSAlistair Popple 		}
2089a98a2f0cSAlistair Popple 
2090a98a2f0cSAlistair Popple 		/*
2091a98a2f0cSAlistair Popple 		 * No need to call mmu_notifier_invalidate_range() it has be
2092a98a2f0cSAlistair Popple 		 * done above for all cases requiring it to happen under page
2093a98a2f0cSAlistair Popple 		 * table lock before mmu_notifier_invalidate_range_end()
2094a98a2f0cSAlistair Popple 		 *
2095ee65728eSMike Rapoport 		 * See Documentation/mm/mmu_notifier.rst
2096a98a2f0cSAlistair Popple 		 */
20974b8554c5SMatthew Wilcox (Oracle) 		page_remove_rmap(subpage, vma, folio_test_hugetlb(folio));
2098b7435507SHugh Dickins 		if (vma->vm_flags & VM_LOCKED)
2099adb11e78SSebastian Andrzej Siewior 			mlock_page_drain_local();
21004b8554c5SMatthew Wilcox (Oracle) 		folio_put(folio);
2101a98a2f0cSAlistair Popple 	}
2102a98a2f0cSAlistair Popple 
2103a98a2f0cSAlistair Popple 	mmu_notifier_invalidate_range_end(&range);
2104a98a2f0cSAlistair Popple 
2105a98a2f0cSAlistair Popple 	return ret;
2106a98a2f0cSAlistair Popple }
2107a98a2f0cSAlistair Popple 
2108a98a2f0cSAlistair Popple /**
2109a98a2f0cSAlistair Popple  * try_to_migrate - try to replace all page table mappings with swap entries
21104b8554c5SMatthew Wilcox (Oracle)  * @folio: the folio to replace page table entries for
2111a98a2f0cSAlistair Popple  * @flags: action and flags
2112a98a2f0cSAlistair Popple  *
21134b8554c5SMatthew Wilcox (Oracle)  * Tries to remove all the page table entries which are mapping this folio and
21144b8554c5SMatthew Wilcox (Oracle)  * replace them with special swap entries. Caller must hold the folio lock.
2115a98a2f0cSAlistair Popple  */
21164b8554c5SMatthew Wilcox (Oracle) void try_to_migrate(struct folio *folio, enum ttu_flags flags)
2117a98a2f0cSAlistair Popple {
2118a98a2f0cSAlistair Popple 	struct rmap_walk_control rwc = {
2119a98a2f0cSAlistair Popple 		.rmap_one = try_to_migrate_one,
2120a98a2f0cSAlistair Popple 		.arg = (void *)flags,
2121a98a2f0cSAlistair Popple 		.done = page_not_mapped,
21222f031c6fSMatthew Wilcox (Oracle) 		.anon_lock = folio_lock_anon_vma_read,
2123a98a2f0cSAlistair Popple 	};
2124a98a2f0cSAlistair Popple 
2125a98a2f0cSAlistair Popple 	/*
2126a98a2f0cSAlistair Popple 	 * Migration always ignores mlock and only supports TTU_RMAP_LOCKED and
2127a98a2f0cSAlistair Popple 	 * TTU_SPLIT_HUGE_PMD and TTU_SYNC flags.
2128a98a2f0cSAlistair Popple 	 */
2129a98a2f0cSAlistair Popple 	if (WARN_ON_ONCE(flags & ~(TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
2130a98a2f0cSAlistair Popple 					TTU_SYNC)))
2131a98a2f0cSAlistair Popple 		return;
2132a98a2f0cSAlistair Popple 
2133f25cbb7aSAlex Sierra 	if (folio_is_zone_device(folio) &&
2134f25cbb7aSAlex Sierra 	    (!folio_is_device_private(folio) && !folio_is_device_coherent(folio)))
21356c855fceSHugh Dickins 		return;
21366c855fceSHugh Dickins 
213752629506SJoonsoo Kim 	/*
213852629506SJoonsoo Kim 	 * During exec, a temporary VMA is setup and later moved.
213952629506SJoonsoo Kim 	 * The VMA is moved under the anon_vma lock but not the
214052629506SJoonsoo Kim 	 * page tables leading to a race where migration cannot
214152629506SJoonsoo Kim 	 * find the migration ptes. Rather than increasing the
214252629506SJoonsoo Kim 	 * locking requirements of exec(), migration skips
214352629506SJoonsoo Kim 	 * temporary VMAs until after exec() completes.
214452629506SJoonsoo Kim 	 */
21454b8554c5SMatthew Wilcox (Oracle) 	if (!folio_test_ksm(folio) && folio_test_anon(folio))
214652629506SJoonsoo Kim 		rwc.invalid_vma = invalid_migration_vma;
214752629506SJoonsoo Kim 
21482a52bcbcSKirill A. Shutemov 	if (flags & TTU_RMAP_LOCKED)
21492f031c6fSMatthew Wilcox (Oracle) 		rmap_walk_locked(folio, &rwc);
21502a52bcbcSKirill A. Shutemov 	else
21512f031c6fSMatthew Wilcox (Oracle) 		rmap_walk(folio, &rwc);
2152b291f000SNick Piggin }
2153e9995ef9SHugh Dickins 
2154b756a3b5SAlistair Popple #ifdef CONFIG_DEVICE_PRIVATE
2155b756a3b5SAlistair Popple struct make_exclusive_args {
2156b756a3b5SAlistair Popple 	struct mm_struct *mm;
2157b756a3b5SAlistair Popple 	unsigned long address;
2158b756a3b5SAlistair Popple 	void *owner;
2159b756a3b5SAlistair Popple 	bool valid;
2160b756a3b5SAlistair Popple };
2161b756a3b5SAlistair Popple 
21622f031c6fSMatthew Wilcox (Oracle) static bool page_make_device_exclusive_one(struct folio *folio,
2163b756a3b5SAlistair Popple 		struct vm_area_struct *vma, unsigned long address, void *priv)
2164b756a3b5SAlistair Popple {
2165b756a3b5SAlistair Popple 	struct mm_struct *mm = vma->vm_mm;
21660d251485SMatthew Wilcox (Oracle) 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
2167b756a3b5SAlistair Popple 	struct make_exclusive_args *args = priv;
2168b756a3b5SAlistair Popple 	pte_t pteval;
2169b756a3b5SAlistair Popple 	struct page *subpage;
2170b756a3b5SAlistair Popple 	bool ret = true;
2171b756a3b5SAlistair Popple 	struct mmu_notifier_range range;
2172b756a3b5SAlistair Popple 	swp_entry_t entry;
2173b756a3b5SAlistair Popple 	pte_t swp_pte;
2174b756a3b5SAlistair Popple 
2175b756a3b5SAlistair Popple 	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma,
2176b756a3b5SAlistair Popple 				      vma->vm_mm, address, min(vma->vm_end,
21770d251485SMatthew Wilcox (Oracle) 				      address + folio_size(folio)),
21780d251485SMatthew Wilcox (Oracle) 				      args->owner);
2179b756a3b5SAlistair Popple 	mmu_notifier_invalidate_range_start(&range);
2180b756a3b5SAlistair Popple 
2181b756a3b5SAlistair Popple 	while (page_vma_mapped_walk(&pvmw)) {
2182b756a3b5SAlistair Popple 		/* Unexpected PMD-mapped THP? */
21830d251485SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!pvmw.pte, folio);
2184b756a3b5SAlistair Popple 
2185b756a3b5SAlistair Popple 		if (!pte_present(*pvmw.pte)) {
2186b756a3b5SAlistair Popple 			ret = false;
2187b756a3b5SAlistair Popple 			page_vma_mapped_walk_done(&pvmw);
2188b756a3b5SAlistair Popple 			break;
2189b756a3b5SAlistair Popple 		}
2190b756a3b5SAlistair Popple 
21910d251485SMatthew Wilcox (Oracle) 		subpage = folio_page(folio,
21920d251485SMatthew Wilcox (Oracle) 				pte_pfn(*pvmw.pte) - folio_pfn(folio));
2193b756a3b5SAlistair Popple 		address = pvmw.address;
2194b756a3b5SAlistair Popple 
2195b756a3b5SAlistair Popple 		/* Nuke the page table entry. */
2196b756a3b5SAlistair Popple 		flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
2197b756a3b5SAlistair Popple 		pteval = ptep_clear_flush(vma, address, pvmw.pte);
2198b756a3b5SAlistair Popple 
21990d251485SMatthew Wilcox (Oracle) 		/* Set the dirty flag on the folio now the pte is gone. */
2200b756a3b5SAlistair Popple 		if (pte_dirty(pteval))
22010d251485SMatthew Wilcox (Oracle) 			folio_mark_dirty(folio);
2202b756a3b5SAlistair Popple 
2203b756a3b5SAlistair Popple 		/*
2204b756a3b5SAlistair Popple 		 * Check that our target page is still mapped at the expected
2205b756a3b5SAlistair Popple 		 * address.
2206b756a3b5SAlistair Popple 		 */
2207b756a3b5SAlistair Popple 		if (args->mm == mm && args->address == address &&
2208b756a3b5SAlistair Popple 		    pte_write(pteval))
2209b756a3b5SAlistair Popple 			args->valid = true;
2210b756a3b5SAlistair Popple 
2211b756a3b5SAlistair Popple 		/*
2212b756a3b5SAlistair Popple 		 * Store the pfn of the page in a special migration
2213b756a3b5SAlistair Popple 		 * pte. do_swap_page() will wait until the migration
2214b756a3b5SAlistair Popple 		 * pte is removed and then restart fault handling.
2215b756a3b5SAlistair Popple 		 */
2216b756a3b5SAlistair Popple 		if (pte_write(pteval))
2217b756a3b5SAlistair Popple 			entry = make_writable_device_exclusive_entry(
2218b756a3b5SAlistair Popple 							page_to_pfn(subpage));
2219b756a3b5SAlistair Popple 		else
2220b756a3b5SAlistair Popple 			entry = make_readable_device_exclusive_entry(
2221b756a3b5SAlistair Popple 							page_to_pfn(subpage));
2222b756a3b5SAlistair Popple 		swp_pte = swp_entry_to_pte(entry);
2223b756a3b5SAlistair Popple 		if (pte_soft_dirty(pteval))
2224b756a3b5SAlistair Popple 			swp_pte = pte_swp_mksoft_dirty(swp_pte);
2225b756a3b5SAlistair Popple 		if (pte_uffd_wp(pteval))
2226b756a3b5SAlistair Popple 			swp_pte = pte_swp_mkuffd_wp(swp_pte);
2227b756a3b5SAlistair Popple 
2228b756a3b5SAlistair Popple 		set_pte_at(mm, address, pvmw.pte, swp_pte);
2229b756a3b5SAlistair Popple 
2230b756a3b5SAlistair Popple 		/*
2231b756a3b5SAlistair Popple 		 * There is a reference on the page for the swap entry which has
2232b756a3b5SAlistair Popple 		 * been removed, so shouldn't take another.
2233b756a3b5SAlistair Popple 		 */
2234cea86fe2SHugh Dickins 		page_remove_rmap(subpage, vma, false);
2235b756a3b5SAlistair Popple 	}
2236b756a3b5SAlistair Popple 
2237b756a3b5SAlistair Popple 	mmu_notifier_invalidate_range_end(&range);
2238b756a3b5SAlistair Popple 
2239b756a3b5SAlistair Popple 	return ret;
2240b756a3b5SAlistair Popple }
2241b756a3b5SAlistair Popple 
2242b756a3b5SAlistair Popple /**
22430d251485SMatthew Wilcox (Oracle)  * folio_make_device_exclusive - Mark the folio exclusively owned by a device.
22440d251485SMatthew Wilcox (Oracle)  * @folio: The folio to replace page table entries for.
22450d251485SMatthew Wilcox (Oracle)  * @mm: The mm_struct where the folio is expected to be mapped.
22460d251485SMatthew Wilcox (Oracle)  * @address: Address where the folio is expected to be mapped.
2247b756a3b5SAlistair Popple  * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier callbacks
2248b756a3b5SAlistair Popple  *
22490d251485SMatthew Wilcox (Oracle)  * Tries to remove all the page table entries which are mapping this
22500d251485SMatthew Wilcox (Oracle)  * folio and replace them with special device exclusive swap entries to
22510d251485SMatthew Wilcox (Oracle)  * grant a device exclusive access to the folio.
2252b756a3b5SAlistair Popple  *
22530d251485SMatthew Wilcox (Oracle)  * Context: Caller must hold the folio lock.
22540d251485SMatthew Wilcox (Oracle)  * Return: false if the page is still mapped, or if it could not be unmapped
2255b756a3b5SAlistair Popple  * from the expected address. Otherwise returns true (success).
2256b756a3b5SAlistair Popple  */
22570d251485SMatthew Wilcox (Oracle) static bool folio_make_device_exclusive(struct folio *folio,
22580d251485SMatthew Wilcox (Oracle) 		struct mm_struct *mm, unsigned long address, void *owner)
2259b756a3b5SAlistair Popple {
2260b756a3b5SAlistair Popple 	struct make_exclusive_args args = {
2261b756a3b5SAlistair Popple 		.mm = mm,
2262b756a3b5SAlistair Popple 		.address = address,
2263b756a3b5SAlistair Popple 		.owner = owner,
2264b756a3b5SAlistair Popple 		.valid = false,
2265b756a3b5SAlistair Popple 	};
2266b756a3b5SAlistair Popple 	struct rmap_walk_control rwc = {
2267b756a3b5SAlistair Popple 		.rmap_one = page_make_device_exclusive_one,
2268b756a3b5SAlistair Popple 		.done = page_not_mapped,
22692f031c6fSMatthew Wilcox (Oracle) 		.anon_lock = folio_lock_anon_vma_read,
2270b756a3b5SAlistair Popple 		.arg = &args,
2271b756a3b5SAlistair Popple 	};
2272b756a3b5SAlistair Popple 
2273b756a3b5SAlistair Popple 	/*
22740d251485SMatthew Wilcox (Oracle) 	 * Restrict to anonymous folios for now to avoid potential writeback
22750d251485SMatthew Wilcox (Oracle) 	 * issues.
2276b756a3b5SAlistair Popple 	 */
22770d251485SMatthew Wilcox (Oracle) 	if (!folio_test_anon(folio))
2278b756a3b5SAlistair Popple 		return false;
2279b756a3b5SAlistair Popple 
22802f031c6fSMatthew Wilcox (Oracle) 	rmap_walk(folio, &rwc);
2281b756a3b5SAlistair Popple 
22820d251485SMatthew Wilcox (Oracle) 	return args.valid && !folio_mapcount(folio);
2283b756a3b5SAlistair Popple }
2284b756a3b5SAlistair Popple 
2285b756a3b5SAlistair Popple /**
2286b756a3b5SAlistair Popple  * make_device_exclusive_range() - Mark a range for exclusive use by a device
2287dd062302SAdrian Huang  * @mm: mm_struct of associated target process
2288b756a3b5SAlistair Popple  * @start: start of the region to mark for exclusive device access
2289b756a3b5SAlistair Popple  * @end: end address of region
2290b756a3b5SAlistair Popple  * @pages: returns the pages which were successfully marked for exclusive access
2291b756a3b5SAlistair Popple  * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
2292b756a3b5SAlistair Popple  *
2293b756a3b5SAlistair Popple  * Returns: number of pages found in the range by GUP. A page is marked for
2294b756a3b5SAlistair Popple  * exclusive access only if the page pointer is non-NULL.
2295b756a3b5SAlistair Popple  *
2296b756a3b5SAlistair Popple  * This function finds ptes mapping page(s) to the given address range, locks
2297b756a3b5SAlistair Popple  * them and replaces mappings with special swap entries preventing userspace CPU
2298b756a3b5SAlistair Popple  * access. On fault these entries are replaced with the original mapping after
2299b756a3b5SAlistair Popple  * calling MMU notifiers.
2300b756a3b5SAlistair Popple  *
2301b756a3b5SAlistair Popple  * A driver using this to program access from a device must use a mmu notifier
2302b756a3b5SAlistair Popple  * critical section to hold a device specific lock during programming. Once
2303b756a3b5SAlistair Popple  * programming is complete it should drop the page lock and reference after
2304b756a3b5SAlistair Popple  * which point CPU access to the page will revoke the exclusive access.
2305b756a3b5SAlistair Popple  */
2306b756a3b5SAlistair Popple int make_device_exclusive_range(struct mm_struct *mm, unsigned long start,
2307b756a3b5SAlistair Popple 				unsigned long end, struct page **pages,
2308b756a3b5SAlistair Popple 				void *owner)
2309b756a3b5SAlistair Popple {
2310b756a3b5SAlistair Popple 	long npages = (end - start) >> PAGE_SHIFT;
2311b756a3b5SAlistair Popple 	long i;
2312b756a3b5SAlistair Popple 
2313b756a3b5SAlistair Popple 	npages = get_user_pages_remote(mm, start, npages,
2314b756a3b5SAlistair Popple 				       FOLL_GET | FOLL_WRITE | FOLL_SPLIT_PMD,
2315b756a3b5SAlistair Popple 				       pages, NULL, NULL);
2316b756a3b5SAlistair Popple 	if (npages < 0)
2317b756a3b5SAlistair Popple 		return npages;
2318b756a3b5SAlistair Popple 
2319b756a3b5SAlistair Popple 	for (i = 0; i < npages; i++, start += PAGE_SIZE) {
23200d251485SMatthew Wilcox (Oracle) 		struct folio *folio = page_folio(pages[i]);
23210d251485SMatthew Wilcox (Oracle) 		if (PageTail(pages[i]) || !folio_trylock(folio)) {
23220d251485SMatthew Wilcox (Oracle) 			folio_put(folio);
2323b756a3b5SAlistair Popple 			pages[i] = NULL;
2324b756a3b5SAlistair Popple 			continue;
2325b756a3b5SAlistair Popple 		}
2326b756a3b5SAlistair Popple 
23270d251485SMatthew Wilcox (Oracle) 		if (!folio_make_device_exclusive(folio, mm, start, owner)) {
23280d251485SMatthew Wilcox (Oracle) 			folio_unlock(folio);
23290d251485SMatthew Wilcox (Oracle) 			folio_put(folio);
2330b756a3b5SAlistair Popple 			pages[i] = NULL;
2331b756a3b5SAlistair Popple 		}
2332b756a3b5SAlistair Popple 	}
2333b756a3b5SAlistair Popple 
2334b756a3b5SAlistair Popple 	return npages;
2335b756a3b5SAlistair Popple }
2336b756a3b5SAlistair Popple EXPORT_SYMBOL_GPL(make_device_exclusive_range);
2337b756a3b5SAlistair Popple #endif
2338b756a3b5SAlistair Popple 
233901d8b20dSPeter Zijlstra void __put_anon_vma(struct anon_vma *anon_vma)
234076545066SRik van Riel {
234176545066SRik van Riel 	struct anon_vma *root = anon_vma->root;
234276545066SRik van Riel 
2343624483f3SAndrey Ryabinin 	anon_vma_free(anon_vma);
234401d8b20dSPeter Zijlstra 	if (root != anon_vma && atomic_dec_and_test(&root->refcount))
234576545066SRik van Riel 		anon_vma_free(root);
234676545066SRik van Riel }
234776545066SRik van Riel 
23482f031c6fSMatthew Wilcox (Oracle) static struct anon_vma *rmap_walk_anon_lock(struct folio *folio,
23496d4675e6SMinchan Kim 					    struct rmap_walk_control *rwc)
2350faecd8ddSJoonsoo Kim {
2351faecd8ddSJoonsoo Kim 	struct anon_vma *anon_vma;
2352faecd8ddSJoonsoo Kim 
23530dd1c7bbSJoonsoo Kim 	if (rwc->anon_lock)
23546d4675e6SMinchan Kim 		return rwc->anon_lock(folio, rwc);
23550dd1c7bbSJoonsoo Kim 
2356faecd8ddSJoonsoo Kim 	/*
23572f031c6fSMatthew Wilcox (Oracle) 	 * Note: remove_migration_ptes() cannot use folio_lock_anon_vma_read()
2358faecd8ddSJoonsoo Kim 	 * because that depends on page_mapped(); but not all its usages
2359c1e8d7c6SMichel Lespinasse 	 * are holding mmap_lock. Users without mmap_lock are required to
2360faecd8ddSJoonsoo Kim 	 * take a reference count to prevent the anon_vma disappearing
2361faecd8ddSJoonsoo Kim 	 */
2362e05b3453SMatthew Wilcox (Oracle) 	anon_vma = folio_anon_vma(folio);
2363faecd8ddSJoonsoo Kim 	if (!anon_vma)
2364faecd8ddSJoonsoo Kim 		return NULL;
2365faecd8ddSJoonsoo Kim 
23666d4675e6SMinchan Kim 	if (anon_vma_trylock_read(anon_vma))
23676d4675e6SMinchan Kim 		goto out;
23686d4675e6SMinchan Kim 
23696d4675e6SMinchan Kim 	if (rwc->try_lock) {
23706d4675e6SMinchan Kim 		anon_vma = NULL;
23716d4675e6SMinchan Kim 		rwc->contended = true;
23726d4675e6SMinchan Kim 		goto out;
23736d4675e6SMinchan Kim 	}
23746d4675e6SMinchan Kim 
2375faecd8ddSJoonsoo Kim 	anon_vma_lock_read(anon_vma);
23766d4675e6SMinchan Kim out:
2377faecd8ddSJoonsoo Kim 	return anon_vma;
2378faecd8ddSJoonsoo Kim }
2379faecd8ddSJoonsoo Kim 
2380e9995ef9SHugh Dickins /*
2381e8351ac9SJoonsoo Kim  * rmap_walk_anon - do something to anonymous page using the object-based
2382e8351ac9SJoonsoo Kim  * rmap method
2383e8351ac9SJoonsoo Kim  * @page: the page to be handled
2384e8351ac9SJoonsoo Kim  * @rwc: control variable according to each walk type
2385e8351ac9SJoonsoo Kim  *
2386e8351ac9SJoonsoo Kim  * Find all the mappings of a page using the mapping pointer and the vma chains
2387e8351ac9SJoonsoo Kim  * contained in the anon_vma struct it points to.
2388e9995ef9SHugh Dickins  */
238984fbbe21SMatthew Wilcox (Oracle) static void rmap_walk_anon(struct folio *folio,
23906d4675e6SMinchan Kim 		struct rmap_walk_control *rwc, bool locked)
2391e9995ef9SHugh Dickins {
2392e9995ef9SHugh Dickins 	struct anon_vma *anon_vma;
2393a8fa41adSKirill A. Shutemov 	pgoff_t pgoff_start, pgoff_end;
23945beb4930SRik van Riel 	struct anon_vma_chain *avc;
2395e9995ef9SHugh Dickins 
2396b9773199SKirill A. Shutemov 	if (locked) {
2397e05b3453SMatthew Wilcox (Oracle) 		anon_vma = folio_anon_vma(folio);
2398b9773199SKirill A. Shutemov 		/* anon_vma disappear under us? */
2399e05b3453SMatthew Wilcox (Oracle) 		VM_BUG_ON_FOLIO(!anon_vma, folio);
2400b9773199SKirill A. Shutemov 	} else {
24012f031c6fSMatthew Wilcox (Oracle) 		anon_vma = rmap_walk_anon_lock(folio, rwc);
2402b9773199SKirill A. Shutemov 	}
2403e9995ef9SHugh Dickins 	if (!anon_vma)
24041df631aeSMinchan Kim 		return;
2405faecd8ddSJoonsoo Kim 
24062f031c6fSMatthew Wilcox (Oracle) 	pgoff_start = folio_pgoff(folio);
24072f031c6fSMatthew Wilcox (Oracle) 	pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
2408a8fa41adSKirill A. Shutemov 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
2409a8fa41adSKirill A. Shutemov 			pgoff_start, pgoff_end) {
24105beb4930SRik van Riel 		struct vm_area_struct *vma = avc->vma;
24112f031c6fSMatthew Wilcox (Oracle) 		unsigned long address = vma_address(&folio->page, vma);
24120dd1c7bbSJoonsoo Kim 
2413494334e4SHugh Dickins 		VM_BUG_ON_VMA(address == -EFAULT, vma);
2414ad12695fSAndrea Arcangeli 		cond_resched();
2415ad12695fSAndrea Arcangeli 
24160dd1c7bbSJoonsoo Kim 		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
24170dd1c7bbSJoonsoo Kim 			continue;
24180dd1c7bbSJoonsoo Kim 
24192f031c6fSMatthew Wilcox (Oracle) 		if (!rwc->rmap_one(folio, vma, address, rwc->arg))
2420e9995ef9SHugh Dickins 			break;
24212f031c6fSMatthew Wilcox (Oracle) 		if (rwc->done && rwc->done(folio))
24220dd1c7bbSJoonsoo Kim 			break;
2423e9995ef9SHugh Dickins 	}
2424b9773199SKirill A. Shutemov 
2425b9773199SKirill A. Shutemov 	if (!locked)
24264fc3f1d6SIngo Molnar 		anon_vma_unlock_read(anon_vma);
2427e9995ef9SHugh Dickins }
2428e9995ef9SHugh Dickins 
2429e8351ac9SJoonsoo Kim /*
2430e8351ac9SJoonsoo Kim  * rmap_walk_file - do something to file page using the object-based rmap method
2431e8351ac9SJoonsoo Kim  * @page: the page to be handled
2432e8351ac9SJoonsoo Kim  * @rwc: control variable according to each walk type
2433e8351ac9SJoonsoo Kim  *
2434e8351ac9SJoonsoo Kim  * Find all the mappings of a page using the mapping pointer and the vma chains
2435e8351ac9SJoonsoo Kim  * contained in the address_space struct it points to.
2436e8351ac9SJoonsoo Kim  */
243784fbbe21SMatthew Wilcox (Oracle) static void rmap_walk_file(struct folio *folio,
24386d4675e6SMinchan Kim 		struct rmap_walk_control *rwc, bool locked)
2439e9995ef9SHugh Dickins {
24402f031c6fSMatthew Wilcox (Oracle) 	struct address_space *mapping = folio_mapping(folio);
2441a8fa41adSKirill A. Shutemov 	pgoff_t pgoff_start, pgoff_end;
2442e9995ef9SHugh Dickins 	struct vm_area_struct *vma;
2443e9995ef9SHugh Dickins 
24449f32624bSJoonsoo Kim 	/*
24459f32624bSJoonsoo Kim 	 * The page lock not only makes sure that page->mapping cannot
24469f32624bSJoonsoo Kim 	 * suddenly be NULLified by truncation, it makes sure that the
24479f32624bSJoonsoo Kim 	 * structure at mapping cannot be freed and reused yet,
2448c8c06efaSDavidlohr Bueso 	 * so we can safely take mapping->i_mmap_rwsem.
24499f32624bSJoonsoo Kim 	 */
24502f031c6fSMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
24519f32624bSJoonsoo Kim 
2452e9995ef9SHugh Dickins 	if (!mapping)
24531df631aeSMinchan Kim 		return;
24543dec0ba0SDavidlohr Bueso 
24552f031c6fSMatthew Wilcox (Oracle) 	pgoff_start = folio_pgoff(folio);
24562f031c6fSMatthew Wilcox (Oracle) 	pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
24576d4675e6SMinchan Kim 	if (!locked) {
24586d4675e6SMinchan Kim 		if (i_mmap_trylock_read(mapping))
24596d4675e6SMinchan Kim 			goto lookup;
24606d4675e6SMinchan Kim 
24616d4675e6SMinchan Kim 		if (rwc->try_lock) {
24626d4675e6SMinchan Kim 			rwc->contended = true;
24636d4675e6SMinchan Kim 			return;
24646d4675e6SMinchan Kim 		}
24656d4675e6SMinchan Kim 
24663dec0ba0SDavidlohr Bueso 		i_mmap_lock_read(mapping);
24676d4675e6SMinchan Kim 	}
24686d4675e6SMinchan Kim lookup:
2469a8fa41adSKirill A. Shutemov 	vma_interval_tree_foreach(vma, &mapping->i_mmap,
2470a8fa41adSKirill A. Shutemov 			pgoff_start, pgoff_end) {
24712f031c6fSMatthew Wilcox (Oracle) 		unsigned long address = vma_address(&folio->page, vma);
24720dd1c7bbSJoonsoo Kim 
2473494334e4SHugh Dickins 		VM_BUG_ON_VMA(address == -EFAULT, vma);
2474ad12695fSAndrea Arcangeli 		cond_resched();
2475ad12695fSAndrea Arcangeli 
24760dd1c7bbSJoonsoo Kim 		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
24770dd1c7bbSJoonsoo Kim 			continue;
24780dd1c7bbSJoonsoo Kim 
24792f031c6fSMatthew Wilcox (Oracle) 		if (!rwc->rmap_one(folio, vma, address, rwc->arg))
24800dd1c7bbSJoonsoo Kim 			goto done;
24812f031c6fSMatthew Wilcox (Oracle) 		if (rwc->done && rwc->done(folio))
24820dd1c7bbSJoonsoo Kim 			goto done;
2483e9995ef9SHugh Dickins 	}
24840dd1c7bbSJoonsoo Kim 
24850dd1c7bbSJoonsoo Kim done:
2486b9773199SKirill A. Shutemov 	if (!locked)
24873dec0ba0SDavidlohr Bueso 		i_mmap_unlock_read(mapping);
2488e9995ef9SHugh Dickins }
2489e9995ef9SHugh Dickins 
24906d4675e6SMinchan Kim void rmap_walk(struct folio *folio, struct rmap_walk_control *rwc)
2491e9995ef9SHugh Dickins {
24922f031c6fSMatthew Wilcox (Oracle) 	if (unlikely(folio_test_ksm(folio)))
24932f031c6fSMatthew Wilcox (Oracle) 		rmap_walk_ksm(folio, rwc);
24942f031c6fSMatthew Wilcox (Oracle) 	else if (folio_test_anon(folio))
24952f031c6fSMatthew Wilcox (Oracle) 		rmap_walk_anon(folio, rwc, false);
2496e9995ef9SHugh Dickins 	else
24972f031c6fSMatthew Wilcox (Oracle) 		rmap_walk_file(folio, rwc, false);
2498b9773199SKirill A. Shutemov }
2499b9773199SKirill A. Shutemov 
2500b9773199SKirill A. Shutemov /* Like rmap_walk, but caller holds relevant rmap lock */
25016d4675e6SMinchan Kim void rmap_walk_locked(struct folio *folio, struct rmap_walk_control *rwc)
2502b9773199SKirill A. Shutemov {
2503b9773199SKirill A. Shutemov 	/* no ksm support for now */
25042f031c6fSMatthew Wilcox (Oracle) 	VM_BUG_ON_FOLIO(folio_test_ksm(folio), folio);
25052f031c6fSMatthew Wilcox (Oracle) 	if (folio_test_anon(folio))
25062f031c6fSMatthew Wilcox (Oracle) 		rmap_walk_anon(folio, rwc, true);
2507b9773199SKirill A. Shutemov 	else
25082f031c6fSMatthew Wilcox (Oracle) 		rmap_walk_file(folio, rwc, true);
2509e9995ef9SHugh Dickins }
25100fe6e20bSNaoya Horiguchi 
2511e3390f67SNaoya Horiguchi #ifdef CONFIG_HUGETLB_PAGE
25120fe6e20bSNaoya Horiguchi /*
2513451b9514SKirill Tkhai  * The following two functions are for anonymous (private mapped) hugepages.
25140fe6e20bSNaoya Horiguchi  * Unlike common anonymous pages, anonymous hugepages have no accounting code
25150fe6e20bSNaoya Horiguchi  * and no lru code, because we handle hugepages differently from common pages.
251628c5209dSDavid Hildenbrand  *
251728c5209dSDavid Hildenbrand  * RMAP_COMPOUND is ignored.
25180fe6e20bSNaoya Horiguchi  */
251928c5209dSDavid Hildenbrand void hugepage_add_anon_rmap(struct page *page, struct vm_area_struct *vma,
252028c5209dSDavid Hildenbrand 			    unsigned long address, rmap_t flags)
25210fe6e20bSNaoya Horiguchi {
25220fe6e20bSNaoya Horiguchi 	struct anon_vma *anon_vma = vma->anon_vma;
25230fe6e20bSNaoya Horiguchi 	int first;
2524a850ea30SNaoya Horiguchi 
2525a850ea30SNaoya Horiguchi 	BUG_ON(!PageLocked(page));
25260fe6e20bSNaoya Horiguchi 	BUG_ON(!anon_vma);
25275dbe0af4SHugh Dickins 	/* address might be in next vma when migration races vma_adjust */
252853f9263bSKirill A. Shutemov 	first = atomic_inc_and_test(compound_mapcount_ptr(page));
25296c287605SDavid Hildenbrand 	VM_BUG_ON_PAGE(!first && (flags & RMAP_EXCLUSIVE), page);
25306c287605SDavid Hildenbrand 	VM_BUG_ON_PAGE(!first && PageAnonExclusive(page), page);
25310fe6e20bSNaoya Horiguchi 	if (first)
253228c5209dSDavid Hildenbrand 		__page_set_anon_rmap(page, vma, address,
253328c5209dSDavid Hildenbrand 				     !!(flags & RMAP_EXCLUSIVE));
25340fe6e20bSNaoya Horiguchi }
25350fe6e20bSNaoya Horiguchi 
25360fe6e20bSNaoya Horiguchi void hugepage_add_new_anon_rmap(struct page *page,
25370fe6e20bSNaoya Horiguchi 			struct vm_area_struct *vma, unsigned long address)
25380fe6e20bSNaoya Horiguchi {
25390fe6e20bSNaoya Horiguchi 	BUG_ON(address < vma->vm_start || address >= vma->vm_end);
254053f9263bSKirill A. Shutemov 	atomic_set(compound_mapcount_ptr(page), 0);
254147e29d32SJohn Hubbard 	atomic_set(compound_pincount_ptr(page), 0);
254247e29d32SJohn Hubbard 
2543451b9514SKirill Tkhai 	__page_set_anon_rmap(page, vma, address, 1);
25440fe6e20bSNaoya Horiguchi }
2545e3390f67SNaoya Horiguchi #endif /* CONFIG_HUGETLB_PAGE */
2546