xref: /linux/mm/rmap.c (revision 90aaca852ca13a6c962b25964fb6678120f266b1)
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  *
231b1dcc1bSJes Sorensen  * inode->i_mutex	(while writing or truncating, not reading or faulting)
24c1e8d7c6SMichel Lespinasse  *   mm->mmap_lock
25c0d0381aSMike Kravetz  *     page->flags PG_locked (lock_page)   * (see huegtlbfs below)
2688f306b6SKirill A. Shutemov  *       hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share)
27c8c06efaSDavidlohr Bueso  *         mapping->i_mmap_rwsem
28c0d0381aSMike Kravetz  *           hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
295a505085SIngo Molnar  *           anon_vma->rwsem
30b8072f09SHugh Dickins  *             mm->page_table_lock or pte_lock
315d337b91SHugh Dickins  *               swap_lock (in swap_duplicate, swap_info_get)
321da177e4SLinus Torvalds  *                 mmlist_lock (in mmput, drain_mmlist and others)
331da177e4SLinus Torvalds  *                 mapping->private_lock (in __set_page_dirty_buffers)
3415b44736SHugh Dickins  *                   lock_page_memcg move_lock (in __set_page_dirty_buffers)
35b93b0163SMatthew Wilcox  *                     i_pages lock (widely used)
3615b44736SHugh Dickins  *                       lruvec->lru_lock (in lock_page_lruvec_irq)
37250df6edSDave Chinner  *                 inode->i_lock (in set_page_dirty's __mark_inode_dirty)
38f758eeabSChristoph Hellwig  *                 bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
391da177e4SLinus Torvalds  *                   sb_lock (within inode_lock in fs/fs-writeback.c)
40b93b0163SMatthew Wilcox  *                   i_pages lock (widely used, in set_page_dirty,
411da177e4SLinus Torvalds  *                             in arch-dependent flush_dcache_mmap_lock,
42f758eeabSChristoph Hellwig  *                             within bdi.wb->list_lock in __sync_single_inode)
436a46079cSAndi Kleen  *
445a505085SIngo Molnar  * anon_vma->rwsem,mapping->i_mutex      (memory_failure, collect_procs_anon)
456a46079cSAndi Kleen  *   ->tasklist_lock
466a46079cSAndi Kleen  *     pte map lock
47c0d0381aSMike Kravetz  *
48c0d0381aSMike Kravetz  * * hugetlbfs PageHuge() pages take locks in this order:
49c0d0381aSMike Kravetz  *         mapping->i_mmap_rwsem
50c0d0381aSMike Kravetz  *           hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
51c0d0381aSMike Kravetz  *             page->flags PG_locked (lock_page)
521da177e4SLinus Torvalds  */
531da177e4SLinus Torvalds 
541da177e4SLinus Torvalds #include <linux/mm.h>
556e84f315SIngo Molnar #include <linux/sched/mm.h>
5629930025SIngo Molnar #include <linux/sched/task.h>
571da177e4SLinus Torvalds #include <linux/pagemap.h>
581da177e4SLinus Torvalds #include <linux/swap.h>
591da177e4SLinus Torvalds #include <linux/swapops.h>
601da177e4SLinus Torvalds #include <linux/slab.h>
611da177e4SLinus Torvalds #include <linux/init.h>
625ad64688SHugh Dickins #include <linux/ksm.h>
631da177e4SLinus Torvalds #include <linux/rmap.h>
641da177e4SLinus Torvalds #include <linux/rcupdate.h>
65b95f1b31SPaul Gortmaker #include <linux/export.h>
668a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
67cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
6864cdd548SKOSAKI Motohiro #include <linux/migrate.h>
690fe6e20bSNaoya Horiguchi #include <linux/hugetlb.h>
70444f84fdSBen Dooks #include <linux/huge_mm.h>
71ef5d437fSJan Kara #include <linux/backing-dev.h>
7233c3fc71SVladimir Davydov #include <linux/page_idle.h>
73a5430ddaSJérôme Glisse #include <linux/memremap.h>
74bce73e48SChristian Borntraeger #include <linux/userfaultfd_k.h>
751da177e4SLinus Torvalds 
761da177e4SLinus Torvalds #include <asm/tlbflush.h>
771da177e4SLinus Torvalds 
7872b252aeSMel Gorman #include <trace/events/tlb.h>
7972b252aeSMel Gorman 
80b291f000SNick Piggin #include "internal.h"
81b291f000SNick Piggin 
82fdd2e5f8SAdrian Bunk static struct kmem_cache *anon_vma_cachep;
835beb4930SRik van Riel static struct kmem_cache *anon_vma_chain_cachep;
84fdd2e5f8SAdrian Bunk 
85fdd2e5f8SAdrian Bunk static inline struct anon_vma *anon_vma_alloc(void)
86fdd2e5f8SAdrian Bunk {
8701d8b20dSPeter Zijlstra 	struct anon_vma *anon_vma;
8801d8b20dSPeter Zijlstra 
8901d8b20dSPeter Zijlstra 	anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
9001d8b20dSPeter Zijlstra 	if (anon_vma) {
9101d8b20dSPeter Zijlstra 		atomic_set(&anon_vma->refcount, 1);
927a3ef208SKonstantin Khlebnikov 		anon_vma->degree = 1;	/* Reference for first vma */
937a3ef208SKonstantin Khlebnikov 		anon_vma->parent = anon_vma;
9401d8b20dSPeter Zijlstra 		/*
9501d8b20dSPeter Zijlstra 		 * Initialise the anon_vma root to point to itself. If called
9601d8b20dSPeter Zijlstra 		 * from fork, the root will be reset to the parents anon_vma.
9701d8b20dSPeter Zijlstra 		 */
9801d8b20dSPeter Zijlstra 		anon_vma->root = anon_vma;
99fdd2e5f8SAdrian Bunk 	}
100fdd2e5f8SAdrian Bunk 
10101d8b20dSPeter Zijlstra 	return anon_vma;
10201d8b20dSPeter Zijlstra }
10301d8b20dSPeter Zijlstra 
10401d8b20dSPeter Zijlstra static inline void anon_vma_free(struct anon_vma *anon_vma)
105fdd2e5f8SAdrian Bunk {
10601d8b20dSPeter Zijlstra 	VM_BUG_ON(atomic_read(&anon_vma->refcount));
10788c22088SPeter Zijlstra 
10888c22088SPeter Zijlstra 	/*
1094fc3f1d6SIngo Molnar 	 * Synchronize against page_lock_anon_vma_read() such that
11088c22088SPeter Zijlstra 	 * we can safely hold the lock without the anon_vma getting
11188c22088SPeter Zijlstra 	 * freed.
11288c22088SPeter Zijlstra 	 *
11388c22088SPeter Zijlstra 	 * Relies on the full mb implied by the atomic_dec_and_test() from
11488c22088SPeter Zijlstra 	 * put_anon_vma() against the acquire barrier implied by
1154fc3f1d6SIngo Molnar 	 * down_read_trylock() from page_lock_anon_vma_read(). This orders:
11688c22088SPeter Zijlstra 	 *
1174fc3f1d6SIngo Molnar 	 * page_lock_anon_vma_read()	VS	put_anon_vma()
1184fc3f1d6SIngo Molnar 	 *   down_read_trylock()		  atomic_dec_and_test()
11988c22088SPeter Zijlstra 	 *   LOCK				  MB
1204fc3f1d6SIngo Molnar 	 *   atomic_read()			  rwsem_is_locked()
12188c22088SPeter Zijlstra 	 *
12288c22088SPeter Zijlstra 	 * LOCK should suffice since the actual taking of the lock must
12388c22088SPeter Zijlstra 	 * happen _before_ what follows.
12488c22088SPeter Zijlstra 	 */
1257f39dda9SHugh Dickins 	might_sleep();
1265a505085SIngo Molnar 	if (rwsem_is_locked(&anon_vma->root->rwsem)) {
1274fc3f1d6SIngo Molnar 		anon_vma_lock_write(anon_vma);
12808b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
12988c22088SPeter Zijlstra 	}
13088c22088SPeter Zijlstra 
131fdd2e5f8SAdrian Bunk 	kmem_cache_free(anon_vma_cachep, anon_vma);
132fdd2e5f8SAdrian Bunk }
1331da177e4SLinus Torvalds 
134dd34739cSLinus Torvalds static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
1355beb4930SRik van Riel {
136dd34739cSLinus Torvalds 	return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
1375beb4930SRik van Riel }
1385beb4930SRik van Riel 
139e574b5fdSNamhyung Kim static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
1405beb4930SRik van Riel {
1415beb4930SRik van Riel 	kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
1425beb4930SRik van Riel }
1435beb4930SRik van Riel 
1446583a843SKautuk Consul static void anon_vma_chain_link(struct vm_area_struct *vma,
1456583a843SKautuk Consul 				struct anon_vma_chain *avc,
1466583a843SKautuk Consul 				struct anon_vma *anon_vma)
1476583a843SKautuk Consul {
1486583a843SKautuk Consul 	avc->vma = vma;
1496583a843SKautuk Consul 	avc->anon_vma = anon_vma;
1506583a843SKautuk Consul 	list_add(&avc->same_vma, &vma->anon_vma_chain);
151bf181b9fSMichel Lespinasse 	anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
1526583a843SKautuk Consul }
1536583a843SKautuk Consul 
154d9d332e0SLinus Torvalds /**
155d5a187daSVlastimil Babka  * __anon_vma_prepare - attach an anon_vma to a memory region
156d9d332e0SLinus Torvalds  * @vma: the memory region in question
157d9d332e0SLinus Torvalds  *
158d9d332e0SLinus Torvalds  * This makes sure the memory mapping described by 'vma' has
159d9d332e0SLinus Torvalds  * an 'anon_vma' attached to it, so that we can associate the
160d9d332e0SLinus Torvalds  * anonymous pages mapped into it with that anon_vma.
161d9d332e0SLinus Torvalds  *
162d5a187daSVlastimil Babka  * The common case will be that we already have one, which
163d5a187daSVlastimil Babka  * is handled inline by anon_vma_prepare(). But if
16423a0790aSFigo.zhang  * not we either need to find an adjacent mapping that we
165d9d332e0SLinus Torvalds  * can re-use the anon_vma from (very common when the only
166d9d332e0SLinus Torvalds  * reason for splitting a vma has been mprotect()), or we
167d9d332e0SLinus Torvalds  * allocate a new one.
168d9d332e0SLinus Torvalds  *
169d9d332e0SLinus Torvalds  * Anon-vma allocations are very subtle, because we may have
1704fc3f1d6SIngo Molnar  * optimistically looked up an anon_vma in page_lock_anon_vma_read()
171aaf1f990SMiaohe Lin  * and that may actually touch the rwsem even in the newly
172d9d332e0SLinus Torvalds  * allocated vma (it depends on RCU to make sure that the
173d9d332e0SLinus Torvalds  * anon_vma isn't actually destroyed).
174d9d332e0SLinus Torvalds  *
175d9d332e0SLinus Torvalds  * As a result, we need to do proper anon_vma locking even
176d9d332e0SLinus Torvalds  * for the new allocation. At the same time, we do not want
177d9d332e0SLinus Torvalds  * to do any locking for the common case of already having
178d9d332e0SLinus Torvalds  * an anon_vma.
179d9d332e0SLinus Torvalds  *
180c1e8d7c6SMichel Lespinasse  * This must be called with the mmap_lock held for reading.
181d9d332e0SLinus Torvalds  */
182d5a187daSVlastimil Babka int __anon_vma_prepare(struct vm_area_struct *vma)
1831da177e4SLinus Torvalds {
184d5a187daSVlastimil Babka 	struct mm_struct *mm = vma->vm_mm;
185d5a187daSVlastimil Babka 	struct anon_vma *anon_vma, *allocated;
1865beb4930SRik van Riel 	struct anon_vma_chain *avc;
1871da177e4SLinus Torvalds 
1881da177e4SLinus Torvalds 	might_sleep();
1891da177e4SLinus Torvalds 
190dd34739cSLinus Torvalds 	avc = anon_vma_chain_alloc(GFP_KERNEL);
1915beb4930SRik van Riel 	if (!avc)
1925beb4930SRik van Riel 		goto out_enomem;
1935beb4930SRik van Riel 
1941da177e4SLinus Torvalds 	anon_vma = find_mergeable_anon_vma(vma);
1951da177e4SLinus Torvalds 	allocated = NULL;
196d9d332e0SLinus Torvalds 	if (!anon_vma) {
1971da177e4SLinus Torvalds 		anon_vma = anon_vma_alloc();
1981da177e4SLinus Torvalds 		if (unlikely(!anon_vma))
1995beb4930SRik van Riel 			goto out_enomem_free_avc;
2001da177e4SLinus Torvalds 		allocated = anon_vma;
2011da177e4SLinus Torvalds 	}
2021da177e4SLinus Torvalds 
2034fc3f1d6SIngo Molnar 	anon_vma_lock_write(anon_vma);
2041da177e4SLinus Torvalds 	/* page_table_lock to protect against threads */
2051da177e4SLinus Torvalds 	spin_lock(&mm->page_table_lock);
2061da177e4SLinus Torvalds 	if (likely(!vma->anon_vma)) {
2071da177e4SLinus Torvalds 		vma->anon_vma = anon_vma;
2086583a843SKautuk Consul 		anon_vma_chain_link(vma, avc, anon_vma);
2097a3ef208SKonstantin Khlebnikov 		/* vma reference or self-parent link for new root */
2107a3ef208SKonstantin Khlebnikov 		anon_vma->degree++;
2111da177e4SLinus Torvalds 		allocated = NULL;
21231f2b0ebSOleg Nesterov 		avc = NULL;
2131da177e4SLinus Torvalds 	}
2141da177e4SLinus Torvalds 	spin_unlock(&mm->page_table_lock);
21508b52706SKonstantin Khlebnikov 	anon_vma_unlock_write(anon_vma);
21631f2b0ebSOleg Nesterov 
21731f2b0ebSOleg Nesterov 	if (unlikely(allocated))
21801d8b20dSPeter Zijlstra 		put_anon_vma(allocated);
21931f2b0ebSOleg Nesterov 	if (unlikely(avc))
2205beb4930SRik van Riel 		anon_vma_chain_free(avc);
221d5a187daSVlastimil Babka 
2221da177e4SLinus Torvalds 	return 0;
2235beb4930SRik van Riel 
2245beb4930SRik van Riel  out_enomem_free_avc:
2255beb4930SRik van Riel 	anon_vma_chain_free(avc);
2265beb4930SRik van Riel  out_enomem:
2275beb4930SRik van Riel 	return -ENOMEM;
2281da177e4SLinus Torvalds }
2291da177e4SLinus Torvalds 
230bb4aa396SLinus Torvalds /*
231bb4aa396SLinus Torvalds  * This is a useful helper function for locking the anon_vma root as
232bb4aa396SLinus Torvalds  * we traverse the vma->anon_vma_chain, looping over anon_vma's that
233bb4aa396SLinus Torvalds  * have the same vma.
234bb4aa396SLinus Torvalds  *
235bb4aa396SLinus Torvalds  * Such anon_vma's should have the same root, so you'd expect to see
236bb4aa396SLinus Torvalds  * just a single mutex_lock for the whole traversal.
237bb4aa396SLinus Torvalds  */
238bb4aa396SLinus Torvalds static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
239bb4aa396SLinus Torvalds {
240bb4aa396SLinus Torvalds 	struct anon_vma *new_root = anon_vma->root;
241bb4aa396SLinus Torvalds 	if (new_root != root) {
242bb4aa396SLinus Torvalds 		if (WARN_ON_ONCE(root))
2435a505085SIngo Molnar 			up_write(&root->rwsem);
244bb4aa396SLinus Torvalds 		root = new_root;
2455a505085SIngo Molnar 		down_write(&root->rwsem);
246bb4aa396SLinus Torvalds 	}
247bb4aa396SLinus Torvalds 	return root;
248bb4aa396SLinus Torvalds }
249bb4aa396SLinus Torvalds 
250bb4aa396SLinus Torvalds static inline void unlock_anon_vma_root(struct anon_vma *root)
251bb4aa396SLinus Torvalds {
252bb4aa396SLinus Torvalds 	if (root)
2535a505085SIngo Molnar 		up_write(&root->rwsem);
254bb4aa396SLinus Torvalds }
255bb4aa396SLinus Torvalds 
2565beb4930SRik van Riel /*
2575beb4930SRik van Riel  * Attach the anon_vmas from src to dst.
2585beb4930SRik van Riel  * Returns 0 on success, -ENOMEM on failure.
2597a3ef208SKonstantin Khlebnikov  *
26047b390d2SWei Yang  * anon_vma_clone() is called by __vma_split(), __split_vma(), copy_vma() and
26147b390d2SWei Yang  * anon_vma_fork(). The first three want an exact copy of src, while the last
26247b390d2SWei Yang  * one, anon_vma_fork(), may try to reuse an existing anon_vma to prevent
26347b390d2SWei Yang  * endless growth of anon_vma. Since dst->anon_vma is set to NULL before call,
26447b390d2SWei Yang  * we can identify this case by checking (!dst->anon_vma && src->anon_vma).
26547b390d2SWei Yang  *
26647b390d2SWei Yang  * If (!dst->anon_vma && src->anon_vma) is true, this function tries to find
26747b390d2SWei Yang  * and reuse existing anon_vma which has no vmas and only one child anon_vma.
26847b390d2SWei Yang  * This prevents degradation of anon_vma hierarchy to endless linear chain in
26947b390d2SWei Yang  * case of constantly forking task. On the other hand, an anon_vma with more
27047b390d2SWei Yang  * than one child isn't reused even if there was no alive vma, thus rmap
27147b390d2SWei Yang  * walker has a good chance of avoiding scanning the whole hierarchy when it
27247b390d2SWei Yang  * searches where page is mapped.
2735beb4930SRik van Riel  */
2745beb4930SRik van Riel int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
2755beb4930SRik van Riel {
2765beb4930SRik van Riel 	struct anon_vma_chain *avc, *pavc;
277bb4aa396SLinus Torvalds 	struct anon_vma *root = NULL;
2785beb4930SRik van Riel 
279646d87b4SLinus Torvalds 	list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
280bb4aa396SLinus Torvalds 		struct anon_vma *anon_vma;
281bb4aa396SLinus Torvalds 
282dd34739cSLinus Torvalds 		avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
283dd34739cSLinus Torvalds 		if (unlikely(!avc)) {
284dd34739cSLinus Torvalds 			unlock_anon_vma_root(root);
285dd34739cSLinus Torvalds 			root = NULL;
286dd34739cSLinus Torvalds 			avc = anon_vma_chain_alloc(GFP_KERNEL);
2875beb4930SRik van Riel 			if (!avc)
2885beb4930SRik van Riel 				goto enomem_failure;
289dd34739cSLinus Torvalds 		}
290bb4aa396SLinus Torvalds 		anon_vma = pavc->anon_vma;
291bb4aa396SLinus Torvalds 		root = lock_anon_vma_root(root, anon_vma);
292bb4aa396SLinus Torvalds 		anon_vma_chain_link(dst, avc, anon_vma);
2937a3ef208SKonstantin Khlebnikov 
2947a3ef208SKonstantin Khlebnikov 		/*
2957a3ef208SKonstantin Khlebnikov 		 * Reuse existing anon_vma if its degree lower than two,
2967a3ef208SKonstantin Khlebnikov 		 * that means it has no vma and only one anon_vma child.
2977a3ef208SKonstantin Khlebnikov 		 *
2987a3ef208SKonstantin Khlebnikov 		 * Do not chose parent anon_vma, otherwise first child
2997a3ef208SKonstantin Khlebnikov 		 * will always reuse it. Root anon_vma is never reused:
3007a3ef208SKonstantin Khlebnikov 		 * it has self-parent reference and at least one child.
3017a3ef208SKonstantin Khlebnikov 		 */
30247b390d2SWei Yang 		if (!dst->anon_vma && src->anon_vma &&
30347b390d2SWei Yang 		    anon_vma != src->anon_vma && anon_vma->degree < 2)
3047a3ef208SKonstantin Khlebnikov 			dst->anon_vma = anon_vma;
3055beb4930SRik van Riel 	}
3067a3ef208SKonstantin Khlebnikov 	if (dst->anon_vma)
3077a3ef208SKonstantin Khlebnikov 		dst->anon_vma->degree++;
308bb4aa396SLinus Torvalds 	unlock_anon_vma_root(root);
3095beb4930SRik van Riel 	return 0;
3105beb4930SRik van Riel 
3115beb4930SRik van Riel  enomem_failure:
3123fe89b3eSLeon Yu 	/*
3133fe89b3eSLeon Yu 	 * dst->anon_vma is dropped here otherwise its degree can be incorrectly
3143fe89b3eSLeon Yu 	 * decremented in unlink_anon_vmas().
3153fe89b3eSLeon Yu 	 * We can safely do this because callers of anon_vma_clone() don't care
3163fe89b3eSLeon Yu 	 * about dst->anon_vma if anon_vma_clone() failed.
3173fe89b3eSLeon Yu 	 */
3183fe89b3eSLeon Yu 	dst->anon_vma = NULL;
3195beb4930SRik van Riel 	unlink_anon_vmas(dst);
3205beb4930SRik van Riel 	return -ENOMEM;
3211da177e4SLinus Torvalds }
3221da177e4SLinus Torvalds 
3235beb4930SRik van Riel /*
3245beb4930SRik van Riel  * Attach vma to its own anon_vma, as well as to the anon_vmas that
3255beb4930SRik van Riel  * the corresponding VMA in the parent process is attached to.
3265beb4930SRik van Riel  * Returns 0 on success, non-zero on failure.
3275beb4930SRik van Riel  */
3285beb4930SRik van Riel int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
3291da177e4SLinus Torvalds {
3305beb4930SRik van Riel 	struct anon_vma_chain *avc;
3315beb4930SRik van Riel 	struct anon_vma *anon_vma;
332c4ea95d7SDaniel Forrest 	int error;
3335beb4930SRik van Riel 
3345beb4930SRik van Riel 	/* Don't bother if the parent process has no anon_vma here. */
3355beb4930SRik van Riel 	if (!pvma->anon_vma)
3365beb4930SRik van Riel 		return 0;
3375beb4930SRik van Riel 
3387a3ef208SKonstantin Khlebnikov 	/* Drop inherited anon_vma, we'll reuse existing or allocate new. */
3397a3ef208SKonstantin Khlebnikov 	vma->anon_vma = NULL;
3407a3ef208SKonstantin Khlebnikov 
3415beb4930SRik van Riel 	/*
3425beb4930SRik van Riel 	 * First, attach the new VMA to the parent VMA's anon_vmas,
3435beb4930SRik van Riel 	 * so rmap can find non-COWed pages in child processes.
3445beb4930SRik van Riel 	 */
345c4ea95d7SDaniel Forrest 	error = anon_vma_clone(vma, pvma);
346c4ea95d7SDaniel Forrest 	if (error)
347c4ea95d7SDaniel Forrest 		return error;
3485beb4930SRik van Riel 
3497a3ef208SKonstantin Khlebnikov 	/* An existing anon_vma has been reused, all done then. */
3507a3ef208SKonstantin Khlebnikov 	if (vma->anon_vma)
3517a3ef208SKonstantin Khlebnikov 		return 0;
3527a3ef208SKonstantin Khlebnikov 
3535beb4930SRik van Riel 	/* Then add our own anon_vma. */
3545beb4930SRik van Riel 	anon_vma = anon_vma_alloc();
3555beb4930SRik van Riel 	if (!anon_vma)
3565beb4930SRik van Riel 		goto out_error;
357dd34739cSLinus Torvalds 	avc = anon_vma_chain_alloc(GFP_KERNEL);
3585beb4930SRik van Riel 	if (!avc)
3595beb4930SRik van Riel 		goto out_error_free_anon_vma;
3605c341ee1SRik van Riel 
3615c341ee1SRik van Riel 	/*
362aaf1f990SMiaohe Lin 	 * The root anon_vma's rwsem is the lock actually used when we
3635c341ee1SRik van Riel 	 * lock any of the anon_vmas in this anon_vma tree.
3645c341ee1SRik van Riel 	 */
3655c341ee1SRik van Riel 	anon_vma->root = pvma->anon_vma->root;
3667a3ef208SKonstantin Khlebnikov 	anon_vma->parent = pvma->anon_vma;
36776545066SRik van Riel 	/*
36801d8b20dSPeter Zijlstra 	 * With refcounts, an anon_vma can stay around longer than the
36901d8b20dSPeter Zijlstra 	 * process it belongs to. The root anon_vma needs to be pinned until
37001d8b20dSPeter Zijlstra 	 * this anon_vma is freed, because the lock lives in the root.
37176545066SRik van Riel 	 */
37276545066SRik van Riel 	get_anon_vma(anon_vma->root);
3735beb4930SRik van Riel 	/* Mark this anon_vma as the one where our new (COWed) pages go. */
3745beb4930SRik van Riel 	vma->anon_vma = anon_vma;
3754fc3f1d6SIngo Molnar 	anon_vma_lock_write(anon_vma);
3765c341ee1SRik van Riel 	anon_vma_chain_link(vma, avc, anon_vma);
3777a3ef208SKonstantin Khlebnikov 	anon_vma->parent->degree++;
37808b52706SKonstantin Khlebnikov 	anon_vma_unlock_write(anon_vma);
3795beb4930SRik van Riel 
3805beb4930SRik van Riel 	return 0;
3815beb4930SRik van Riel 
3825beb4930SRik van Riel  out_error_free_anon_vma:
38301d8b20dSPeter Zijlstra 	put_anon_vma(anon_vma);
3845beb4930SRik van Riel  out_error:
3854946d54cSRik van Riel 	unlink_anon_vmas(vma);
3865beb4930SRik van Riel 	return -ENOMEM;
3875beb4930SRik van Riel }
3885beb4930SRik van Riel 
3895beb4930SRik van Riel void unlink_anon_vmas(struct vm_area_struct *vma)
3905beb4930SRik van Riel {
3915beb4930SRik van Riel 	struct anon_vma_chain *avc, *next;
392eee2acbaSPeter Zijlstra 	struct anon_vma *root = NULL;
3935beb4930SRik van Riel 
3945c341ee1SRik van Riel 	/*
3955c341ee1SRik van Riel 	 * Unlink each anon_vma chained to the VMA.  This list is ordered
3965c341ee1SRik van Riel 	 * from newest to oldest, ensuring the root anon_vma gets freed last.
3975c341ee1SRik van Riel 	 */
3985beb4930SRik van Riel 	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
399eee2acbaSPeter Zijlstra 		struct anon_vma *anon_vma = avc->anon_vma;
400eee2acbaSPeter Zijlstra 
401eee2acbaSPeter Zijlstra 		root = lock_anon_vma_root(root, anon_vma);
402bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
403eee2acbaSPeter Zijlstra 
404eee2acbaSPeter Zijlstra 		/*
405eee2acbaSPeter Zijlstra 		 * Leave empty anon_vmas on the list - we'll need
406eee2acbaSPeter Zijlstra 		 * to free them outside the lock.
407eee2acbaSPeter Zijlstra 		 */
408f808c13fSDavidlohr Bueso 		if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
4097a3ef208SKonstantin Khlebnikov 			anon_vma->parent->degree--;
410eee2acbaSPeter Zijlstra 			continue;
4117a3ef208SKonstantin Khlebnikov 		}
412eee2acbaSPeter Zijlstra 
413eee2acbaSPeter Zijlstra 		list_del(&avc->same_vma);
414eee2acbaSPeter Zijlstra 		anon_vma_chain_free(avc);
415eee2acbaSPeter Zijlstra 	}
416ee8ab190SLi Xinhai 	if (vma->anon_vma) {
4177a3ef208SKonstantin Khlebnikov 		vma->anon_vma->degree--;
418ee8ab190SLi Xinhai 
419ee8ab190SLi Xinhai 		/*
420ee8ab190SLi Xinhai 		 * vma would still be needed after unlink, and anon_vma will be prepared
421ee8ab190SLi Xinhai 		 * when handle fault.
422ee8ab190SLi Xinhai 		 */
423ee8ab190SLi Xinhai 		vma->anon_vma = NULL;
424ee8ab190SLi Xinhai 	}
425eee2acbaSPeter Zijlstra 	unlock_anon_vma_root(root);
426eee2acbaSPeter Zijlstra 
427eee2acbaSPeter Zijlstra 	/*
428eee2acbaSPeter Zijlstra 	 * Iterate the list once more, it now only contains empty and unlinked
429eee2acbaSPeter Zijlstra 	 * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
4305a505085SIngo Molnar 	 * needing to write-acquire the anon_vma->root->rwsem.
431eee2acbaSPeter Zijlstra 	 */
432eee2acbaSPeter Zijlstra 	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
433eee2acbaSPeter Zijlstra 		struct anon_vma *anon_vma = avc->anon_vma;
434eee2acbaSPeter Zijlstra 
435e4c5800aSKonstantin Khlebnikov 		VM_WARN_ON(anon_vma->degree);
436eee2acbaSPeter Zijlstra 		put_anon_vma(anon_vma);
437eee2acbaSPeter Zijlstra 
4385beb4930SRik van Riel 		list_del(&avc->same_vma);
4395beb4930SRik van Riel 		anon_vma_chain_free(avc);
4405beb4930SRik van Riel 	}
4415beb4930SRik van Riel }
4425beb4930SRik van Riel 
44351cc5068SAlexey Dobriyan static void anon_vma_ctor(void *data)
4441da177e4SLinus Torvalds {
4451da177e4SLinus Torvalds 	struct anon_vma *anon_vma = data;
4461da177e4SLinus Torvalds 
4475a505085SIngo Molnar 	init_rwsem(&anon_vma->rwsem);
44883813267SPeter Zijlstra 	atomic_set(&anon_vma->refcount, 0);
449f808c13fSDavidlohr Bueso 	anon_vma->rb_root = RB_ROOT_CACHED;
4501da177e4SLinus Torvalds }
4511da177e4SLinus Torvalds 
4521da177e4SLinus Torvalds void __init anon_vma_init(void)
4531da177e4SLinus Torvalds {
4541da177e4SLinus Torvalds 	anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
4555f0d5a3aSPaul E. McKenney 			0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
4565d097056SVladimir Davydov 			anon_vma_ctor);
4575d097056SVladimir Davydov 	anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
4585d097056SVladimir Davydov 			SLAB_PANIC|SLAB_ACCOUNT);
4591da177e4SLinus Torvalds }
4601da177e4SLinus Torvalds 
4611da177e4SLinus Torvalds /*
4626111e4caSPeter Zijlstra  * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
4636111e4caSPeter Zijlstra  *
4646111e4caSPeter Zijlstra  * Since there is no serialization what so ever against page_remove_rmap()
4656111e4caSPeter Zijlstra  * the best this function can do is return a locked anon_vma that might
4666111e4caSPeter Zijlstra  * have been relevant to this page.
4676111e4caSPeter Zijlstra  *
4686111e4caSPeter Zijlstra  * The page might have been remapped to a different anon_vma or the anon_vma
4696111e4caSPeter Zijlstra  * returned may already be freed (and even reused).
4706111e4caSPeter Zijlstra  *
471bc658c96SPeter Zijlstra  * In case it was remapped to a different anon_vma, the new anon_vma will be a
472bc658c96SPeter Zijlstra  * child of the old anon_vma, and the anon_vma lifetime rules will therefore
473bc658c96SPeter Zijlstra  * ensure that any anon_vma obtained from the page will still be valid for as
474bc658c96SPeter Zijlstra  * long as we observe page_mapped() [ hence all those page_mapped() tests ].
475bc658c96SPeter Zijlstra  *
4766111e4caSPeter Zijlstra  * All users of this function must be very careful when walking the anon_vma
4776111e4caSPeter Zijlstra  * chain and verify that the page in question is indeed mapped in it
4786111e4caSPeter Zijlstra  * [ something equivalent to page_mapped_in_vma() ].
4796111e4caSPeter Zijlstra  *
480091e4299SMiles Chen  * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
481091e4299SMiles Chen  * page_remove_rmap() that the anon_vma pointer from page->mapping is valid
482091e4299SMiles Chen  * if there is a mapcount, we can dereference the anon_vma after observing
483091e4299SMiles Chen  * those.
4841da177e4SLinus Torvalds  */
485746b18d4SPeter Zijlstra struct anon_vma *page_get_anon_vma(struct page *page)
4861da177e4SLinus Torvalds {
487746b18d4SPeter Zijlstra 	struct anon_vma *anon_vma = NULL;
4881da177e4SLinus Torvalds 	unsigned long anon_mapping;
4891da177e4SLinus Torvalds 
4901da177e4SLinus Torvalds 	rcu_read_lock();
4914db0c3c2SJason Low 	anon_mapping = (unsigned long)READ_ONCE(page->mapping);
4923ca7b3c5SHugh Dickins 	if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
4931da177e4SLinus Torvalds 		goto out;
4941da177e4SLinus Torvalds 	if (!page_mapped(page))
4951da177e4SLinus Torvalds 		goto out;
4961da177e4SLinus Torvalds 
4971da177e4SLinus Torvalds 	anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
498746b18d4SPeter Zijlstra 	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
499746b18d4SPeter Zijlstra 		anon_vma = NULL;
500746b18d4SPeter Zijlstra 		goto out;
501746b18d4SPeter Zijlstra 	}
502f1819427SHugh Dickins 
503f1819427SHugh Dickins 	/*
504f1819427SHugh Dickins 	 * If this page is still mapped, then its anon_vma cannot have been
505746b18d4SPeter Zijlstra 	 * freed.  But if it has been unmapped, we have no security against the
506746b18d4SPeter Zijlstra 	 * anon_vma structure being freed and reused (for another anon_vma:
5075f0d5a3aSPaul E. McKenney 	 * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
508746b18d4SPeter Zijlstra 	 * above cannot corrupt).
509f1819427SHugh Dickins 	 */
510746b18d4SPeter Zijlstra 	if (!page_mapped(page)) {
5117f39dda9SHugh Dickins 		rcu_read_unlock();
512746b18d4SPeter Zijlstra 		put_anon_vma(anon_vma);
5137f39dda9SHugh Dickins 		return NULL;
514746b18d4SPeter Zijlstra 	}
5151da177e4SLinus Torvalds out:
5161da177e4SLinus Torvalds 	rcu_read_unlock();
517746b18d4SPeter Zijlstra 
518746b18d4SPeter Zijlstra 	return anon_vma;
519746b18d4SPeter Zijlstra }
520746b18d4SPeter Zijlstra 
52188c22088SPeter Zijlstra /*
52288c22088SPeter Zijlstra  * Similar to page_get_anon_vma() except it locks the anon_vma.
52388c22088SPeter Zijlstra  *
52488c22088SPeter Zijlstra  * Its a little more complex as it tries to keep the fast path to a single
52588c22088SPeter Zijlstra  * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
52688c22088SPeter Zijlstra  * reference like with page_get_anon_vma() and then block on the mutex.
52788c22088SPeter Zijlstra  */
5284fc3f1d6SIngo Molnar struct anon_vma *page_lock_anon_vma_read(struct page *page)
529746b18d4SPeter Zijlstra {
53088c22088SPeter Zijlstra 	struct anon_vma *anon_vma = NULL;
531eee0f252SHugh Dickins 	struct anon_vma *root_anon_vma;
53288c22088SPeter Zijlstra 	unsigned long anon_mapping;
533746b18d4SPeter Zijlstra 
53488c22088SPeter Zijlstra 	rcu_read_lock();
5354db0c3c2SJason Low 	anon_mapping = (unsigned long)READ_ONCE(page->mapping);
53688c22088SPeter Zijlstra 	if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
53788c22088SPeter Zijlstra 		goto out;
53888c22088SPeter Zijlstra 	if (!page_mapped(page))
53988c22088SPeter Zijlstra 		goto out;
54088c22088SPeter Zijlstra 
54188c22088SPeter Zijlstra 	anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
5424db0c3c2SJason Low 	root_anon_vma = READ_ONCE(anon_vma->root);
5434fc3f1d6SIngo Molnar 	if (down_read_trylock(&root_anon_vma->rwsem)) {
54488c22088SPeter Zijlstra 		/*
545eee0f252SHugh Dickins 		 * If the page is still mapped, then this anon_vma is still
546eee0f252SHugh Dickins 		 * its anon_vma, and holding the mutex ensures that it will
547bc658c96SPeter Zijlstra 		 * not go away, see anon_vma_free().
54888c22088SPeter Zijlstra 		 */
549eee0f252SHugh Dickins 		if (!page_mapped(page)) {
5504fc3f1d6SIngo Molnar 			up_read(&root_anon_vma->rwsem);
55188c22088SPeter Zijlstra 			anon_vma = NULL;
55288c22088SPeter Zijlstra 		}
55388c22088SPeter Zijlstra 		goto out;
55488c22088SPeter Zijlstra 	}
55588c22088SPeter Zijlstra 
55688c22088SPeter Zijlstra 	/* trylock failed, we got to sleep */
55788c22088SPeter Zijlstra 	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
55888c22088SPeter Zijlstra 		anon_vma = NULL;
55988c22088SPeter Zijlstra 		goto out;
56088c22088SPeter Zijlstra 	}
56188c22088SPeter Zijlstra 
56288c22088SPeter Zijlstra 	if (!page_mapped(page)) {
5637f39dda9SHugh Dickins 		rcu_read_unlock();
56488c22088SPeter Zijlstra 		put_anon_vma(anon_vma);
5657f39dda9SHugh Dickins 		return NULL;
56688c22088SPeter Zijlstra 	}
56788c22088SPeter Zijlstra 
56888c22088SPeter Zijlstra 	/* we pinned the anon_vma, its safe to sleep */
56988c22088SPeter Zijlstra 	rcu_read_unlock();
5704fc3f1d6SIngo Molnar 	anon_vma_lock_read(anon_vma);
571746b18d4SPeter Zijlstra 
57288c22088SPeter Zijlstra 	if (atomic_dec_and_test(&anon_vma->refcount)) {
57388c22088SPeter Zijlstra 		/*
57488c22088SPeter Zijlstra 		 * Oops, we held the last refcount, release the lock
57588c22088SPeter Zijlstra 		 * and bail -- can't simply use put_anon_vma() because
5764fc3f1d6SIngo Molnar 		 * we'll deadlock on the anon_vma_lock_write() recursion.
57788c22088SPeter Zijlstra 		 */
5784fc3f1d6SIngo Molnar 		anon_vma_unlock_read(anon_vma);
57988c22088SPeter Zijlstra 		__put_anon_vma(anon_vma);
58088c22088SPeter Zijlstra 		anon_vma = NULL;
58188c22088SPeter Zijlstra 	}
58288c22088SPeter Zijlstra 
58388c22088SPeter Zijlstra 	return anon_vma;
58488c22088SPeter Zijlstra 
58588c22088SPeter Zijlstra out:
58688c22088SPeter Zijlstra 	rcu_read_unlock();
587746b18d4SPeter Zijlstra 	return anon_vma;
58834bbd704SOleg Nesterov }
58934bbd704SOleg Nesterov 
5904fc3f1d6SIngo Molnar void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
59134bbd704SOleg Nesterov {
5924fc3f1d6SIngo Molnar 	anon_vma_unlock_read(anon_vma);
5931da177e4SLinus Torvalds }
5941da177e4SLinus Torvalds 
59572b252aeSMel Gorman #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
59672b252aeSMel Gorman /*
59772b252aeSMel Gorman  * Flush TLB entries for recently unmapped pages from remote CPUs. It is
59872b252aeSMel Gorman  * important if a PTE was dirty when it was unmapped that it's flushed
59972b252aeSMel Gorman  * before any IO is initiated on the page to prevent lost writes. Similarly,
60072b252aeSMel Gorman  * it must be flushed before freeing to prevent data leakage.
60172b252aeSMel Gorman  */
60272b252aeSMel Gorman void try_to_unmap_flush(void)
60372b252aeSMel Gorman {
60472b252aeSMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
60572b252aeSMel Gorman 
60672b252aeSMel Gorman 	if (!tlb_ubc->flush_required)
60772b252aeSMel Gorman 		return;
60872b252aeSMel Gorman 
609e73ad5ffSAndy Lutomirski 	arch_tlbbatch_flush(&tlb_ubc->arch);
61072b252aeSMel Gorman 	tlb_ubc->flush_required = false;
611d950c947SMel Gorman 	tlb_ubc->writable = false;
61272b252aeSMel Gorman }
61372b252aeSMel Gorman 
614d950c947SMel Gorman /* Flush iff there are potentially writable TLB entries that can race with IO */
615d950c947SMel Gorman void try_to_unmap_flush_dirty(void)
616d950c947SMel Gorman {
617d950c947SMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
618d950c947SMel Gorman 
619d950c947SMel Gorman 	if (tlb_ubc->writable)
620d950c947SMel Gorman 		try_to_unmap_flush();
621d950c947SMel Gorman }
622d950c947SMel Gorman 
623c7ab0d2fSKirill A. Shutemov static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
62472b252aeSMel Gorman {
62572b252aeSMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
62672b252aeSMel Gorman 
627e73ad5ffSAndy Lutomirski 	arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
62872b252aeSMel Gorman 	tlb_ubc->flush_required = true;
629d950c947SMel Gorman 
630d950c947SMel Gorman 	/*
6313ea27719SMel Gorman 	 * Ensure compiler does not re-order the setting of tlb_flush_batched
6323ea27719SMel Gorman 	 * before the PTE is cleared.
6333ea27719SMel Gorman 	 */
6343ea27719SMel Gorman 	barrier();
6353ea27719SMel Gorman 	mm->tlb_flush_batched = true;
6363ea27719SMel Gorman 
6373ea27719SMel Gorman 	/*
638d950c947SMel Gorman 	 * If the PTE was dirty then it's best to assume it's writable. The
639d950c947SMel Gorman 	 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
640d950c947SMel Gorman 	 * before the page is queued for IO.
641d950c947SMel Gorman 	 */
642d950c947SMel Gorman 	if (writable)
643d950c947SMel Gorman 		tlb_ubc->writable = true;
64472b252aeSMel Gorman }
64572b252aeSMel Gorman 
64672b252aeSMel Gorman /*
64772b252aeSMel Gorman  * Returns true if the TLB flush should be deferred to the end of a batch of
64872b252aeSMel Gorman  * unmap operations to reduce IPIs.
64972b252aeSMel Gorman  */
65072b252aeSMel Gorman static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
65172b252aeSMel Gorman {
65272b252aeSMel Gorman 	bool should_defer = false;
65372b252aeSMel Gorman 
65472b252aeSMel Gorman 	if (!(flags & TTU_BATCH_FLUSH))
65572b252aeSMel Gorman 		return false;
65672b252aeSMel Gorman 
65772b252aeSMel Gorman 	/* If remote CPUs need to be flushed then defer batch the flush */
65872b252aeSMel Gorman 	if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
65972b252aeSMel Gorman 		should_defer = true;
66072b252aeSMel Gorman 	put_cpu();
66172b252aeSMel Gorman 
66272b252aeSMel Gorman 	return should_defer;
66372b252aeSMel Gorman }
6643ea27719SMel Gorman 
6653ea27719SMel Gorman /*
6663ea27719SMel Gorman  * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
6673ea27719SMel Gorman  * releasing the PTL if TLB flushes are batched. It's possible for a parallel
6683ea27719SMel Gorman  * operation such as mprotect or munmap to race between reclaim unmapping
6693ea27719SMel Gorman  * the page and flushing the page. If this race occurs, it potentially allows
6703ea27719SMel Gorman  * access to data via a stale TLB entry. Tracking all mm's that have TLB
6713ea27719SMel Gorman  * batching in flight would be expensive during reclaim so instead track
6723ea27719SMel Gorman  * whether TLB batching occurred in the past and if so then do a flush here
6733ea27719SMel Gorman  * if required. This will cost one additional flush per reclaim cycle paid
6743ea27719SMel Gorman  * by the first operation at risk such as mprotect and mumap.
6753ea27719SMel Gorman  *
6763ea27719SMel Gorman  * This must be called under the PTL so that an access to tlb_flush_batched
6773ea27719SMel Gorman  * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
6783ea27719SMel Gorman  * via the PTL.
6793ea27719SMel Gorman  */
6803ea27719SMel Gorman void flush_tlb_batched_pending(struct mm_struct *mm)
6813ea27719SMel Gorman {
6829c1177b6SQian Cai 	if (data_race(mm->tlb_flush_batched)) {
6833ea27719SMel Gorman 		flush_tlb_mm(mm);
6843ea27719SMel Gorman 
6853ea27719SMel Gorman 		/*
6863ea27719SMel Gorman 		 * Do not allow the compiler to re-order the clearing of
6873ea27719SMel Gorman 		 * tlb_flush_batched before the tlb is flushed.
6883ea27719SMel Gorman 		 */
6893ea27719SMel Gorman 		barrier();
6903ea27719SMel Gorman 		mm->tlb_flush_batched = false;
6913ea27719SMel Gorman 	}
6923ea27719SMel Gorman }
69372b252aeSMel Gorman #else
694c7ab0d2fSKirill A. Shutemov static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
69572b252aeSMel Gorman {
69672b252aeSMel Gorman }
69772b252aeSMel Gorman 
69872b252aeSMel Gorman static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
69972b252aeSMel Gorman {
70072b252aeSMel Gorman 	return false;
70172b252aeSMel Gorman }
70272b252aeSMel Gorman #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
70372b252aeSMel Gorman 
7041da177e4SLinus Torvalds /*
705bf89c8c8SHuang Shijie  * At what user virtual address is page expected in vma?
706ab941e0fSNaoya Horiguchi  * Caller should check the page is actually part of the vma.
7071da177e4SLinus Torvalds  */
7081da177e4SLinus Torvalds unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
7091da177e4SLinus Torvalds {
71086c2ad19SMichel Lespinasse 	unsigned long address;
71121d0d443SAndrea Arcangeli 	if (PageAnon(page)) {
7124829b906SHugh Dickins 		struct anon_vma *page__anon_vma = page_anon_vma(page);
7134829b906SHugh Dickins 		/*
7144829b906SHugh Dickins 		 * Note: swapoff's unuse_vma() is more efficient with this
7154829b906SHugh Dickins 		 * check, and needs it to match anon_vma when KSM is active.
7164829b906SHugh Dickins 		 */
7174829b906SHugh Dickins 		if (!vma->anon_vma || !page__anon_vma ||
7184829b906SHugh Dickins 		    vma->anon_vma->root != page__anon_vma->root)
71921d0d443SAndrea Arcangeli 			return -EFAULT;
72027ba0644SKirill A. Shutemov 	} else if (page->mapping) {
72127ba0644SKirill A. Shutemov 		if (!vma->vm_file || vma->vm_file->f_mapping != page->mapping)
7221da177e4SLinus Torvalds 			return -EFAULT;
7231da177e4SLinus Torvalds 	} else
7241da177e4SLinus Torvalds 		return -EFAULT;
72586c2ad19SMichel Lespinasse 	address = __vma_address(page, vma);
72686c2ad19SMichel Lespinasse 	if (unlikely(address < vma->vm_start || address >= vma->vm_end))
72786c2ad19SMichel Lespinasse 		return -EFAULT;
72886c2ad19SMichel Lespinasse 	return address;
7291da177e4SLinus Torvalds }
7301da177e4SLinus Torvalds 
7316219049aSBob Liu pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
7326219049aSBob Liu {
7336219049aSBob Liu 	pgd_t *pgd;
734c2febafcSKirill A. Shutemov 	p4d_t *p4d;
7356219049aSBob Liu 	pud_t *pud;
7366219049aSBob Liu 	pmd_t *pmd = NULL;
737f72e7dcdSHugh Dickins 	pmd_t pmde;
7386219049aSBob Liu 
7396219049aSBob Liu 	pgd = pgd_offset(mm, address);
7406219049aSBob Liu 	if (!pgd_present(*pgd))
7416219049aSBob Liu 		goto out;
7426219049aSBob Liu 
743c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, address);
744c2febafcSKirill A. Shutemov 	if (!p4d_present(*p4d))
745c2febafcSKirill A. Shutemov 		goto out;
746c2febafcSKirill A. Shutemov 
747c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, address);
7486219049aSBob Liu 	if (!pud_present(*pud))
7496219049aSBob Liu 		goto out;
7506219049aSBob Liu 
7516219049aSBob Liu 	pmd = pmd_offset(pud, address);
752f72e7dcdSHugh Dickins 	/*
7538809aa2dSAneesh Kumar K.V 	 * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
754f72e7dcdSHugh Dickins 	 * without holding anon_vma lock for write.  So when looking for a
755f72e7dcdSHugh Dickins 	 * genuine pmde (in which to find pte), test present and !THP together.
756f72e7dcdSHugh Dickins 	 */
757e37c6982SChristian Borntraeger 	pmde = *pmd;
758e37c6982SChristian Borntraeger 	barrier();
759f72e7dcdSHugh Dickins 	if (!pmd_present(pmde) || pmd_trans_huge(pmde))
7606219049aSBob Liu 		pmd = NULL;
7616219049aSBob Liu out:
7626219049aSBob Liu 	return pmd;
7636219049aSBob Liu }
7646219049aSBob Liu 
7659f32624bSJoonsoo Kim struct page_referenced_arg {
7669f32624bSJoonsoo Kim 	int mapcount;
7679f32624bSJoonsoo Kim 	int referenced;
7689f32624bSJoonsoo Kim 	unsigned long vm_flags;
7699f32624bSJoonsoo Kim 	struct mem_cgroup *memcg;
7709f32624bSJoonsoo Kim };
77181b4082dSNikita Danilov /*
7729f32624bSJoonsoo Kim  * arg: page_referenced_arg will be passed
7731da177e4SLinus Torvalds  */
774e4b82222SMinchan Kim static bool page_referenced_one(struct page *page, struct vm_area_struct *vma,
7759f32624bSJoonsoo Kim 			unsigned long address, void *arg)
7761da177e4SLinus Torvalds {
7779f32624bSJoonsoo Kim 	struct page_referenced_arg *pra = arg;
7788eaededeSKirill A. Shutemov 	struct page_vma_mapped_walk pvmw = {
7798eaededeSKirill A. Shutemov 		.page = page,
7808eaededeSKirill A. Shutemov 		.vma = vma,
7818eaededeSKirill A. Shutemov 		.address = address,
7828eaededeSKirill A. Shutemov 	};
7838749cfeaSVladimir Davydov 	int referenced = 0;
7842da28bfdSAndrea Arcangeli 
7858eaededeSKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
7868eaededeSKirill A. Shutemov 		address = pvmw.address;
7872da28bfdSAndrea Arcangeli 
788b20ce5e0SKirill A. Shutemov 		if (vma->vm_flags & VM_LOCKED) {
7898eaededeSKirill A. Shutemov 			page_vma_mapped_walk_done(&pvmw);
7909f32624bSJoonsoo Kim 			pra->vm_flags |= VM_LOCKED;
791e4b82222SMinchan Kim 			return false; /* To break the loop */
7922da28bfdSAndrea Arcangeli 		}
7932da28bfdSAndrea Arcangeli 
7948eaededeSKirill A. Shutemov 		if (pvmw.pte) {
7958eaededeSKirill A. Shutemov 			if (ptep_clear_flush_young_notify(vma, address,
7968eaededeSKirill A. Shutemov 						pvmw.pte)) {
7974917e5d0SJohannes Weiner 				/*
7988eaededeSKirill A. Shutemov 				 * Don't treat a reference through
7998eaededeSKirill A. Shutemov 				 * a sequentially read mapping as such.
8008eaededeSKirill A. Shutemov 				 * If the page has been used in another mapping,
8018eaededeSKirill A. Shutemov 				 * we will catch it; if this other mapping is
8028eaededeSKirill A. Shutemov 				 * already gone, the unmap path will have set
8038eaededeSKirill A. Shutemov 				 * PG_referenced or activated the page.
8044917e5d0SJohannes Weiner 				 */
80564363aadSJoe Perches 				if (likely(!(vma->vm_flags & VM_SEQ_READ)))
8061da177e4SLinus Torvalds 					referenced++;
8074917e5d0SJohannes Weiner 			}
8088749cfeaSVladimir Davydov 		} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
8098eaededeSKirill A. Shutemov 			if (pmdp_clear_flush_young_notify(vma, address,
8108eaededeSKirill A. Shutemov 						pvmw.pmd))
8118749cfeaSVladimir Davydov 				referenced++;
8128749cfeaSVladimir Davydov 		} else {
8138749cfeaSVladimir Davydov 			/* unexpected pmd-mapped page? */
8148749cfeaSVladimir Davydov 			WARN_ON_ONCE(1);
8158749cfeaSVladimir Davydov 		}
8168eaededeSKirill A. Shutemov 
8178eaededeSKirill A. Shutemov 		pra->mapcount--;
8188eaededeSKirill A. Shutemov 	}
81971e3aac0SAndrea Arcangeli 
82033c3fc71SVladimir Davydov 	if (referenced)
82133c3fc71SVladimir Davydov 		clear_page_idle(page);
82233c3fc71SVladimir Davydov 	if (test_and_clear_page_young(page))
82333c3fc71SVladimir Davydov 		referenced++;
82433c3fc71SVladimir Davydov 
8259f32624bSJoonsoo Kim 	if (referenced) {
8269f32624bSJoonsoo Kim 		pra->referenced++;
8279f32624bSJoonsoo Kim 		pra->vm_flags |= vma->vm_flags;
8281da177e4SLinus Torvalds 	}
8291da177e4SLinus Torvalds 
8309f32624bSJoonsoo Kim 	if (!pra->mapcount)
831e4b82222SMinchan Kim 		return false; /* To break the loop */
8329f32624bSJoonsoo Kim 
833e4b82222SMinchan Kim 	return true;
8349f32624bSJoonsoo Kim }
8359f32624bSJoonsoo Kim 
8369f32624bSJoonsoo Kim static bool invalid_page_referenced_vma(struct vm_area_struct *vma, void *arg)
8371da177e4SLinus Torvalds {
8389f32624bSJoonsoo Kim 	struct page_referenced_arg *pra = arg;
8399f32624bSJoonsoo Kim 	struct mem_cgroup *memcg = pra->memcg;
8401da177e4SLinus Torvalds 
8419f32624bSJoonsoo Kim 	if (!mm_match_cgroup(vma->vm_mm, memcg))
8429f32624bSJoonsoo Kim 		return true;
8431da177e4SLinus Torvalds 
8449f32624bSJoonsoo Kim 	return false;
8451da177e4SLinus Torvalds }
8461da177e4SLinus Torvalds 
8471da177e4SLinus Torvalds /**
8481da177e4SLinus Torvalds  * page_referenced - test if the page was referenced
8491da177e4SLinus Torvalds  * @page: the page to test
8501da177e4SLinus Torvalds  * @is_locked: caller holds lock on the page
85172835c86SJohannes Weiner  * @memcg: target memory cgroup
8526fe6b7e3SWu Fengguang  * @vm_flags: collect encountered vma->vm_flags who actually referenced the page
8531da177e4SLinus Torvalds  *
8541da177e4SLinus Torvalds  * Quick test_and_clear_referenced for all mappings to a page,
8551da177e4SLinus Torvalds  * returns the number of ptes which referenced the page.
8561da177e4SLinus Torvalds  */
8576fe6b7e3SWu Fengguang int page_referenced(struct page *page,
8586fe6b7e3SWu Fengguang 		    int is_locked,
85972835c86SJohannes Weiner 		    struct mem_cgroup *memcg,
8606fe6b7e3SWu Fengguang 		    unsigned long *vm_flags)
8611da177e4SLinus Torvalds {
8625ad64688SHugh Dickins 	int we_locked = 0;
8639f32624bSJoonsoo Kim 	struct page_referenced_arg pra = {
864b20ce5e0SKirill A. Shutemov 		.mapcount = total_mapcount(page),
8659f32624bSJoonsoo Kim 		.memcg = memcg,
8669f32624bSJoonsoo Kim 	};
8679f32624bSJoonsoo Kim 	struct rmap_walk_control rwc = {
8689f32624bSJoonsoo Kim 		.rmap_one = page_referenced_one,
8699f32624bSJoonsoo Kim 		.arg = (void *)&pra,
8709f32624bSJoonsoo Kim 		.anon_lock = page_lock_anon_vma_read,
8719f32624bSJoonsoo Kim 	};
8721da177e4SLinus Torvalds 
8736fe6b7e3SWu Fengguang 	*vm_flags = 0;
874059d8442SHuang Shijie 	if (!pra.mapcount)
8759f32624bSJoonsoo Kim 		return 0;
8769f32624bSJoonsoo Kim 
8779f32624bSJoonsoo Kim 	if (!page_rmapping(page))
8789f32624bSJoonsoo Kim 		return 0;
8799f32624bSJoonsoo Kim 
8805ad64688SHugh Dickins 	if (!is_locked && (!PageAnon(page) || PageKsm(page))) {
8815ad64688SHugh Dickins 		we_locked = trylock_page(page);
8829f32624bSJoonsoo Kim 		if (!we_locked)
8839f32624bSJoonsoo Kim 			return 1;
8845ad64688SHugh Dickins 	}
8859f32624bSJoonsoo Kim 
8869f32624bSJoonsoo Kim 	/*
8879f32624bSJoonsoo Kim 	 * If we are reclaiming on behalf of a cgroup, skip
8889f32624bSJoonsoo Kim 	 * counting on behalf of references from different
8899f32624bSJoonsoo Kim 	 * cgroups
8909f32624bSJoonsoo Kim 	 */
8919f32624bSJoonsoo Kim 	if (memcg) {
8929f32624bSJoonsoo Kim 		rwc.invalid_vma = invalid_page_referenced_vma;
8935ad64688SHugh Dickins 	}
8949f32624bSJoonsoo Kim 
895c24f386cSMinchan Kim 	rmap_walk(page, &rwc);
8969f32624bSJoonsoo Kim 	*vm_flags = pra.vm_flags;
8979f32624bSJoonsoo Kim 
8985ad64688SHugh Dickins 	if (we_locked)
8991da177e4SLinus Torvalds 		unlock_page(page);
9009f32624bSJoonsoo Kim 
9019f32624bSJoonsoo Kim 	return pra.referenced;
9021da177e4SLinus Torvalds }
9031da177e4SLinus Torvalds 
904e4b82222SMinchan Kim static bool page_mkclean_one(struct page *page, struct vm_area_struct *vma,
9059853a407SJoonsoo Kim 			    unsigned long address, void *arg)
906d08b3851SPeter Zijlstra {
907f27176cfSKirill A. Shutemov 	struct page_vma_mapped_walk pvmw = {
908f27176cfSKirill A. Shutemov 		.page = page,
909f27176cfSKirill A. Shutemov 		.vma = vma,
910f27176cfSKirill A. Shutemov 		.address = address,
911f27176cfSKirill A. Shutemov 		.flags = PVMW_SYNC,
912f27176cfSKirill A. Shutemov 	};
913ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
9149853a407SJoonsoo Kim 	int *cleaned = arg;
915d08b3851SPeter Zijlstra 
916369ea824SJérôme Glisse 	/*
917369ea824SJérôme Glisse 	 * We have to assume the worse case ie pmd for invalidation. Note that
918369ea824SJérôme Glisse 	 * the page can not be free from this function.
919369ea824SJérôme Glisse 	 */
9207269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
9217269f999SJérôme Glisse 				0, vma, vma->vm_mm, address,
922a50b854eSMatthew Wilcox (Oracle) 				min(vma->vm_end, address + page_size(page)));
923ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
924369ea824SJérôme Glisse 
925f27176cfSKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
926f27176cfSKirill A. Shutemov 		int ret = 0;
927369ea824SJérôme Glisse 
9281f18b296SYueHaibing 		address = pvmw.address;
929f27176cfSKirill A. Shutemov 		if (pvmw.pte) {
930c2fda5feSPeter Zijlstra 			pte_t entry;
931f27176cfSKirill A. Shutemov 			pte_t *pte = pvmw.pte;
932f27176cfSKirill A. Shutemov 
933f27176cfSKirill A. Shutemov 			if (!pte_dirty(*pte) && !pte_write(*pte))
934f27176cfSKirill A. Shutemov 				continue;
935d08b3851SPeter Zijlstra 
936785373b4SLinus Torvalds 			flush_cache_page(vma, address, pte_pfn(*pte));
937785373b4SLinus Torvalds 			entry = ptep_clear_flush(vma, address, pte);
938d08b3851SPeter Zijlstra 			entry = pte_wrprotect(entry);
939c2fda5feSPeter Zijlstra 			entry = pte_mkclean(entry);
940785373b4SLinus Torvalds 			set_pte_at(vma->vm_mm, address, pte, entry);
941d08b3851SPeter Zijlstra 			ret = 1;
942f27176cfSKirill A. Shutemov 		} else {
943396bcc52SMatthew Wilcox (Oracle) #ifdef CONFIG_TRANSPARENT_HUGEPAGE
944f27176cfSKirill A. Shutemov 			pmd_t *pmd = pvmw.pmd;
945f27176cfSKirill A. Shutemov 			pmd_t entry;
946d08b3851SPeter Zijlstra 
947f27176cfSKirill A. Shutemov 			if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
948f27176cfSKirill A. Shutemov 				continue;
949f27176cfSKirill A. Shutemov 
950785373b4SLinus Torvalds 			flush_cache_page(vma, address, page_to_pfn(page));
951024eee0eSAneesh Kumar K.V 			entry = pmdp_invalidate(vma, address, pmd);
952f27176cfSKirill A. Shutemov 			entry = pmd_wrprotect(entry);
953f27176cfSKirill A. Shutemov 			entry = pmd_mkclean(entry);
954785373b4SLinus Torvalds 			set_pmd_at(vma->vm_mm, address, pmd, entry);
955f27176cfSKirill A. Shutemov 			ret = 1;
956f27176cfSKirill A. Shutemov #else
957f27176cfSKirill A. Shutemov 			/* unexpected pmd-mapped page? */
958f27176cfSKirill A. Shutemov 			WARN_ON_ONCE(1);
959f27176cfSKirill A. Shutemov #endif
960f27176cfSKirill A. Shutemov 		}
9612ec74c3eSSagi Grimberg 
9620f10851eSJérôme Glisse 		/*
9630f10851eSJérôme Glisse 		 * No need to call mmu_notifier_invalidate_range() as we are
9640f10851eSJérôme Glisse 		 * downgrading page table protection not changing it to point
9650f10851eSJérôme Glisse 		 * to a new page.
9660f10851eSJérôme Glisse 		 *
967ad56b738SMike Rapoport 		 * See Documentation/vm/mmu_notifier.rst
9680f10851eSJérôme Glisse 		 */
9690f10851eSJérôme Glisse 		if (ret)
9709853a407SJoonsoo Kim 			(*cleaned)++;
9719853a407SJoonsoo Kim 	}
972f27176cfSKirill A. Shutemov 
973ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
974369ea824SJérôme Glisse 
975e4b82222SMinchan Kim 	return true;
976d08b3851SPeter Zijlstra }
977d08b3851SPeter Zijlstra 
9789853a407SJoonsoo Kim static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
979d08b3851SPeter Zijlstra {
9809853a407SJoonsoo Kim 	if (vma->vm_flags & VM_SHARED)
981871beb8cSFengguang Wu 		return false;
982d08b3851SPeter Zijlstra 
983871beb8cSFengguang Wu 	return true;
984d08b3851SPeter Zijlstra }
985d08b3851SPeter Zijlstra 
986d08b3851SPeter Zijlstra int page_mkclean(struct page *page)
987d08b3851SPeter Zijlstra {
9889853a407SJoonsoo Kim 	int cleaned = 0;
9899853a407SJoonsoo Kim 	struct address_space *mapping;
9909853a407SJoonsoo Kim 	struct rmap_walk_control rwc = {
9919853a407SJoonsoo Kim 		.arg = (void *)&cleaned,
9929853a407SJoonsoo Kim 		.rmap_one = page_mkclean_one,
9939853a407SJoonsoo Kim 		.invalid_vma = invalid_mkclean_vma,
9949853a407SJoonsoo Kim 	};
995d08b3851SPeter Zijlstra 
996d08b3851SPeter Zijlstra 	BUG_ON(!PageLocked(page));
997d08b3851SPeter Zijlstra 
9989853a407SJoonsoo Kim 	if (!page_mapped(page))
9999853a407SJoonsoo Kim 		return 0;
1000d08b3851SPeter Zijlstra 
10019853a407SJoonsoo Kim 	mapping = page_mapping(page);
10029853a407SJoonsoo Kim 	if (!mapping)
10039853a407SJoonsoo Kim 		return 0;
10049853a407SJoonsoo Kim 
10059853a407SJoonsoo Kim 	rmap_walk(page, &rwc);
10069853a407SJoonsoo Kim 
10079853a407SJoonsoo Kim 	return cleaned;
1008d08b3851SPeter Zijlstra }
100960b59beaSJaya Kumar EXPORT_SYMBOL_GPL(page_mkclean);
1010d08b3851SPeter Zijlstra 
10111da177e4SLinus Torvalds /**
1012c44b6743SRik van Riel  * page_move_anon_rmap - move a page to our anon_vma
1013c44b6743SRik van Riel  * @page:	the page to move to our anon_vma
1014c44b6743SRik van Riel  * @vma:	the vma the page belongs to
1015c44b6743SRik van Riel  *
1016c44b6743SRik van Riel  * When a page belongs exclusively to one process after a COW event,
1017c44b6743SRik van Riel  * that page can be moved into the anon_vma that belongs to just that
1018c44b6743SRik van Riel  * process, so the rmap code will not search the parent or sibling
1019c44b6743SRik van Riel  * processes.
1020c44b6743SRik van Riel  */
10215a49973dSHugh Dickins void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
1022c44b6743SRik van Riel {
1023c44b6743SRik van Riel 	struct anon_vma *anon_vma = vma->anon_vma;
1024c44b6743SRik van Riel 
10255a49973dSHugh Dickins 	page = compound_head(page);
10265a49973dSHugh Dickins 
1027309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
102881d1b09cSSasha Levin 	VM_BUG_ON_VMA(!anon_vma, vma);
1029c44b6743SRik van Riel 
1030c44b6743SRik van Riel 	anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
1031414e2fb8SVladimir Davydov 	/*
1032414e2fb8SVladimir Davydov 	 * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
1033414e2fb8SVladimir Davydov 	 * simultaneously, so a concurrent reader (eg page_referenced()'s
1034414e2fb8SVladimir Davydov 	 * PageAnon()) will not see one without the other.
1035414e2fb8SVladimir Davydov 	 */
1036414e2fb8SVladimir Davydov 	WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
1037c44b6743SRik van Riel }
1038c44b6743SRik van Riel 
1039c44b6743SRik van Riel /**
104043d8eac4SRandy Dunlap  * __page_set_anon_rmap - set up new anonymous rmap
1041451b9514SKirill Tkhai  * @page:	Page or Hugepage to add to rmap
10424e1c1975SAndi Kleen  * @vma:	VM area to add page to.
10434e1c1975SAndi Kleen  * @address:	User virtual address of the mapping
1044e8a03febSRik van Riel  * @exclusive:	the page is exclusively owned by the current process
10451da177e4SLinus Torvalds  */
10469617d95eSNick Piggin static void __page_set_anon_rmap(struct page *page,
1047e8a03febSRik van Riel 	struct vm_area_struct *vma, unsigned long address, int exclusive)
10481da177e4SLinus Torvalds {
1049e8a03febSRik van Riel 	struct anon_vma *anon_vma = vma->anon_vma;
10502822c1aaSNick Piggin 
1051e8a03febSRik van Riel 	BUG_ON(!anon_vma);
1052ea90002bSLinus Torvalds 
10534e1c1975SAndi Kleen 	if (PageAnon(page))
10544e1c1975SAndi Kleen 		return;
10554e1c1975SAndi Kleen 
1056ea90002bSLinus Torvalds 	/*
1057e8a03febSRik van Riel 	 * If the page isn't exclusively mapped into this vma,
1058e8a03febSRik van Riel 	 * we must use the _oldest_ possible anon_vma for the
1059e8a03febSRik van Riel 	 * page mapping!
1060ea90002bSLinus Torvalds 	 */
10614e1c1975SAndi Kleen 	if (!exclusive)
1062288468c3SAndrea Arcangeli 		anon_vma = anon_vma->root;
1063ea90002bSLinus Torvalds 
106416f5e707SAlex Shi 	/*
106516f5e707SAlex Shi 	 * page_idle does a lockless/optimistic rmap scan on page->mapping.
106616f5e707SAlex Shi 	 * Make sure the compiler doesn't split the stores of anon_vma and
106716f5e707SAlex Shi 	 * the PAGE_MAPPING_ANON type identifier, otherwise the rmap code
106816f5e707SAlex Shi 	 * could mistake the mapping for a struct address_space and crash.
106916f5e707SAlex Shi 	 */
10701da177e4SLinus Torvalds 	anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
107116f5e707SAlex Shi 	WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
10724d7670e0SNick Piggin 	page->index = linear_page_index(vma, address);
10731da177e4SLinus Torvalds }
10749617d95eSNick Piggin 
10759617d95eSNick Piggin /**
107643d8eac4SRandy Dunlap  * __page_check_anon_rmap - sanity check anonymous rmap addition
1077c97a9e10SNick Piggin  * @page:	the page to add the mapping to
1078c97a9e10SNick Piggin  * @vma:	the vm area in which the mapping is added
1079c97a9e10SNick Piggin  * @address:	the user virtual address mapped
1080c97a9e10SNick Piggin  */
1081c97a9e10SNick Piggin static void __page_check_anon_rmap(struct page *page,
1082c97a9e10SNick Piggin 	struct vm_area_struct *vma, unsigned long address)
1083c97a9e10SNick Piggin {
1084c97a9e10SNick Piggin 	/*
1085c97a9e10SNick Piggin 	 * The page's anon-rmap details (mapping and index) are guaranteed to
1086c97a9e10SNick Piggin 	 * be set up correctly at this point.
1087c97a9e10SNick Piggin 	 *
1088c97a9e10SNick Piggin 	 * We have exclusion against page_add_anon_rmap because the caller
1089*90aaca85SMiaohe Lin 	 * always holds the page locked.
1090c97a9e10SNick Piggin 	 *
1091c97a9e10SNick Piggin 	 * We have exclusion against page_add_new_anon_rmap because those pages
1092c97a9e10SNick Piggin 	 * are initially only visible via the pagetables, and the pte is locked
1093c97a9e10SNick Piggin 	 * over the call to page_add_new_anon_rmap.
1094c97a9e10SNick Piggin 	 */
109530c46382SYang Shi 	VM_BUG_ON_PAGE(page_anon_vma(page)->root != vma->anon_vma->root, page);
109630c46382SYang Shi 	VM_BUG_ON_PAGE(page_to_pgoff(page) != linear_page_index(vma, address),
109730c46382SYang Shi 		       page);
1098c97a9e10SNick Piggin }
1099c97a9e10SNick Piggin 
1100c97a9e10SNick Piggin /**
11019617d95eSNick Piggin  * page_add_anon_rmap - add pte mapping to an anonymous page
11029617d95eSNick Piggin  * @page:	the page to add the mapping to
11039617d95eSNick Piggin  * @vma:	the vm area in which the mapping is added
11049617d95eSNick Piggin  * @address:	the user virtual address mapped
1105d281ee61SKirill A. Shutemov  * @compound:	charge the page as compound or small page
11069617d95eSNick Piggin  *
11075ad64688SHugh Dickins  * The caller needs to hold the pte lock, and the page must be locked in
110880e14822SHugh Dickins  * the anon_vma case: to serialize mapping,index checking after setting,
110980e14822SHugh Dickins  * and to ensure that PageAnon is not being upgraded racily to PageKsm
111080e14822SHugh Dickins  * (but PageKsm is never downgraded to PageAnon).
11119617d95eSNick Piggin  */
11129617d95eSNick Piggin void page_add_anon_rmap(struct page *page,
1113d281ee61SKirill A. Shutemov 	struct vm_area_struct *vma, unsigned long address, bool compound)
11149617d95eSNick Piggin {
1115d281ee61SKirill A. Shutemov 	do_page_add_anon_rmap(page, vma, address, compound ? RMAP_COMPOUND : 0);
1116ad8c2ee8SRik van Riel }
1117ad8c2ee8SRik van Riel 
1118ad8c2ee8SRik van Riel /*
1119ad8c2ee8SRik van Riel  * Special version of the above for do_swap_page, which often runs
1120ad8c2ee8SRik van Riel  * into pages that are exclusively owned by the current process.
1121ad8c2ee8SRik van Riel  * Everybody else should continue to use page_add_anon_rmap above.
1122ad8c2ee8SRik van Riel  */
1123ad8c2ee8SRik van Riel void do_page_add_anon_rmap(struct page *page,
1124d281ee61SKirill A. Shutemov 	struct vm_area_struct *vma, unsigned long address, int flags)
1125ad8c2ee8SRik van Riel {
1126d281ee61SKirill A. Shutemov 	bool compound = flags & RMAP_COMPOUND;
112753f9263bSKirill A. Shutemov 	bool first;
112853f9263bSKirill A. Shutemov 
1129be5d0a74SJohannes Weiner 	if (unlikely(PageKsm(page)))
1130be5d0a74SJohannes Weiner 		lock_page_memcg(page);
1131be5d0a74SJohannes Weiner 	else
1132be5d0a74SJohannes Weiner 		VM_BUG_ON_PAGE(!PageLocked(page), page);
1133be5d0a74SJohannes Weiner 
113453f9263bSKirill A. Shutemov 	if (compound) {
113553f9263bSKirill A. Shutemov 		atomic_t *mapcount;
1136e9b61f19SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
113753f9263bSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageTransHuge(page), page);
113853f9263bSKirill A. Shutemov 		mapcount = compound_mapcount_ptr(page);
113953f9263bSKirill A. Shutemov 		first = atomic_inc_and_test(mapcount);
114053f9263bSKirill A. Shutemov 	} else {
114153f9263bSKirill A. Shutemov 		first = atomic_inc_and_test(&page->_mapcount);
114253f9263bSKirill A. Shutemov 	}
114353f9263bSKirill A. Shutemov 
114453f9263bSKirill A. Shutemov 	if (first) {
11456c357848SMatthew Wilcox (Oracle) 		int nr = compound ? thp_nr_pages(page) : 1;
1146bea04b07SJianyu Zhan 		/*
1147bea04b07SJianyu Zhan 		 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1148bea04b07SJianyu Zhan 		 * these counters are not modified in interrupt context, and
1149bea04b07SJianyu Zhan 		 * pte lock(a spinlock) is held, which implies preemption
1150bea04b07SJianyu Zhan 		 * disabled.
1151bea04b07SJianyu Zhan 		 */
115265c45377SKirill A. Shutemov 		if (compound)
115369473e5dSMuchun Song 			__mod_lruvec_page_state(page, NR_ANON_THPS, nr);
1154be5d0a74SJohannes Weiner 		__mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
115579134171SAndrea Arcangeli 	}
11565ad64688SHugh Dickins 
1157be5d0a74SJohannes Weiner 	if (unlikely(PageKsm(page))) {
1158be5d0a74SJohannes Weiner 		unlock_page_memcg(page);
1159be5d0a74SJohannes Weiner 		return;
1160be5d0a74SJohannes Weiner 	}
116153f9263bSKirill A. Shutemov 
11625dbe0af4SHugh Dickins 	/* address might be in next vma when migration races vma_adjust */
11635ad64688SHugh Dickins 	if (first)
1164d281ee61SKirill A. Shutemov 		__page_set_anon_rmap(page, vma, address,
1165d281ee61SKirill A. Shutemov 				flags & RMAP_EXCLUSIVE);
116669029cd5SKAMEZAWA Hiroyuki 	else
1167c97a9e10SNick Piggin 		__page_check_anon_rmap(page, vma, address);
11681da177e4SLinus Torvalds }
11691da177e4SLinus Torvalds 
117043d8eac4SRandy Dunlap /**
11719617d95eSNick Piggin  * page_add_new_anon_rmap - add pte mapping to a new anonymous page
11729617d95eSNick Piggin  * @page:	the page to add the mapping to
11739617d95eSNick Piggin  * @vma:	the vm area in which the mapping is added
11749617d95eSNick Piggin  * @address:	the user virtual address mapped
1175d281ee61SKirill A. Shutemov  * @compound:	charge the page as compound or small page
11769617d95eSNick Piggin  *
11779617d95eSNick Piggin  * Same as page_add_anon_rmap but must only be called on *new* pages.
11789617d95eSNick Piggin  * This means the inc-and-test can be bypassed.
1179c97a9e10SNick Piggin  * Page does not have to be locked.
11809617d95eSNick Piggin  */
11819617d95eSNick Piggin void page_add_new_anon_rmap(struct page *page,
1182d281ee61SKirill A. Shutemov 	struct vm_area_struct *vma, unsigned long address, bool compound)
11839617d95eSNick Piggin {
11846c357848SMatthew Wilcox (Oracle) 	int nr = compound ? thp_nr_pages(page) : 1;
1185d281ee61SKirill A. Shutemov 
118681d1b09cSSasha Levin 	VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
1187fa9949daSHugh Dickins 	__SetPageSwapBacked(page);
1188d281ee61SKirill A. Shutemov 	if (compound) {
1189d281ee61SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageTransHuge(page), page);
119053f9263bSKirill A. Shutemov 		/* increment count (starts at -1) */
119153f9263bSKirill A. Shutemov 		atomic_set(compound_mapcount_ptr(page), 0);
119247e29d32SJohn Hubbard 		if (hpage_pincount_available(page))
119347e29d32SJohn Hubbard 			atomic_set(compound_pincount_ptr(page), 0);
119447e29d32SJohn Hubbard 
119569473e5dSMuchun Song 		__mod_lruvec_page_state(page, NR_ANON_THPS, nr);
119653f9263bSKirill A. Shutemov 	} else {
119753f9263bSKirill A. Shutemov 		/* Anon THP always mapped first with PMD */
119853f9263bSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageTransCompound(page), page);
119953f9263bSKirill A. Shutemov 		/* increment count (starts at -1) */
120053f9263bSKirill A. Shutemov 		atomic_set(&page->_mapcount, 0);
1201d281ee61SKirill A. Shutemov 	}
1202be5d0a74SJohannes Weiner 	__mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
1203e8a03febSRik van Riel 	__page_set_anon_rmap(page, vma, address, 1);
12049617d95eSNick Piggin }
12059617d95eSNick Piggin 
12061da177e4SLinus Torvalds /**
12071da177e4SLinus Torvalds  * page_add_file_rmap - add pte mapping to a file page
12081da177e4SLinus Torvalds  * @page: the page to add the mapping to
1209e8b098fcSMike Rapoport  * @compound: charge the page as compound or small page
12101da177e4SLinus Torvalds  *
1211b8072f09SHugh Dickins  * The caller needs to hold the pte lock.
12121da177e4SLinus Torvalds  */
1213dd78feddSKirill A. Shutemov void page_add_file_rmap(struct page *page, bool compound)
12141da177e4SLinus Torvalds {
1215dd78feddSKirill A. Shutemov 	int i, nr = 1;
1216dd78feddSKirill A. Shutemov 
1217dd78feddSKirill A. Shutemov 	VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
121862cccb8cSJohannes Weiner 	lock_page_memcg(page);
1219dd78feddSKirill A. Shutemov 	if (compound && PageTransHuge(page)) {
1220a1528e21SMuchun Song 		int nr_pages = thp_nr_pages(page);
1221a1528e21SMuchun Song 
1222a1528e21SMuchun Song 		for (i = 0, nr = 0; i < nr_pages; i++) {
1223dd78feddSKirill A. Shutemov 			if (atomic_inc_and_test(&page[i]._mapcount))
1224dd78feddSKirill A. Shutemov 				nr++;
1225d69b042fSBalbir Singh 		}
1226dd78feddSKirill A. Shutemov 		if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
1227dd78feddSKirill A. Shutemov 			goto out;
122899cb0dbdSSong Liu 		if (PageSwapBacked(page))
1229a1528e21SMuchun Song 			__mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1230a1528e21SMuchun Song 						nr_pages);
123199cb0dbdSSong Liu 		else
1232380780e7SMuchun Song 			__mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1233380780e7SMuchun Song 						nr_pages);
1234dd78feddSKirill A. Shutemov 	} else {
1235c8efc390SKirill A. Shutemov 		if (PageTransCompound(page) && page_mapping(page)) {
1236c8efc390SKirill A. Shutemov 			VM_WARN_ON_ONCE(!PageLocked(page));
1237c8efc390SKirill A. Shutemov 
12389a73f61bSKirill A. Shutemov 			SetPageDoubleMap(compound_head(page));
12399a73f61bSKirill A. Shutemov 			if (PageMlocked(page))
12409a73f61bSKirill A. Shutemov 				clear_page_mlock(compound_head(page));
12419a73f61bSKirill A. Shutemov 		}
1242dd78feddSKirill A. Shutemov 		if (!atomic_inc_and_test(&page->_mapcount))
1243dd78feddSKirill A. Shutemov 			goto out;
1244dd78feddSKirill A. Shutemov 	}
124500f3ca2cSJohannes Weiner 	__mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
1246dd78feddSKirill A. Shutemov out:
124762cccb8cSJohannes Weiner 	unlock_page_memcg(page);
12481da177e4SLinus Torvalds }
12491da177e4SLinus Torvalds 
1250dd78feddSKirill A. Shutemov static void page_remove_file_rmap(struct page *page, bool compound)
12518186eb6aSJohannes Weiner {
1252dd78feddSKirill A. Shutemov 	int i, nr = 1;
1253dd78feddSKirill A. Shutemov 
125457dea93aSSteve Capper 	VM_BUG_ON_PAGE(compound && !PageHead(page), page);
12558186eb6aSJohannes Weiner 
125653f9263bSKirill A. Shutemov 	/* Hugepages are not counted in NR_FILE_MAPPED for now. */
125753f9263bSKirill A. Shutemov 	if (unlikely(PageHuge(page))) {
125853f9263bSKirill A. Shutemov 		/* hugetlb pages are always mapped with pmds */
125953f9263bSKirill A. Shutemov 		atomic_dec(compound_mapcount_ptr(page));
1260be5d0a74SJohannes Weiner 		return;
126153f9263bSKirill A. Shutemov 	}
126253f9263bSKirill A. Shutemov 
12638186eb6aSJohannes Weiner 	/* page still mapped by someone else? */
1264dd78feddSKirill A. Shutemov 	if (compound && PageTransHuge(page)) {
1265a1528e21SMuchun Song 		int nr_pages = thp_nr_pages(page);
1266a1528e21SMuchun Song 
1267a1528e21SMuchun Song 		for (i = 0, nr = 0; i < nr_pages; i++) {
1268dd78feddSKirill A. Shutemov 			if (atomic_add_negative(-1, &page[i]._mapcount))
1269dd78feddSKirill A. Shutemov 				nr++;
1270dd78feddSKirill A. Shutemov 		}
1271dd78feddSKirill A. Shutemov 		if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1272be5d0a74SJohannes Weiner 			return;
127399cb0dbdSSong Liu 		if (PageSwapBacked(page))
1274a1528e21SMuchun Song 			__mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1275a1528e21SMuchun Song 						-nr_pages);
127699cb0dbdSSong Liu 		else
1277380780e7SMuchun Song 			__mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1278380780e7SMuchun Song 						-nr_pages);
1279dd78feddSKirill A. Shutemov 	} else {
12808186eb6aSJohannes Weiner 		if (!atomic_add_negative(-1, &page->_mapcount))
1281be5d0a74SJohannes Weiner 			return;
1282dd78feddSKirill A. Shutemov 	}
12838186eb6aSJohannes Weiner 
12848186eb6aSJohannes Weiner 	/*
128500f3ca2cSJohannes Weiner 	 * We use the irq-unsafe __{inc|mod}_lruvec_page_state because
12868186eb6aSJohannes Weiner 	 * these counters are not modified in interrupt context, and
12878186eb6aSJohannes Weiner 	 * pte lock(a spinlock) is held, which implies preemption disabled.
12888186eb6aSJohannes Weiner 	 */
128900f3ca2cSJohannes Weiner 	__mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
12908186eb6aSJohannes Weiner 
12918186eb6aSJohannes Weiner 	if (unlikely(PageMlocked(page)))
12928186eb6aSJohannes Weiner 		clear_page_mlock(page);
12938186eb6aSJohannes Weiner }
12948186eb6aSJohannes Weiner 
129553f9263bSKirill A. Shutemov static void page_remove_anon_compound_rmap(struct page *page)
129653f9263bSKirill A. Shutemov {
129753f9263bSKirill A. Shutemov 	int i, nr;
129853f9263bSKirill A. Shutemov 
129953f9263bSKirill A. Shutemov 	if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
130053f9263bSKirill A. Shutemov 		return;
130153f9263bSKirill A. Shutemov 
130253f9263bSKirill A. Shutemov 	/* Hugepages are not counted in NR_ANON_PAGES for now. */
130353f9263bSKirill A. Shutemov 	if (unlikely(PageHuge(page)))
130453f9263bSKirill A. Shutemov 		return;
130553f9263bSKirill A. Shutemov 
130653f9263bSKirill A. Shutemov 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
130753f9263bSKirill A. Shutemov 		return;
130853f9263bSKirill A. Shutemov 
130969473e5dSMuchun Song 	__mod_lruvec_page_state(page, NR_ANON_THPS, -thp_nr_pages(page));
131053f9263bSKirill A. Shutemov 
131153f9263bSKirill A. Shutemov 	if (TestClearPageDoubleMap(page)) {
131253f9263bSKirill A. Shutemov 		/*
131353f9263bSKirill A. Shutemov 		 * Subpages can be mapped with PTEs too. Check how many of
1314f1fe80d4SKirill A. Shutemov 		 * them are still mapped.
131553f9263bSKirill A. Shutemov 		 */
13165eaf35abSMatthew Wilcox (Oracle) 		for (i = 0, nr = 0; i < thp_nr_pages(page); i++) {
131753f9263bSKirill A. Shutemov 			if (atomic_add_negative(-1, &page[i]._mapcount))
131853f9263bSKirill A. Shutemov 				nr++;
131953f9263bSKirill A. Shutemov 		}
1320f1fe80d4SKirill A. Shutemov 
1321f1fe80d4SKirill A. Shutemov 		/*
1322f1fe80d4SKirill A. Shutemov 		 * Queue the page for deferred split if at least one small
1323f1fe80d4SKirill A. Shutemov 		 * page of the compound page is unmapped, but at least one
1324f1fe80d4SKirill A. Shutemov 		 * small page is still mapped.
1325f1fe80d4SKirill A. Shutemov 		 */
13265eaf35abSMatthew Wilcox (Oracle) 		if (nr && nr < thp_nr_pages(page))
1327f1fe80d4SKirill A. Shutemov 			deferred_split_huge_page(page);
132853f9263bSKirill A. Shutemov 	} else {
13295eaf35abSMatthew Wilcox (Oracle) 		nr = thp_nr_pages(page);
133053f9263bSKirill A. Shutemov 	}
133153f9263bSKirill A. Shutemov 
1332e90309c9SKirill A. Shutemov 	if (unlikely(PageMlocked(page)))
1333e90309c9SKirill A. Shutemov 		clear_page_mlock(page);
1334e90309c9SKirill A. Shutemov 
1335f1fe80d4SKirill A. Shutemov 	if (nr)
1336be5d0a74SJohannes Weiner 		__mod_lruvec_page_state(page, NR_ANON_MAPPED, -nr);
133753f9263bSKirill A. Shutemov }
133853f9263bSKirill A. Shutemov 
13391da177e4SLinus Torvalds /**
13401da177e4SLinus Torvalds  * page_remove_rmap - take down pte mapping from a page
13411da177e4SLinus Torvalds  * @page:	page to remove mapping from
1342d281ee61SKirill A. Shutemov  * @compound:	uncharge the page as compound or small page
13431da177e4SLinus Torvalds  *
1344b8072f09SHugh Dickins  * The caller needs to hold the pte lock.
13451da177e4SLinus Torvalds  */
1346d281ee61SKirill A. Shutemov void page_remove_rmap(struct page *page, bool compound)
13471da177e4SLinus Torvalds {
1348be5d0a74SJohannes Weiner 	lock_page_memcg(page);
134989c06bd5SKAMEZAWA Hiroyuki 
1350be5d0a74SJohannes Weiner 	if (!PageAnon(page)) {
1351be5d0a74SJohannes Weiner 		page_remove_file_rmap(page, compound);
1352be5d0a74SJohannes Weiner 		goto out;
1353be5d0a74SJohannes Weiner 	}
1354be5d0a74SJohannes Weiner 
1355be5d0a74SJohannes Weiner 	if (compound) {
1356be5d0a74SJohannes Weiner 		page_remove_anon_compound_rmap(page);
1357be5d0a74SJohannes Weiner 		goto out;
1358be5d0a74SJohannes Weiner 	}
135953f9263bSKirill A. Shutemov 
1360b904dcfeSKOSAKI Motohiro 	/* page still mapped by someone else? */
1361b904dcfeSKOSAKI Motohiro 	if (!atomic_add_negative(-1, &page->_mapcount))
1362be5d0a74SJohannes Weiner 		goto out;
13638186eb6aSJohannes Weiner 
13641da177e4SLinus Torvalds 	/*
1365bea04b07SJianyu Zhan 	 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1366bea04b07SJianyu Zhan 	 * these counters are not modified in interrupt context, and
1367bea04b07SJianyu Zhan 	 * pte lock(a spinlock) is held, which implies preemption disabled.
13680fe6e20bSNaoya Horiguchi 	 */
1369be5d0a74SJohannes Weiner 	__dec_lruvec_page_state(page, NR_ANON_MAPPED);
13708186eb6aSJohannes Weiner 
1371e6c509f8SHugh Dickins 	if (unlikely(PageMlocked(page)))
1372e6c509f8SHugh Dickins 		clear_page_mlock(page);
13738186eb6aSJohannes Weiner 
13749a982250SKirill A. Shutemov 	if (PageTransCompound(page))
13759a982250SKirill A. Shutemov 		deferred_split_huge_page(compound_head(page));
13769a982250SKirill A. Shutemov 
137716f8c5b2SHugh Dickins 	/*
13781da177e4SLinus Torvalds 	 * It would be tidy to reset the PageAnon mapping here,
13791da177e4SLinus Torvalds 	 * but that might overwrite a racing page_add_anon_rmap
13801da177e4SLinus Torvalds 	 * which increments mapcount after us but sets mapping
13812d4894b5SMel Gorman 	 * before us: so leave the reset to free_unref_page,
13821da177e4SLinus Torvalds 	 * and remember that it's only reliable while mapped.
13831da177e4SLinus Torvalds 	 * Leaving it set also helps swapoff to reinstate ptes
13841da177e4SLinus Torvalds 	 * faster for those pages still in swapcache.
13851da177e4SLinus Torvalds 	 */
1386be5d0a74SJohannes Weiner out:
1387be5d0a74SJohannes Weiner 	unlock_page_memcg(page);
13881da177e4SLinus Torvalds }
13891da177e4SLinus Torvalds 
13901da177e4SLinus Torvalds /*
139152629506SJoonsoo Kim  * @arg: enum ttu_flags will be passed to this argument
13921da177e4SLinus Torvalds  */
1393e4b82222SMinchan Kim static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,
139452629506SJoonsoo Kim 		     unsigned long address, void *arg)
13951da177e4SLinus Torvalds {
13961da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
1397c7ab0d2fSKirill A. Shutemov 	struct page_vma_mapped_walk pvmw = {
1398c7ab0d2fSKirill A. Shutemov 		.page = page,
1399c7ab0d2fSKirill A. Shutemov 		.vma = vma,
1400c7ab0d2fSKirill A. Shutemov 		.address = address,
1401c7ab0d2fSKirill A. Shutemov 	};
14021da177e4SLinus Torvalds 	pte_t pteval;
1403c7ab0d2fSKirill A. Shutemov 	struct page *subpage;
1404785373b4SLinus Torvalds 	bool ret = true;
1405ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
14064708f318SPalmer Dabbelt 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
14071da177e4SLinus Torvalds 
1408b87537d9SHugh Dickins 	/* munlock has nothing to gain from examining un-locked vmas */
1409b87537d9SHugh Dickins 	if ((flags & TTU_MUNLOCK) && !(vma->vm_flags & VM_LOCKED))
1410e4b82222SMinchan Kim 		return true;
1411b87537d9SHugh Dickins 
1412a5430ddaSJérôme Glisse 	if (IS_ENABLED(CONFIG_MIGRATION) && (flags & TTU_MIGRATION) &&
1413a5430ddaSJérôme Glisse 	    is_zone_device_page(page) && !is_device_private_page(page))
1414a5430ddaSJérôme Glisse 		return true;
1415a5430ddaSJérôme Glisse 
1416fec89c10SKirill A. Shutemov 	if (flags & TTU_SPLIT_HUGE_PMD) {
1417fec89c10SKirill A. Shutemov 		split_huge_pmd_address(vma, address,
1418b5ff8161SNaoya Horiguchi 				flags & TTU_SPLIT_FREEZE, page);
1419fec89c10SKirill A. Shutemov 	}
1420fec89c10SKirill A. Shutemov 
1421369ea824SJérôme Glisse 	/*
1422017b1660SMike Kravetz 	 * For THP, we have to assume the worse case ie pmd for invalidation.
1423017b1660SMike Kravetz 	 * For hugetlb, it could be much worse if we need to do pud
1424017b1660SMike Kravetz 	 * invalidation in the case of pmd sharing.
1425017b1660SMike Kravetz 	 *
1426017b1660SMike Kravetz 	 * Note that the page can not be free in this function as call of
1427017b1660SMike Kravetz 	 * try_to_unmap() must hold a reference on the page.
1428369ea824SJérôme Glisse 	 */
14297269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
14306f4f13e8SJérôme Glisse 				address,
1431a50b854eSMatthew Wilcox (Oracle) 				min(vma->vm_end, address + page_size(page)));
1432017b1660SMike Kravetz 	if (PageHuge(page)) {
1433017b1660SMike Kravetz 		/*
1434017b1660SMike Kravetz 		 * If sharing is possible, start and end will be adjusted
1435017b1660SMike Kravetz 		 * accordingly.
1436017b1660SMike Kravetz 		 */
1437ac46d4f3SJérôme Glisse 		adjust_range_if_pmd_sharing_possible(vma, &range.start,
1438ac46d4f3SJérôme Glisse 						     &range.end);
1439017b1660SMike Kravetz 	}
1440ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
1441369ea824SJérôme Glisse 
1442c7ab0d2fSKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
1443616b8371SZi Yan #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1444616b8371SZi Yan 		/* PMD-mapped THP migration entry */
1445616b8371SZi Yan 		if (!pvmw.pte && (flags & TTU_MIGRATION)) {
1446616b8371SZi Yan 			VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
1447616b8371SZi Yan 
1448616b8371SZi Yan 			set_pmd_migration_entry(&pvmw, page);
1449616b8371SZi Yan 			continue;
1450616b8371SZi Yan 		}
1451616b8371SZi Yan #endif
1452616b8371SZi Yan 
14531da177e4SLinus Torvalds 		/*
14541da177e4SLinus Torvalds 		 * If the page is mlock()d, we cannot swap it out.
14551da177e4SLinus Torvalds 		 * If it's recently referenced (perhaps page_referenced
14561da177e4SLinus Torvalds 		 * skipped over this mm) then we should reactivate it.
14571da177e4SLinus Torvalds 		 */
145814fa31b8SAndi Kleen 		if (!(flags & TTU_IGNORE_MLOCK)) {
1459b87537d9SHugh Dickins 			if (vma->vm_flags & VM_LOCKED) {
14609a73f61bSKirill A. Shutemov 				/* PTE-mapped THP are never mlocked */
14619a73f61bSKirill A. Shutemov 				if (!PageTransCompound(page)) {
14629a73f61bSKirill A. Shutemov 					/*
14639a73f61bSKirill A. Shutemov 					 * Holding pte lock, we do *not* need
1464c1e8d7c6SMichel Lespinasse 					 * mmap_lock here
14659a73f61bSKirill A. Shutemov 					 */
1466b87537d9SHugh Dickins 					mlock_vma_page(page);
14679a73f61bSKirill A. Shutemov 				}
1468e4b82222SMinchan Kim 				ret = false;
1469c7ab0d2fSKirill A. Shutemov 				page_vma_mapped_walk_done(&pvmw);
1470c7ab0d2fSKirill A. Shutemov 				break;
1471b87537d9SHugh Dickins 			}
1472daa5ba76SKonstantin Khlebnikov 			if (flags & TTU_MUNLOCK)
1473c7ab0d2fSKirill A. Shutemov 				continue;
147414fa31b8SAndi Kleen 		}
1475c7ab0d2fSKirill A. Shutemov 
14768346242aSKirill A. Shutemov 		/* Unexpected PMD-mapped THP? */
14778346242aSKirill A. Shutemov 		VM_BUG_ON_PAGE(!pvmw.pte, page);
14788346242aSKirill A. Shutemov 
14798346242aSKirill A. Shutemov 		subpage = page - page_to_pfn(page) + pte_pfn(*pvmw.pte);
1480785373b4SLinus Torvalds 		address = pvmw.address;
1481785373b4SLinus Torvalds 
1482336bf30eSMike Kravetz 		if (PageHuge(page) && !PageAnon(page)) {
1483c0d0381aSMike Kravetz 			/*
1484c0d0381aSMike Kravetz 			 * To call huge_pmd_unshare, i_mmap_rwsem must be
1485c0d0381aSMike Kravetz 			 * held in write mode.  Caller needs to explicitly
1486c0d0381aSMike Kravetz 			 * do this outside rmap routines.
1487c0d0381aSMike Kravetz 			 */
1488c0d0381aSMike Kravetz 			VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
148934ae204fSMike Kravetz 			if (huge_pmd_unshare(mm, vma, &address, pvmw.pte)) {
1490017b1660SMike Kravetz 				/*
1491017b1660SMike Kravetz 				 * huge_pmd_unshare unmapped an entire PMD
1492017b1660SMike Kravetz 				 * page.  There is no way of knowing exactly
1493017b1660SMike Kravetz 				 * which PMDs may be cached for this mm, so
1494017b1660SMike Kravetz 				 * we must flush them all.  start/end were
1495017b1660SMike Kravetz 				 * already adjusted above to cover this range.
1496017b1660SMike Kravetz 				 */
1497ac46d4f3SJérôme Glisse 				flush_cache_range(vma, range.start, range.end);
1498ac46d4f3SJérôme Glisse 				flush_tlb_range(vma, range.start, range.end);
1499ac46d4f3SJérôme Glisse 				mmu_notifier_invalidate_range(mm, range.start,
1500ac46d4f3SJérôme Glisse 							      range.end);
1501017b1660SMike Kravetz 
1502017b1660SMike Kravetz 				/*
1503017b1660SMike Kravetz 				 * The ref count of the PMD page was dropped
1504017b1660SMike Kravetz 				 * which is part of the way map counting
1505017b1660SMike Kravetz 				 * is done for shared PMDs.  Return 'true'
1506017b1660SMike Kravetz 				 * here.  When there is no other sharing,
1507017b1660SMike Kravetz 				 * huge_pmd_unshare returns false and we will
1508017b1660SMike Kravetz 				 * unmap the actual page and drop map count
1509017b1660SMike Kravetz 				 * to zero.
1510017b1660SMike Kravetz 				 */
1511017b1660SMike Kravetz 				page_vma_mapped_walk_done(&pvmw);
1512017b1660SMike Kravetz 				break;
1513017b1660SMike Kravetz 			}
1514017b1660SMike Kravetz 		}
15158346242aSKirill A. Shutemov 
1516a5430ddaSJérôme Glisse 		if (IS_ENABLED(CONFIG_MIGRATION) &&
1517a5430ddaSJérôme Glisse 		    (flags & TTU_MIGRATION) &&
1518a5430ddaSJérôme Glisse 		    is_zone_device_page(page)) {
1519a5430ddaSJérôme Glisse 			swp_entry_t entry;
1520a5430ddaSJérôme Glisse 			pte_t swp_pte;
1521a5430ddaSJérôme Glisse 
1522a5430ddaSJérôme Glisse 			pteval = ptep_get_and_clear(mm, pvmw.address, pvmw.pte);
1523a5430ddaSJérôme Glisse 
1524a5430ddaSJérôme Glisse 			/*
1525a5430ddaSJérôme Glisse 			 * Store the pfn of the page in a special migration
1526a5430ddaSJérôme Glisse 			 * pte. do_swap_page() will wait until the migration
1527a5430ddaSJérôme Glisse 			 * pte is removed and then restart fault handling.
1528a5430ddaSJérôme Glisse 			 */
1529a5430ddaSJérôme Glisse 			entry = make_migration_entry(page, 0);
1530a5430ddaSJérôme Glisse 			swp_pte = swp_entry_to_pte(entry);
1531ad7df764SAlistair Popple 
1532ad7df764SAlistair Popple 			/*
1533ad7df764SAlistair Popple 			 * pteval maps a zone device page and is therefore
1534ad7df764SAlistair Popple 			 * a swap pte.
1535ad7df764SAlistair Popple 			 */
1536ad7df764SAlistair Popple 			if (pte_swp_soft_dirty(pteval))
1537a5430ddaSJérôme Glisse 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1538ad7df764SAlistair Popple 			if (pte_swp_uffd_wp(pteval))
1539f45ec5ffSPeter Xu 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
1540a5430ddaSJérôme Glisse 			set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
15410f10851eSJérôme Glisse 			/*
15420f10851eSJérôme Glisse 			 * No need to invalidate here it will synchronize on
15430f10851eSJérôme Glisse 			 * against the special swap migration pte.
15441de13ee5SRalph Campbell 			 *
15451de13ee5SRalph Campbell 			 * The assignment to subpage above was computed from a
15461de13ee5SRalph Campbell 			 * swap PTE which results in an invalid pointer.
15471de13ee5SRalph Campbell 			 * Since only PAGE_SIZE pages can currently be
15481de13ee5SRalph Campbell 			 * migrated, just set it to page. This will need to be
15491de13ee5SRalph Campbell 			 * changed when hugepage migrations to device private
15501de13ee5SRalph Campbell 			 * memory are supported.
15510f10851eSJérôme Glisse 			 */
15521de13ee5SRalph Campbell 			subpage = page;
1553a5430ddaSJérôme Glisse 			goto discard;
1554a5430ddaSJérôme Glisse 		}
1555a5430ddaSJérôme Glisse 
15561da177e4SLinus Torvalds 		/* Nuke the page table entry. */
1557785373b4SLinus Torvalds 		flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
155872b252aeSMel Gorman 		if (should_defer_flush(mm, flags)) {
155972b252aeSMel Gorman 			/*
1560c7ab0d2fSKirill A. Shutemov 			 * We clear the PTE but do not flush so potentially
1561c7ab0d2fSKirill A. Shutemov 			 * a remote CPU could still be writing to the page.
1562c7ab0d2fSKirill A. Shutemov 			 * If the entry was previously clean then the
1563c7ab0d2fSKirill A. Shutemov 			 * architecture must guarantee that a clear->dirty
1564c7ab0d2fSKirill A. Shutemov 			 * transition on a cached TLB entry is written through
1565c7ab0d2fSKirill A. Shutemov 			 * and traps if the PTE is unmapped.
156672b252aeSMel Gorman 			 */
1567785373b4SLinus Torvalds 			pteval = ptep_get_and_clear(mm, address, pvmw.pte);
156872b252aeSMel Gorman 
1569c7ab0d2fSKirill A. Shutemov 			set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
157072b252aeSMel Gorman 		} else {
1571785373b4SLinus Torvalds 			pteval = ptep_clear_flush(vma, address, pvmw.pte);
157272b252aeSMel Gorman 		}
15731da177e4SLinus Torvalds 
1574c7ab0d2fSKirill A. Shutemov 		/* Move the dirty bit to the page. Now the pte is gone. */
15751da177e4SLinus Torvalds 		if (pte_dirty(pteval))
15761da177e4SLinus Torvalds 			set_page_dirty(page);
15771da177e4SLinus Torvalds 
1578365e9c87SHugh Dickins 		/* Update high watermark before we lower rss */
1579365e9c87SHugh Dickins 		update_hiwater_rss(mm);
1580365e9c87SHugh Dickins 
1581888b9f7cSAndi Kleen 		if (PageHWPoison(page) && !(flags & TTU_IGNORE_HWPOISON)) {
15825fd27b8eSPunit Agrawal 			pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
15835d317b2bSNaoya Horiguchi 			if (PageHuge(page)) {
1584d8c6546bSMatthew Wilcox (Oracle) 				hugetlb_count_sub(compound_nr(page), mm);
1585785373b4SLinus Torvalds 				set_huge_swap_pte_at(mm, address,
15865fd27b8eSPunit Agrawal 						     pvmw.pte, pteval,
15875fd27b8eSPunit Agrawal 						     vma_mmu_pagesize(vma));
15885d317b2bSNaoya Horiguchi 			} else {
1589eca56ff9SJerome Marchand 				dec_mm_counter(mm, mm_counter(page));
1590785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
15915f24ae58SNaoya Horiguchi 			}
1592c7ab0d2fSKirill A. Shutemov 
1593bce73e48SChristian Borntraeger 		} else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
159445961722SKonstantin Weitz 			/*
159545961722SKonstantin Weitz 			 * The guest indicated that the page content is of no
159645961722SKonstantin Weitz 			 * interest anymore. Simply discard the pte, vmscan
159745961722SKonstantin Weitz 			 * will take care of the rest.
1598bce73e48SChristian Borntraeger 			 * A future reference will then fault in a new zero
1599bce73e48SChristian Borntraeger 			 * page. When userfaultfd is active, we must not drop
1600bce73e48SChristian Borntraeger 			 * this page though, as its main user (postcopy
1601bce73e48SChristian Borntraeger 			 * migration) will not expect userfaults on already
1602bce73e48SChristian Borntraeger 			 * copied pages.
160345961722SKonstantin Weitz 			 */
1604eca56ff9SJerome Marchand 			dec_mm_counter(mm, mm_counter(page));
16050f10851eSJérôme Glisse 			/* We have to invalidate as we cleared the pte */
16060f10851eSJérôme Glisse 			mmu_notifier_invalidate_range(mm, address,
16070f10851eSJérôme Glisse 						      address + PAGE_SIZE);
1608c7ab0d2fSKirill A. Shutemov 		} else if (IS_ENABLED(CONFIG_MIGRATION) &&
1609b5ff8161SNaoya Horiguchi 				(flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))) {
1610470f119fSHugh Dickins 			swp_entry_t entry;
1611470f119fSHugh Dickins 			pte_t swp_pte;
1612ca827d55SKhalid Aziz 
1613ca827d55SKhalid Aziz 			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1614ca827d55SKhalid Aziz 				set_pte_at(mm, address, pvmw.pte, pteval);
1615ca827d55SKhalid Aziz 				ret = false;
1616ca827d55SKhalid Aziz 				page_vma_mapped_walk_done(&pvmw);
1617ca827d55SKhalid Aziz 				break;
1618ca827d55SKhalid Aziz 			}
1619ca827d55SKhalid Aziz 
1620470f119fSHugh Dickins 			/*
1621470f119fSHugh Dickins 			 * Store the pfn of the page in a special migration
1622470f119fSHugh Dickins 			 * pte. do_swap_page() will wait until the migration
1623470f119fSHugh Dickins 			 * pte is removed and then restart fault handling.
1624470f119fSHugh Dickins 			 */
1625c7ab0d2fSKirill A. Shutemov 			entry = make_migration_entry(subpage,
1626c7ab0d2fSKirill A. Shutemov 					pte_write(pteval));
1627470f119fSHugh Dickins 			swp_pte = swp_entry_to_pte(entry);
1628470f119fSHugh Dickins 			if (pte_soft_dirty(pteval))
1629470f119fSHugh Dickins 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1630f45ec5ffSPeter Xu 			if (pte_uffd_wp(pteval))
1631f45ec5ffSPeter Xu 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
1632785373b4SLinus Torvalds 			set_pte_at(mm, address, pvmw.pte, swp_pte);
16330f10851eSJérôme Glisse 			/*
16340f10851eSJérôme Glisse 			 * No need to invalidate here it will synchronize on
16350f10851eSJérôme Glisse 			 * against the special swap migration pte.
16360f10851eSJérôme Glisse 			 */
1637888b9f7cSAndi Kleen 		} else if (PageAnon(page)) {
1638c7ab0d2fSKirill A. Shutemov 			swp_entry_t entry = { .val = page_private(subpage) };
1639179ef71cSCyrill Gorcunov 			pte_t swp_pte;
16401da177e4SLinus Torvalds 			/*
16411da177e4SLinus Torvalds 			 * Store the swap location in the pte.
16421da177e4SLinus Torvalds 			 * See handle_pte_fault() ...
16431da177e4SLinus Torvalds 			 */
1644eb94a878SMinchan Kim 			if (unlikely(PageSwapBacked(page) != PageSwapCache(page))) {
1645eb94a878SMinchan Kim 				WARN_ON_ONCE(1);
164683612a94SMinchan Kim 				ret = false;
1647369ea824SJérôme Glisse 				/* We have to invalidate as we cleared the pte */
16480f10851eSJérôme Glisse 				mmu_notifier_invalidate_range(mm, address,
16490f10851eSJérôme Glisse 							address + PAGE_SIZE);
1650eb94a878SMinchan Kim 				page_vma_mapped_walk_done(&pvmw);
1651eb94a878SMinchan Kim 				break;
1652eb94a878SMinchan Kim 			}
1653854e9ed0SMinchan Kim 
1654802a3a92SShaohua Li 			/* MADV_FREE page check */
1655802a3a92SShaohua Li 			if (!PageSwapBacked(page)) {
1656a128ca71SShaohua Li 				if (!PageDirty(page)) {
16570f10851eSJérôme Glisse 					/* Invalidate as we cleared the pte */
16580f10851eSJérôme Glisse 					mmu_notifier_invalidate_range(mm,
16590f10851eSJérôme Glisse 						address, address + PAGE_SIZE);
1660854e9ed0SMinchan Kim 					dec_mm_counter(mm, MM_ANONPAGES);
1661854e9ed0SMinchan Kim 					goto discard;
1662854e9ed0SMinchan Kim 				}
1663854e9ed0SMinchan Kim 
1664802a3a92SShaohua Li 				/*
1665802a3a92SShaohua Li 				 * If the page was redirtied, it cannot be
1666802a3a92SShaohua Li 				 * discarded. Remap the page to page table.
1667802a3a92SShaohua Li 				 */
1668785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
166918863d3aSMinchan Kim 				SetPageSwapBacked(page);
1670e4b82222SMinchan Kim 				ret = false;
1671802a3a92SShaohua Li 				page_vma_mapped_walk_done(&pvmw);
1672802a3a92SShaohua Li 				break;
1673802a3a92SShaohua Li 			}
1674802a3a92SShaohua Li 
1675570a335bSHugh Dickins 			if (swap_duplicate(entry) < 0) {
1676785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
1677e4b82222SMinchan Kim 				ret = false;
1678c7ab0d2fSKirill A. Shutemov 				page_vma_mapped_walk_done(&pvmw);
1679c7ab0d2fSKirill A. Shutemov 				break;
1680570a335bSHugh Dickins 			}
1681ca827d55SKhalid Aziz 			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1682ca827d55SKhalid Aziz 				set_pte_at(mm, address, pvmw.pte, pteval);
1683ca827d55SKhalid Aziz 				ret = false;
1684ca827d55SKhalid Aziz 				page_vma_mapped_walk_done(&pvmw);
1685ca827d55SKhalid Aziz 				break;
1686ca827d55SKhalid Aziz 			}
16871da177e4SLinus Torvalds 			if (list_empty(&mm->mmlist)) {
16881da177e4SLinus Torvalds 				spin_lock(&mmlist_lock);
1689f412ac08SHugh Dickins 				if (list_empty(&mm->mmlist))
16901da177e4SLinus Torvalds 					list_add(&mm->mmlist, &init_mm.mmlist);
16911da177e4SLinus Torvalds 				spin_unlock(&mmlist_lock);
16921da177e4SLinus Torvalds 			}
1693d559db08SKAMEZAWA Hiroyuki 			dec_mm_counter(mm, MM_ANONPAGES);
1694b084d435SKAMEZAWA Hiroyuki 			inc_mm_counter(mm, MM_SWAPENTS);
1695179ef71cSCyrill Gorcunov 			swp_pte = swp_entry_to_pte(entry);
1696179ef71cSCyrill Gorcunov 			if (pte_soft_dirty(pteval))
1697179ef71cSCyrill Gorcunov 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1698f45ec5ffSPeter Xu 			if (pte_uffd_wp(pteval))
1699f45ec5ffSPeter Xu 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
1700785373b4SLinus Torvalds 			set_pte_at(mm, address, pvmw.pte, swp_pte);
17010f10851eSJérôme Glisse 			/* Invalidate as we cleared the pte */
1702369ea824SJérôme Glisse 			mmu_notifier_invalidate_range(mm, address,
1703369ea824SJérôme Glisse 						      address + PAGE_SIZE);
17040f10851eSJérôme Glisse 		} else {
17050f10851eSJérôme Glisse 			/*
1706906f9cdfSHugh Dickins 			 * This is a locked file-backed page, thus it cannot
1707906f9cdfSHugh Dickins 			 * be removed from the page cache and replaced by a new
1708906f9cdfSHugh Dickins 			 * page before mmu_notifier_invalidate_range_end, so no
17090f10851eSJérôme Glisse 			 * concurrent thread might update its page table to
17100f10851eSJérôme Glisse 			 * point at new page while a device still is using this
17110f10851eSJérôme Glisse 			 * page.
17120f10851eSJérôme Glisse 			 *
1713ad56b738SMike Rapoport 			 * See Documentation/vm/mmu_notifier.rst
17140f10851eSJérôme Glisse 			 */
17150f10851eSJérôme Glisse 			dec_mm_counter(mm, mm_counter_file(page));
17160f10851eSJérôme Glisse 		}
17170f10851eSJérôme Glisse discard:
17180f10851eSJérôme Glisse 		/*
17190f10851eSJérôme Glisse 		 * No need to call mmu_notifier_invalidate_range() it has be
17200f10851eSJérôme Glisse 		 * done above for all cases requiring it to happen under page
17210f10851eSJérôme Glisse 		 * table lock before mmu_notifier_invalidate_range_end()
17220f10851eSJérôme Glisse 		 *
1723ad56b738SMike Rapoport 		 * See Documentation/vm/mmu_notifier.rst
17240f10851eSJérôme Glisse 		 */
17250f10851eSJérôme Glisse 		page_remove_rmap(subpage, PageHuge(page));
17260f10851eSJérôme Glisse 		put_page(page);
1727c7ab0d2fSKirill A. Shutemov 	}
1728369ea824SJérôme Glisse 
1729ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
1730369ea824SJérôme Glisse 
1731caed0f48SKOSAKI Motohiro 	return ret;
17321da177e4SLinus Torvalds }
17331da177e4SLinus Torvalds 
173452629506SJoonsoo Kim static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
173552629506SJoonsoo Kim {
1736222100eeSAnshuman Khandual 	return vma_is_temporary_stack(vma);
173752629506SJoonsoo Kim }
173852629506SJoonsoo Kim 
17392a52bcbcSKirill A. Shutemov static int page_mapcount_is_zero(struct page *page)
174052629506SJoonsoo Kim {
1741c7ab0d2fSKirill A. Shutemov 	return !total_mapcount(page);
17422a52bcbcSKirill A. Shutemov }
174352629506SJoonsoo Kim 
17441da177e4SLinus Torvalds /**
17451da177e4SLinus Torvalds  * try_to_unmap - try to remove all page table mappings to a page
17461da177e4SLinus Torvalds  * @page: the page to get unmapped
174714fa31b8SAndi Kleen  * @flags: action and flags
17481da177e4SLinus Torvalds  *
17491da177e4SLinus Torvalds  * Tries to remove all the page table entries which are mapping this
17501da177e4SLinus Torvalds  * page, used in the pageout path.  Caller must hold the page lock.
17511da177e4SLinus Torvalds  *
1752666e5a40SMinchan Kim  * If unmap is successful, return true. Otherwise, false.
17531da177e4SLinus Torvalds  */
1754666e5a40SMinchan Kim bool try_to_unmap(struct page *page, enum ttu_flags flags)
17551da177e4SLinus Torvalds {
175652629506SJoonsoo Kim 	struct rmap_walk_control rwc = {
175752629506SJoonsoo Kim 		.rmap_one = try_to_unmap_one,
1758802a3a92SShaohua Li 		.arg = (void *)flags,
17592a52bcbcSKirill A. Shutemov 		.done = page_mapcount_is_zero,
176052629506SJoonsoo Kim 		.anon_lock = page_lock_anon_vma_read,
176152629506SJoonsoo Kim 	};
17621da177e4SLinus Torvalds 
176352629506SJoonsoo Kim 	/*
176452629506SJoonsoo Kim 	 * During exec, a temporary VMA is setup and later moved.
176552629506SJoonsoo Kim 	 * The VMA is moved under the anon_vma lock but not the
176652629506SJoonsoo Kim 	 * page tables leading to a race where migration cannot
176752629506SJoonsoo Kim 	 * find the migration ptes. Rather than increasing the
176852629506SJoonsoo Kim 	 * locking requirements of exec(), migration skips
176952629506SJoonsoo Kim 	 * temporary VMAs until after exec() completes.
177052629506SJoonsoo Kim 	 */
1771b5ff8161SNaoya Horiguchi 	if ((flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))
1772b5ff8161SNaoya Horiguchi 	    && !PageKsm(page) && PageAnon(page))
177352629506SJoonsoo Kim 		rwc.invalid_vma = invalid_migration_vma;
177452629506SJoonsoo Kim 
17752a52bcbcSKirill A. Shutemov 	if (flags & TTU_RMAP_LOCKED)
177633fc80e2SMinchan Kim 		rmap_walk_locked(page, &rwc);
17772a52bcbcSKirill A. Shutemov 	else
177833fc80e2SMinchan Kim 		rmap_walk(page, &rwc);
177952629506SJoonsoo Kim 
1780666e5a40SMinchan Kim 	return !page_mapcount(page) ? true : false;
17811da177e4SLinus Torvalds }
178281b4082dSNikita Danilov 
17832a52bcbcSKirill A. Shutemov static int page_not_mapped(struct page *page)
17842a52bcbcSKirill A. Shutemov {
17852a52bcbcSKirill A. Shutemov 	return !page_mapped(page);
1786e0af87ffSMiaohe Lin }
17872a52bcbcSKirill A. Shutemov 
1788b291f000SNick Piggin /**
1789b291f000SNick Piggin  * try_to_munlock - try to munlock a page
1790b291f000SNick Piggin  * @page: the page to be munlocked
1791b291f000SNick Piggin  *
1792b291f000SNick Piggin  * Called from munlock code.  Checks all of the VMAs mapping the page
1793b291f000SNick Piggin  * to make sure nobody else has this page mlocked. The page will be
1794b291f000SNick Piggin  * returned with PG_mlocked cleared if no other vmas have it mlocked.
1795b291f000SNick Piggin  */
1796854e9ed0SMinchan Kim 
1797192d7232SMinchan Kim void try_to_munlock(struct page *page)
1798192d7232SMinchan Kim {
1799e8351ac9SJoonsoo Kim 	struct rmap_walk_control rwc = {
1800e8351ac9SJoonsoo Kim 		.rmap_one = try_to_unmap_one,
1801802a3a92SShaohua Li 		.arg = (void *)TTU_MUNLOCK,
1802e8351ac9SJoonsoo Kim 		.done = page_not_mapped,
1803e8351ac9SJoonsoo Kim 		.anon_lock = page_lock_anon_vma_read,
1804e8351ac9SJoonsoo Kim 
1805e8351ac9SJoonsoo Kim 	};
1806e8351ac9SJoonsoo Kim 
1807309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page) || PageLRU(page), page);
1808192d7232SMinchan Kim 	VM_BUG_ON_PAGE(PageCompound(page) && PageDoubleMap(page), page);
1809b291f000SNick Piggin 
1810192d7232SMinchan Kim 	rmap_walk(page, &rwc);
1811b291f000SNick Piggin }
1812e9995ef9SHugh Dickins 
181301d8b20dSPeter Zijlstra void __put_anon_vma(struct anon_vma *anon_vma)
181476545066SRik van Riel {
181576545066SRik van Riel 	struct anon_vma *root = anon_vma->root;
181676545066SRik van Riel 
1817624483f3SAndrey Ryabinin 	anon_vma_free(anon_vma);
181801d8b20dSPeter Zijlstra 	if (root != anon_vma && atomic_dec_and_test(&root->refcount))
181976545066SRik van Riel 		anon_vma_free(root);
182076545066SRik van Riel }
182176545066SRik van Riel 
18220dd1c7bbSJoonsoo Kim static struct anon_vma *rmap_walk_anon_lock(struct page *page,
18230dd1c7bbSJoonsoo Kim 					struct rmap_walk_control *rwc)
1824faecd8ddSJoonsoo Kim {
1825faecd8ddSJoonsoo Kim 	struct anon_vma *anon_vma;
1826faecd8ddSJoonsoo Kim 
18270dd1c7bbSJoonsoo Kim 	if (rwc->anon_lock)
18280dd1c7bbSJoonsoo Kim 		return rwc->anon_lock(page);
18290dd1c7bbSJoonsoo Kim 
1830faecd8ddSJoonsoo Kim 	/*
1831faecd8ddSJoonsoo Kim 	 * Note: remove_migration_ptes() cannot use page_lock_anon_vma_read()
1832faecd8ddSJoonsoo Kim 	 * because that depends on page_mapped(); but not all its usages
1833c1e8d7c6SMichel Lespinasse 	 * are holding mmap_lock. Users without mmap_lock are required to
1834faecd8ddSJoonsoo Kim 	 * take a reference count to prevent the anon_vma disappearing
1835faecd8ddSJoonsoo Kim 	 */
1836faecd8ddSJoonsoo Kim 	anon_vma = page_anon_vma(page);
1837faecd8ddSJoonsoo Kim 	if (!anon_vma)
1838faecd8ddSJoonsoo Kim 		return NULL;
1839faecd8ddSJoonsoo Kim 
1840faecd8ddSJoonsoo Kim 	anon_vma_lock_read(anon_vma);
1841faecd8ddSJoonsoo Kim 	return anon_vma;
1842faecd8ddSJoonsoo Kim }
1843faecd8ddSJoonsoo Kim 
1844e9995ef9SHugh Dickins /*
1845e8351ac9SJoonsoo Kim  * rmap_walk_anon - do something to anonymous page using the object-based
1846e8351ac9SJoonsoo Kim  * rmap method
1847e8351ac9SJoonsoo Kim  * @page: the page to be handled
1848e8351ac9SJoonsoo Kim  * @rwc: control variable according to each walk type
1849e8351ac9SJoonsoo Kim  *
1850e8351ac9SJoonsoo Kim  * Find all the mappings of a page using the mapping pointer and the vma chains
1851e8351ac9SJoonsoo Kim  * contained in the anon_vma struct it points to.
1852e8351ac9SJoonsoo Kim  *
1853c1e8d7c6SMichel Lespinasse  * When called from try_to_munlock(), the mmap_lock of the mm containing the vma
1854e8351ac9SJoonsoo Kim  * where the page was found will be held for write.  So, we won't recheck
1855e8351ac9SJoonsoo Kim  * vm_flags for that VMA.  That should be OK, because that vma shouldn't be
1856e8351ac9SJoonsoo Kim  * LOCKED.
1857e9995ef9SHugh Dickins  */
18581df631aeSMinchan Kim static void rmap_walk_anon(struct page *page, struct rmap_walk_control *rwc,
1859b9773199SKirill A. Shutemov 		bool locked)
1860e9995ef9SHugh Dickins {
1861e9995ef9SHugh Dickins 	struct anon_vma *anon_vma;
1862a8fa41adSKirill A. Shutemov 	pgoff_t pgoff_start, pgoff_end;
18635beb4930SRik van Riel 	struct anon_vma_chain *avc;
1864e9995ef9SHugh Dickins 
1865b9773199SKirill A. Shutemov 	if (locked) {
1866b9773199SKirill A. Shutemov 		anon_vma = page_anon_vma(page);
1867b9773199SKirill A. Shutemov 		/* anon_vma disappear under us? */
1868b9773199SKirill A. Shutemov 		VM_BUG_ON_PAGE(!anon_vma, page);
1869b9773199SKirill A. Shutemov 	} else {
18700dd1c7bbSJoonsoo Kim 		anon_vma = rmap_walk_anon_lock(page, rwc);
1871b9773199SKirill A. Shutemov 	}
1872e9995ef9SHugh Dickins 	if (!anon_vma)
18731df631aeSMinchan Kim 		return;
1874faecd8ddSJoonsoo Kim 
1875a8fa41adSKirill A. Shutemov 	pgoff_start = page_to_pgoff(page);
18766c357848SMatthew Wilcox (Oracle) 	pgoff_end = pgoff_start + thp_nr_pages(page) - 1;
1877a8fa41adSKirill A. Shutemov 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
1878a8fa41adSKirill A. Shutemov 			pgoff_start, pgoff_end) {
18795beb4930SRik van Riel 		struct vm_area_struct *vma = avc->vma;
1880e9995ef9SHugh Dickins 		unsigned long address = vma_address(page, vma);
18810dd1c7bbSJoonsoo Kim 
1882ad12695fSAndrea Arcangeli 		cond_resched();
1883ad12695fSAndrea Arcangeli 
18840dd1c7bbSJoonsoo Kim 		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
18850dd1c7bbSJoonsoo Kim 			continue;
18860dd1c7bbSJoonsoo Kim 
1887e4b82222SMinchan Kim 		if (!rwc->rmap_one(page, vma, address, rwc->arg))
1888e9995ef9SHugh Dickins 			break;
18890dd1c7bbSJoonsoo Kim 		if (rwc->done && rwc->done(page))
18900dd1c7bbSJoonsoo Kim 			break;
1891e9995ef9SHugh Dickins 	}
1892b9773199SKirill A. Shutemov 
1893b9773199SKirill A. Shutemov 	if (!locked)
18944fc3f1d6SIngo Molnar 		anon_vma_unlock_read(anon_vma);
1895e9995ef9SHugh Dickins }
1896e9995ef9SHugh Dickins 
1897e8351ac9SJoonsoo Kim /*
1898e8351ac9SJoonsoo Kim  * rmap_walk_file - do something to file page using the object-based rmap method
1899e8351ac9SJoonsoo Kim  * @page: the page to be handled
1900e8351ac9SJoonsoo Kim  * @rwc: control variable according to each walk type
1901e8351ac9SJoonsoo Kim  *
1902e8351ac9SJoonsoo Kim  * Find all the mappings of a page using the mapping pointer and the vma chains
1903e8351ac9SJoonsoo Kim  * contained in the address_space struct it points to.
1904e8351ac9SJoonsoo Kim  *
1905c1e8d7c6SMichel Lespinasse  * When called from try_to_munlock(), the mmap_lock of the mm containing the vma
1906e8351ac9SJoonsoo Kim  * where the page was found will be held for write.  So, we won't recheck
1907e8351ac9SJoonsoo Kim  * vm_flags for that VMA.  That should be OK, because that vma shouldn't be
1908e8351ac9SJoonsoo Kim  * LOCKED.
1909e8351ac9SJoonsoo Kim  */
19101df631aeSMinchan Kim static void rmap_walk_file(struct page *page, struct rmap_walk_control *rwc,
1911b9773199SKirill A. Shutemov 		bool locked)
1912e9995ef9SHugh Dickins {
1913b9773199SKirill A. Shutemov 	struct address_space *mapping = page_mapping(page);
1914a8fa41adSKirill A. Shutemov 	pgoff_t pgoff_start, pgoff_end;
1915e9995ef9SHugh Dickins 	struct vm_area_struct *vma;
1916e9995ef9SHugh Dickins 
19179f32624bSJoonsoo Kim 	/*
19189f32624bSJoonsoo Kim 	 * The page lock not only makes sure that page->mapping cannot
19199f32624bSJoonsoo Kim 	 * suddenly be NULLified by truncation, it makes sure that the
19209f32624bSJoonsoo Kim 	 * structure at mapping cannot be freed and reused yet,
1921c8c06efaSDavidlohr Bueso 	 * so we can safely take mapping->i_mmap_rwsem.
19229f32624bSJoonsoo Kim 	 */
192381d1b09cSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
19249f32624bSJoonsoo Kim 
1925e9995ef9SHugh Dickins 	if (!mapping)
19261df631aeSMinchan Kim 		return;
19273dec0ba0SDavidlohr Bueso 
1928a8fa41adSKirill A. Shutemov 	pgoff_start = page_to_pgoff(page);
19296c357848SMatthew Wilcox (Oracle) 	pgoff_end = pgoff_start + thp_nr_pages(page) - 1;
1930b9773199SKirill A. Shutemov 	if (!locked)
19313dec0ba0SDavidlohr Bueso 		i_mmap_lock_read(mapping);
1932a8fa41adSKirill A. Shutemov 	vma_interval_tree_foreach(vma, &mapping->i_mmap,
1933a8fa41adSKirill A. Shutemov 			pgoff_start, pgoff_end) {
1934e9995ef9SHugh Dickins 		unsigned long address = vma_address(page, vma);
19350dd1c7bbSJoonsoo Kim 
1936ad12695fSAndrea Arcangeli 		cond_resched();
1937ad12695fSAndrea Arcangeli 
19380dd1c7bbSJoonsoo Kim 		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
19390dd1c7bbSJoonsoo Kim 			continue;
19400dd1c7bbSJoonsoo Kim 
1941e4b82222SMinchan Kim 		if (!rwc->rmap_one(page, vma, address, rwc->arg))
19420dd1c7bbSJoonsoo Kim 			goto done;
19430dd1c7bbSJoonsoo Kim 		if (rwc->done && rwc->done(page))
19440dd1c7bbSJoonsoo Kim 			goto done;
1945e9995ef9SHugh Dickins 	}
19460dd1c7bbSJoonsoo Kim 
19470dd1c7bbSJoonsoo Kim done:
1948b9773199SKirill A. Shutemov 	if (!locked)
19493dec0ba0SDavidlohr Bueso 		i_mmap_unlock_read(mapping);
1950e9995ef9SHugh Dickins }
1951e9995ef9SHugh Dickins 
19521df631aeSMinchan Kim void rmap_walk(struct page *page, struct rmap_walk_control *rwc)
1953e9995ef9SHugh Dickins {
1954e9995ef9SHugh Dickins 	if (unlikely(PageKsm(page)))
19551df631aeSMinchan Kim 		rmap_walk_ksm(page, rwc);
1956e9995ef9SHugh Dickins 	else if (PageAnon(page))
19571df631aeSMinchan Kim 		rmap_walk_anon(page, rwc, false);
1958e9995ef9SHugh Dickins 	else
19591df631aeSMinchan Kim 		rmap_walk_file(page, rwc, false);
1960b9773199SKirill A. Shutemov }
1961b9773199SKirill A. Shutemov 
1962b9773199SKirill A. Shutemov /* Like rmap_walk, but caller holds relevant rmap lock */
19631df631aeSMinchan Kim void rmap_walk_locked(struct page *page, struct rmap_walk_control *rwc)
1964b9773199SKirill A. Shutemov {
1965b9773199SKirill A. Shutemov 	/* no ksm support for now */
1966b9773199SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageKsm(page), page);
1967b9773199SKirill A. Shutemov 	if (PageAnon(page))
19681df631aeSMinchan Kim 		rmap_walk_anon(page, rwc, true);
1969b9773199SKirill A. Shutemov 	else
19701df631aeSMinchan Kim 		rmap_walk_file(page, rwc, true);
1971e9995ef9SHugh Dickins }
19720fe6e20bSNaoya Horiguchi 
1973e3390f67SNaoya Horiguchi #ifdef CONFIG_HUGETLB_PAGE
19740fe6e20bSNaoya Horiguchi /*
1975451b9514SKirill Tkhai  * The following two functions are for anonymous (private mapped) hugepages.
19760fe6e20bSNaoya Horiguchi  * Unlike common anonymous pages, anonymous hugepages have no accounting code
19770fe6e20bSNaoya Horiguchi  * and no lru code, because we handle hugepages differently from common pages.
19780fe6e20bSNaoya Horiguchi  */
19790fe6e20bSNaoya Horiguchi void hugepage_add_anon_rmap(struct page *page,
19800fe6e20bSNaoya Horiguchi 			    struct vm_area_struct *vma, unsigned long address)
19810fe6e20bSNaoya Horiguchi {
19820fe6e20bSNaoya Horiguchi 	struct anon_vma *anon_vma = vma->anon_vma;
19830fe6e20bSNaoya Horiguchi 	int first;
1984a850ea30SNaoya Horiguchi 
1985a850ea30SNaoya Horiguchi 	BUG_ON(!PageLocked(page));
19860fe6e20bSNaoya Horiguchi 	BUG_ON(!anon_vma);
19875dbe0af4SHugh Dickins 	/* address might be in next vma when migration races vma_adjust */
198853f9263bSKirill A. Shutemov 	first = atomic_inc_and_test(compound_mapcount_ptr(page));
19890fe6e20bSNaoya Horiguchi 	if (first)
1990451b9514SKirill Tkhai 		__page_set_anon_rmap(page, vma, address, 0);
19910fe6e20bSNaoya Horiguchi }
19920fe6e20bSNaoya Horiguchi 
19930fe6e20bSNaoya Horiguchi void hugepage_add_new_anon_rmap(struct page *page,
19940fe6e20bSNaoya Horiguchi 			struct vm_area_struct *vma, unsigned long address)
19950fe6e20bSNaoya Horiguchi {
19960fe6e20bSNaoya Horiguchi 	BUG_ON(address < vma->vm_start || address >= vma->vm_end);
199753f9263bSKirill A. Shutemov 	atomic_set(compound_mapcount_ptr(page), 0);
199847e29d32SJohn Hubbard 	if (hpage_pincount_available(page))
199947e29d32SJohn Hubbard 		atomic_set(compound_pincount_ptr(page), 0);
200047e29d32SJohn Hubbard 
2001451b9514SKirill Tkhai 	__page_set_anon_rmap(page, vma, address, 1);
20020fe6e20bSNaoya Horiguchi }
2003e3390f67SNaoya Horiguchi #endif /* CONFIG_HUGETLB_PAGE */
2004