xref: /linux/mm/rmap.c (revision 47b390d23bf81894395c8773acf6f73c66465dc4)
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)
241da177e4SLinus Torvalds  *   mm->mmap_sem
251da177e4SLinus Torvalds  *     page->flags PG_locked (lock_page)
2688f306b6SKirill A. Shutemov  *       hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share)
27c8c06efaSDavidlohr Bueso  *         mapping->i_mmap_rwsem
285a505085SIngo Molnar  *           anon_vma->rwsem
29b8072f09SHugh Dickins  *             mm->page_table_lock or pte_lock
30f4b7e272SAndrey Ryabinin  *               pgdat->lru_lock (in mark_page_accessed, isolate_lru_page)
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)
34c4843a75SGreg Thelen  *                   mem_cgroup_{begin,end}_page_stat (memcg->move_lock)
35b93b0163SMatthew Wilcox  *                     i_pages lock (widely used)
36250df6edSDave Chinner  *                 inode->i_lock (in set_page_dirty's __mark_inode_dirty)
37f758eeabSChristoph Hellwig  *                 bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
381da177e4SLinus Torvalds  *                   sb_lock (within inode_lock in fs/fs-writeback.c)
39b93b0163SMatthew Wilcox  *                   i_pages lock (widely used, in set_page_dirty,
401da177e4SLinus Torvalds  *                             in arch-dependent flush_dcache_mmap_lock,
41f758eeabSChristoph Hellwig  *                             within bdi.wb->list_lock in __sync_single_inode)
426a46079cSAndi Kleen  *
435a505085SIngo Molnar  * anon_vma->rwsem,mapping->i_mutex      (memory_failure, collect_procs_anon)
446a46079cSAndi Kleen  *   ->tasklist_lock
456a46079cSAndi Kleen  *     pte map lock
461da177e4SLinus Torvalds  */
471da177e4SLinus Torvalds 
481da177e4SLinus Torvalds #include <linux/mm.h>
496e84f315SIngo Molnar #include <linux/sched/mm.h>
5029930025SIngo Molnar #include <linux/sched/task.h>
511da177e4SLinus Torvalds #include <linux/pagemap.h>
521da177e4SLinus Torvalds #include <linux/swap.h>
531da177e4SLinus Torvalds #include <linux/swapops.h>
541da177e4SLinus Torvalds #include <linux/slab.h>
551da177e4SLinus Torvalds #include <linux/init.h>
565ad64688SHugh Dickins #include <linux/ksm.h>
571da177e4SLinus Torvalds #include <linux/rmap.h>
581da177e4SLinus Torvalds #include <linux/rcupdate.h>
59b95f1b31SPaul Gortmaker #include <linux/export.h>
608a9f3ccdSBalbir Singh #include <linux/memcontrol.h>
61cddb8a5cSAndrea Arcangeli #include <linux/mmu_notifier.h>
6264cdd548SKOSAKI Motohiro #include <linux/migrate.h>
630fe6e20bSNaoya Horiguchi #include <linux/hugetlb.h>
64444f84fdSBen Dooks #include <linux/huge_mm.h>
65ef5d437fSJan Kara #include <linux/backing-dev.h>
6633c3fc71SVladimir Davydov #include <linux/page_idle.h>
67a5430ddaSJérôme Glisse #include <linux/memremap.h>
68bce73e48SChristian Borntraeger #include <linux/userfaultfd_k.h>
691da177e4SLinus Torvalds 
701da177e4SLinus Torvalds #include <asm/tlbflush.h>
711da177e4SLinus Torvalds 
7272b252aeSMel Gorman #include <trace/events/tlb.h>
7372b252aeSMel Gorman 
74b291f000SNick Piggin #include "internal.h"
75b291f000SNick Piggin 
76fdd2e5f8SAdrian Bunk static struct kmem_cache *anon_vma_cachep;
775beb4930SRik van Riel static struct kmem_cache *anon_vma_chain_cachep;
78fdd2e5f8SAdrian Bunk 
79fdd2e5f8SAdrian Bunk static inline struct anon_vma *anon_vma_alloc(void)
80fdd2e5f8SAdrian Bunk {
8101d8b20dSPeter Zijlstra 	struct anon_vma *anon_vma;
8201d8b20dSPeter Zijlstra 
8301d8b20dSPeter Zijlstra 	anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
8401d8b20dSPeter Zijlstra 	if (anon_vma) {
8501d8b20dSPeter Zijlstra 		atomic_set(&anon_vma->refcount, 1);
867a3ef208SKonstantin Khlebnikov 		anon_vma->degree = 1;	/* Reference for first vma */
877a3ef208SKonstantin Khlebnikov 		anon_vma->parent = anon_vma;
8801d8b20dSPeter Zijlstra 		/*
8901d8b20dSPeter Zijlstra 		 * Initialise the anon_vma root to point to itself. If called
9001d8b20dSPeter Zijlstra 		 * from fork, the root will be reset to the parents anon_vma.
9101d8b20dSPeter Zijlstra 		 */
9201d8b20dSPeter Zijlstra 		anon_vma->root = anon_vma;
93fdd2e5f8SAdrian Bunk 	}
94fdd2e5f8SAdrian Bunk 
9501d8b20dSPeter Zijlstra 	return anon_vma;
9601d8b20dSPeter Zijlstra }
9701d8b20dSPeter Zijlstra 
9801d8b20dSPeter Zijlstra static inline void anon_vma_free(struct anon_vma *anon_vma)
99fdd2e5f8SAdrian Bunk {
10001d8b20dSPeter Zijlstra 	VM_BUG_ON(atomic_read(&anon_vma->refcount));
10188c22088SPeter Zijlstra 
10288c22088SPeter Zijlstra 	/*
1034fc3f1d6SIngo Molnar 	 * Synchronize against page_lock_anon_vma_read() such that
10488c22088SPeter Zijlstra 	 * we can safely hold the lock without the anon_vma getting
10588c22088SPeter Zijlstra 	 * freed.
10688c22088SPeter Zijlstra 	 *
10788c22088SPeter Zijlstra 	 * Relies on the full mb implied by the atomic_dec_and_test() from
10888c22088SPeter Zijlstra 	 * put_anon_vma() against the acquire barrier implied by
1094fc3f1d6SIngo Molnar 	 * down_read_trylock() from page_lock_anon_vma_read(). This orders:
11088c22088SPeter Zijlstra 	 *
1114fc3f1d6SIngo Molnar 	 * page_lock_anon_vma_read()	VS	put_anon_vma()
1124fc3f1d6SIngo Molnar 	 *   down_read_trylock()		  atomic_dec_and_test()
11388c22088SPeter Zijlstra 	 *   LOCK				  MB
1144fc3f1d6SIngo Molnar 	 *   atomic_read()			  rwsem_is_locked()
11588c22088SPeter Zijlstra 	 *
11688c22088SPeter Zijlstra 	 * LOCK should suffice since the actual taking of the lock must
11788c22088SPeter Zijlstra 	 * happen _before_ what follows.
11888c22088SPeter Zijlstra 	 */
1197f39dda9SHugh Dickins 	might_sleep();
1205a505085SIngo Molnar 	if (rwsem_is_locked(&anon_vma->root->rwsem)) {
1214fc3f1d6SIngo Molnar 		anon_vma_lock_write(anon_vma);
12208b52706SKonstantin Khlebnikov 		anon_vma_unlock_write(anon_vma);
12388c22088SPeter Zijlstra 	}
12488c22088SPeter Zijlstra 
125fdd2e5f8SAdrian Bunk 	kmem_cache_free(anon_vma_cachep, anon_vma);
126fdd2e5f8SAdrian Bunk }
1271da177e4SLinus Torvalds 
128dd34739cSLinus Torvalds static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
1295beb4930SRik van Riel {
130dd34739cSLinus Torvalds 	return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
1315beb4930SRik van Riel }
1325beb4930SRik van Riel 
133e574b5fdSNamhyung Kim static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
1345beb4930SRik van Riel {
1355beb4930SRik van Riel 	kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
1365beb4930SRik van Riel }
1375beb4930SRik van Riel 
1386583a843SKautuk Consul static void anon_vma_chain_link(struct vm_area_struct *vma,
1396583a843SKautuk Consul 				struct anon_vma_chain *avc,
1406583a843SKautuk Consul 				struct anon_vma *anon_vma)
1416583a843SKautuk Consul {
1426583a843SKautuk Consul 	avc->vma = vma;
1436583a843SKautuk Consul 	avc->anon_vma = anon_vma;
1446583a843SKautuk Consul 	list_add(&avc->same_vma, &vma->anon_vma_chain);
145bf181b9fSMichel Lespinasse 	anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
1466583a843SKautuk Consul }
1476583a843SKautuk Consul 
148d9d332e0SLinus Torvalds /**
149d5a187daSVlastimil Babka  * __anon_vma_prepare - attach an anon_vma to a memory region
150d9d332e0SLinus Torvalds  * @vma: the memory region in question
151d9d332e0SLinus Torvalds  *
152d9d332e0SLinus Torvalds  * This makes sure the memory mapping described by 'vma' has
153d9d332e0SLinus Torvalds  * an 'anon_vma' attached to it, so that we can associate the
154d9d332e0SLinus Torvalds  * anonymous pages mapped into it with that anon_vma.
155d9d332e0SLinus Torvalds  *
156d5a187daSVlastimil Babka  * The common case will be that we already have one, which
157d5a187daSVlastimil Babka  * is handled inline by anon_vma_prepare(). But if
15823a0790aSFigo.zhang  * not we either need to find an adjacent mapping that we
159d9d332e0SLinus Torvalds  * can re-use the anon_vma from (very common when the only
160d9d332e0SLinus Torvalds  * reason for splitting a vma has been mprotect()), or we
161d9d332e0SLinus Torvalds  * allocate a new one.
162d9d332e0SLinus Torvalds  *
163d9d332e0SLinus Torvalds  * Anon-vma allocations are very subtle, because we may have
1644fc3f1d6SIngo Molnar  * optimistically looked up an anon_vma in page_lock_anon_vma_read()
165d9d332e0SLinus Torvalds  * and that may actually touch the spinlock even in the newly
166d9d332e0SLinus Torvalds  * allocated vma (it depends on RCU to make sure that the
167d9d332e0SLinus Torvalds  * anon_vma isn't actually destroyed).
168d9d332e0SLinus Torvalds  *
169d9d332e0SLinus Torvalds  * As a result, we need to do proper anon_vma locking even
170d9d332e0SLinus Torvalds  * for the new allocation. At the same time, we do not want
171d9d332e0SLinus Torvalds  * to do any locking for the common case of already having
172d9d332e0SLinus Torvalds  * an anon_vma.
173d9d332e0SLinus Torvalds  *
174d9d332e0SLinus Torvalds  * This must be called with the mmap_sem held for reading.
175d9d332e0SLinus Torvalds  */
176d5a187daSVlastimil Babka int __anon_vma_prepare(struct vm_area_struct *vma)
1771da177e4SLinus Torvalds {
178d5a187daSVlastimil Babka 	struct mm_struct *mm = vma->vm_mm;
179d5a187daSVlastimil Babka 	struct anon_vma *anon_vma, *allocated;
1805beb4930SRik van Riel 	struct anon_vma_chain *avc;
1811da177e4SLinus Torvalds 
1821da177e4SLinus Torvalds 	might_sleep();
1831da177e4SLinus Torvalds 
184dd34739cSLinus Torvalds 	avc = anon_vma_chain_alloc(GFP_KERNEL);
1855beb4930SRik van Riel 	if (!avc)
1865beb4930SRik van Riel 		goto out_enomem;
1875beb4930SRik van Riel 
1881da177e4SLinus Torvalds 	anon_vma = find_mergeable_anon_vma(vma);
1891da177e4SLinus Torvalds 	allocated = NULL;
190d9d332e0SLinus Torvalds 	if (!anon_vma) {
1911da177e4SLinus Torvalds 		anon_vma = anon_vma_alloc();
1921da177e4SLinus Torvalds 		if (unlikely(!anon_vma))
1935beb4930SRik van Riel 			goto out_enomem_free_avc;
1941da177e4SLinus Torvalds 		allocated = anon_vma;
1951da177e4SLinus Torvalds 	}
1961da177e4SLinus Torvalds 
1974fc3f1d6SIngo Molnar 	anon_vma_lock_write(anon_vma);
1981da177e4SLinus Torvalds 	/* page_table_lock to protect against threads */
1991da177e4SLinus Torvalds 	spin_lock(&mm->page_table_lock);
2001da177e4SLinus Torvalds 	if (likely(!vma->anon_vma)) {
2011da177e4SLinus Torvalds 		vma->anon_vma = anon_vma;
2026583a843SKautuk Consul 		anon_vma_chain_link(vma, avc, anon_vma);
2037a3ef208SKonstantin Khlebnikov 		/* vma reference or self-parent link for new root */
2047a3ef208SKonstantin Khlebnikov 		anon_vma->degree++;
2051da177e4SLinus Torvalds 		allocated = NULL;
20631f2b0ebSOleg Nesterov 		avc = NULL;
2071da177e4SLinus Torvalds 	}
2081da177e4SLinus Torvalds 	spin_unlock(&mm->page_table_lock);
20908b52706SKonstantin Khlebnikov 	anon_vma_unlock_write(anon_vma);
21031f2b0ebSOleg Nesterov 
21131f2b0ebSOleg Nesterov 	if (unlikely(allocated))
21201d8b20dSPeter Zijlstra 		put_anon_vma(allocated);
21331f2b0ebSOleg Nesterov 	if (unlikely(avc))
2145beb4930SRik van Riel 		anon_vma_chain_free(avc);
215d5a187daSVlastimil Babka 
2161da177e4SLinus Torvalds 	return 0;
2175beb4930SRik van Riel 
2185beb4930SRik van Riel  out_enomem_free_avc:
2195beb4930SRik van Riel 	anon_vma_chain_free(avc);
2205beb4930SRik van Riel  out_enomem:
2215beb4930SRik van Riel 	return -ENOMEM;
2221da177e4SLinus Torvalds }
2231da177e4SLinus Torvalds 
224bb4aa396SLinus Torvalds /*
225bb4aa396SLinus Torvalds  * This is a useful helper function for locking the anon_vma root as
226bb4aa396SLinus Torvalds  * we traverse the vma->anon_vma_chain, looping over anon_vma's that
227bb4aa396SLinus Torvalds  * have the same vma.
228bb4aa396SLinus Torvalds  *
229bb4aa396SLinus Torvalds  * Such anon_vma's should have the same root, so you'd expect to see
230bb4aa396SLinus Torvalds  * just a single mutex_lock for the whole traversal.
231bb4aa396SLinus Torvalds  */
232bb4aa396SLinus Torvalds static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
233bb4aa396SLinus Torvalds {
234bb4aa396SLinus Torvalds 	struct anon_vma *new_root = anon_vma->root;
235bb4aa396SLinus Torvalds 	if (new_root != root) {
236bb4aa396SLinus Torvalds 		if (WARN_ON_ONCE(root))
2375a505085SIngo Molnar 			up_write(&root->rwsem);
238bb4aa396SLinus Torvalds 		root = new_root;
2395a505085SIngo Molnar 		down_write(&root->rwsem);
240bb4aa396SLinus Torvalds 	}
241bb4aa396SLinus Torvalds 	return root;
242bb4aa396SLinus Torvalds }
243bb4aa396SLinus Torvalds 
244bb4aa396SLinus Torvalds static inline void unlock_anon_vma_root(struct anon_vma *root)
245bb4aa396SLinus Torvalds {
246bb4aa396SLinus Torvalds 	if (root)
2475a505085SIngo Molnar 		up_write(&root->rwsem);
248bb4aa396SLinus Torvalds }
249bb4aa396SLinus Torvalds 
2505beb4930SRik van Riel /*
2515beb4930SRik van Riel  * Attach the anon_vmas from src to dst.
2525beb4930SRik van Riel  * Returns 0 on success, -ENOMEM on failure.
2537a3ef208SKonstantin Khlebnikov  *
254*47b390d2SWei Yang  * anon_vma_clone() is called by __vma_split(), __split_vma(), copy_vma() and
255*47b390d2SWei Yang  * anon_vma_fork(). The first three want an exact copy of src, while the last
256*47b390d2SWei Yang  * one, anon_vma_fork(), may try to reuse an existing anon_vma to prevent
257*47b390d2SWei Yang  * endless growth of anon_vma. Since dst->anon_vma is set to NULL before call,
258*47b390d2SWei Yang  * we can identify this case by checking (!dst->anon_vma && src->anon_vma).
259*47b390d2SWei Yang  *
260*47b390d2SWei Yang  * If (!dst->anon_vma && src->anon_vma) is true, this function tries to find
261*47b390d2SWei Yang  * and reuse existing anon_vma which has no vmas and only one child anon_vma.
262*47b390d2SWei Yang  * This prevents degradation of anon_vma hierarchy to endless linear chain in
263*47b390d2SWei Yang  * case of constantly forking task. On the other hand, an anon_vma with more
264*47b390d2SWei Yang  * than one child isn't reused even if there was no alive vma, thus rmap
265*47b390d2SWei Yang  * walker has a good chance of avoiding scanning the whole hierarchy when it
266*47b390d2SWei Yang  * searches where page is mapped.
2675beb4930SRik van Riel  */
2685beb4930SRik van Riel int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
2695beb4930SRik van Riel {
2705beb4930SRik van Riel 	struct anon_vma_chain *avc, *pavc;
271bb4aa396SLinus Torvalds 	struct anon_vma *root = NULL;
2725beb4930SRik van Riel 
273646d87b4SLinus Torvalds 	list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
274bb4aa396SLinus Torvalds 		struct anon_vma *anon_vma;
275bb4aa396SLinus Torvalds 
276dd34739cSLinus Torvalds 		avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
277dd34739cSLinus Torvalds 		if (unlikely(!avc)) {
278dd34739cSLinus Torvalds 			unlock_anon_vma_root(root);
279dd34739cSLinus Torvalds 			root = NULL;
280dd34739cSLinus Torvalds 			avc = anon_vma_chain_alloc(GFP_KERNEL);
2815beb4930SRik van Riel 			if (!avc)
2825beb4930SRik van Riel 				goto enomem_failure;
283dd34739cSLinus Torvalds 		}
284bb4aa396SLinus Torvalds 		anon_vma = pavc->anon_vma;
285bb4aa396SLinus Torvalds 		root = lock_anon_vma_root(root, anon_vma);
286bb4aa396SLinus Torvalds 		anon_vma_chain_link(dst, avc, anon_vma);
2877a3ef208SKonstantin Khlebnikov 
2887a3ef208SKonstantin Khlebnikov 		/*
2897a3ef208SKonstantin Khlebnikov 		 * Reuse existing anon_vma if its degree lower than two,
2907a3ef208SKonstantin Khlebnikov 		 * that means it has no vma and only one anon_vma child.
2917a3ef208SKonstantin Khlebnikov 		 *
2927a3ef208SKonstantin Khlebnikov 		 * Do not chose parent anon_vma, otherwise first child
2937a3ef208SKonstantin Khlebnikov 		 * will always reuse it. Root anon_vma is never reused:
2947a3ef208SKonstantin Khlebnikov 		 * it has self-parent reference and at least one child.
2957a3ef208SKonstantin Khlebnikov 		 */
296*47b390d2SWei Yang 		if (!dst->anon_vma && src->anon_vma &&
297*47b390d2SWei Yang 		    anon_vma != src->anon_vma && anon_vma->degree < 2)
2987a3ef208SKonstantin Khlebnikov 			dst->anon_vma = anon_vma;
2995beb4930SRik van Riel 	}
3007a3ef208SKonstantin Khlebnikov 	if (dst->anon_vma)
3017a3ef208SKonstantin Khlebnikov 		dst->anon_vma->degree++;
302bb4aa396SLinus Torvalds 	unlock_anon_vma_root(root);
3035beb4930SRik van Riel 	return 0;
3045beb4930SRik van Riel 
3055beb4930SRik van Riel  enomem_failure:
3063fe89b3eSLeon Yu 	/*
3073fe89b3eSLeon Yu 	 * dst->anon_vma is dropped here otherwise its degree can be incorrectly
3083fe89b3eSLeon Yu 	 * decremented in unlink_anon_vmas().
3093fe89b3eSLeon Yu 	 * We can safely do this because callers of anon_vma_clone() don't care
3103fe89b3eSLeon Yu 	 * about dst->anon_vma if anon_vma_clone() failed.
3113fe89b3eSLeon Yu 	 */
3123fe89b3eSLeon Yu 	dst->anon_vma = NULL;
3135beb4930SRik van Riel 	unlink_anon_vmas(dst);
3145beb4930SRik van Riel 	return -ENOMEM;
3151da177e4SLinus Torvalds }
3161da177e4SLinus Torvalds 
3175beb4930SRik van Riel /*
3185beb4930SRik van Riel  * Attach vma to its own anon_vma, as well as to the anon_vmas that
3195beb4930SRik van Riel  * the corresponding VMA in the parent process is attached to.
3205beb4930SRik van Riel  * Returns 0 on success, non-zero on failure.
3215beb4930SRik van Riel  */
3225beb4930SRik van Riel int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
3231da177e4SLinus Torvalds {
3245beb4930SRik van Riel 	struct anon_vma_chain *avc;
3255beb4930SRik van Riel 	struct anon_vma *anon_vma;
326c4ea95d7SDaniel Forrest 	int error;
3275beb4930SRik van Riel 
3285beb4930SRik van Riel 	/* Don't bother if the parent process has no anon_vma here. */
3295beb4930SRik van Riel 	if (!pvma->anon_vma)
3305beb4930SRik van Riel 		return 0;
3315beb4930SRik van Riel 
3327a3ef208SKonstantin Khlebnikov 	/* Drop inherited anon_vma, we'll reuse existing or allocate new. */
3337a3ef208SKonstantin Khlebnikov 	vma->anon_vma = NULL;
3347a3ef208SKonstantin Khlebnikov 
3355beb4930SRik van Riel 	/*
3365beb4930SRik van Riel 	 * First, attach the new VMA to the parent VMA's anon_vmas,
3375beb4930SRik van Riel 	 * so rmap can find non-COWed pages in child processes.
3385beb4930SRik van Riel 	 */
339c4ea95d7SDaniel Forrest 	error = anon_vma_clone(vma, pvma);
340c4ea95d7SDaniel Forrest 	if (error)
341c4ea95d7SDaniel Forrest 		return error;
3425beb4930SRik van Riel 
3437a3ef208SKonstantin Khlebnikov 	/* An existing anon_vma has been reused, all done then. */
3447a3ef208SKonstantin Khlebnikov 	if (vma->anon_vma)
3457a3ef208SKonstantin Khlebnikov 		return 0;
3467a3ef208SKonstantin Khlebnikov 
3475beb4930SRik van Riel 	/* Then add our own anon_vma. */
3485beb4930SRik van Riel 	anon_vma = anon_vma_alloc();
3495beb4930SRik van Riel 	if (!anon_vma)
3505beb4930SRik van Riel 		goto out_error;
351dd34739cSLinus Torvalds 	avc = anon_vma_chain_alloc(GFP_KERNEL);
3525beb4930SRik van Riel 	if (!avc)
3535beb4930SRik van Riel 		goto out_error_free_anon_vma;
3545c341ee1SRik van Riel 
3555c341ee1SRik van Riel 	/*
3565c341ee1SRik van Riel 	 * The root anon_vma's spinlock is the lock actually used when we
3575c341ee1SRik van Riel 	 * lock any of the anon_vmas in this anon_vma tree.
3585c341ee1SRik van Riel 	 */
3595c341ee1SRik van Riel 	anon_vma->root = pvma->anon_vma->root;
3607a3ef208SKonstantin Khlebnikov 	anon_vma->parent = pvma->anon_vma;
36176545066SRik van Riel 	/*
36201d8b20dSPeter Zijlstra 	 * With refcounts, an anon_vma can stay around longer than the
36301d8b20dSPeter Zijlstra 	 * process it belongs to. The root anon_vma needs to be pinned until
36401d8b20dSPeter Zijlstra 	 * this anon_vma is freed, because the lock lives in the root.
36576545066SRik van Riel 	 */
36676545066SRik van Riel 	get_anon_vma(anon_vma->root);
3675beb4930SRik van Riel 	/* Mark this anon_vma as the one where our new (COWed) pages go. */
3685beb4930SRik van Riel 	vma->anon_vma = anon_vma;
3694fc3f1d6SIngo Molnar 	anon_vma_lock_write(anon_vma);
3705c341ee1SRik van Riel 	anon_vma_chain_link(vma, avc, anon_vma);
3717a3ef208SKonstantin Khlebnikov 	anon_vma->parent->degree++;
37208b52706SKonstantin Khlebnikov 	anon_vma_unlock_write(anon_vma);
3735beb4930SRik van Riel 
3745beb4930SRik van Riel 	return 0;
3755beb4930SRik van Riel 
3765beb4930SRik van Riel  out_error_free_anon_vma:
37701d8b20dSPeter Zijlstra 	put_anon_vma(anon_vma);
3785beb4930SRik van Riel  out_error:
3794946d54cSRik van Riel 	unlink_anon_vmas(vma);
3805beb4930SRik van Riel 	return -ENOMEM;
3815beb4930SRik van Riel }
3825beb4930SRik van Riel 
3835beb4930SRik van Riel void unlink_anon_vmas(struct vm_area_struct *vma)
3845beb4930SRik van Riel {
3855beb4930SRik van Riel 	struct anon_vma_chain *avc, *next;
386eee2acbaSPeter Zijlstra 	struct anon_vma *root = NULL;
3875beb4930SRik van Riel 
3885c341ee1SRik van Riel 	/*
3895c341ee1SRik van Riel 	 * Unlink each anon_vma chained to the VMA.  This list is ordered
3905c341ee1SRik van Riel 	 * from newest to oldest, ensuring the root anon_vma gets freed last.
3915c341ee1SRik van Riel 	 */
3925beb4930SRik van Riel 	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
393eee2acbaSPeter Zijlstra 		struct anon_vma *anon_vma = avc->anon_vma;
394eee2acbaSPeter Zijlstra 
395eee2acbaSPeter Zijlstra 		root = lock_anon_vma_root(root, anon_vma);
396bf181b9fSMichel Lespinasse 		anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
397eee2acbaSPeter Zijlstra 
398eee2acbaSPeter Zijlstra 		/*
399eee2acbaSPeter Zijlstra 		 * Leave empty anon_vmas on the list - we'll need
400eee2acbaSPeter Zijlstra 		 * to free them outside the lock.
401eee2acbaSPeter Zijlstra 		 */
402f808c13fSDavidlohr Bueso 		if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
4037a3ef208SKonstantin Khlebnikov 			anon_vma->parent->degree--;
404eee2acbaSPeter Zijlstra 			continue;
4057a3ef208SKonstantin Khlebnikov 		}
406eee2acbaSPeter Zijlstra 
407eee2acbaSPeter Zijlstra 		list_del(&avc->same_vma);
408eee2acbaSPeter Zijlstra 		anon_vma_chain_free(avc);
409eee2acbaSPeter Zijlstra 	}
4107a3ef208SKonstantin Khlebnikov 	if (vma->anon_vma)
4117a3ef208SKonstantin Khlebnikov 		vma->anon_vma->degree--;
412eee2acbaSPeter Zijlstra 	unlock_anon_vma_root(root);
413eee2acbaSPeter Zijlstra 
414eee2acbaSPeter Zijlstra 	/*
415eee2acbaSPeter Zijlstra 	 * Iterate the list once more, it now only contains empty and unlinked
416eee2acbaSPeter Zijlstra 	 * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
4175a505085SIngo Molnar 	 * needing to write-acquire the anon_vma->root->rwsem.
418eee2acbaSPeter Zijlstra 	 */
419eee2acbaSPeter Zijlstra 	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
420eee2acbaSPeter Zijlstra 		struct anon_vma *anon_vma = avc->anon_vma;
421eee2acbaSPeter Zijlstra 
422e4c5800aSKonstantin Khlebnikov 		VM_WARN_ON(anon_vma->degree);
423eee2acbaSPeter Zijlstra 		put_anon_vma(anon_vma);
424eee2acbaSPeter Zijlstra 
4255beb4930SRik van Riel 		list_del(&avc->same_vma);
4265beb4930SRik van Riel 		anon_vma_chain_free(avc);
4275beb4930SRik van Riel 	}
4285beb4930SRik van Riel }
4295beb4930SRik van Riel 
43051cc5068SAlexey Dobriyan static void anon_vma_ctor(void *data)
4311da177e4SLinus Torvalds {
4321da177e4SLinus Torvalds 	struct anon_vma *anon_vma = data;
4331da177e4SLinus Torvalds 
4345a505085SIngo Molnar 	init_rwsem(&anon_vma->rwsem);
43583813267SPeter Zijlstra 	atomic_set(&anon_vma->refcount, 0);
436f808c13fSDavidlohr Bueso 	anon_vma->rb_root = RB_ROOT_CACHED;
4371da177e4SLinus Torvalds }
4381da177e4SLinus Torvalds 
4391da177e4SLinus Torvalds void __init anon_vma_init(void)
4401da177e4SLinus Torvalds {
4411da177e4SLinus Torvalds 	anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
4425f0d5a3aSPaul E. McKenney 			0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
4435d097056SVladimir Davydov 			anon_vma_ctor);
4445d097056SVladimir Davydov 	anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
4455d097056SVladimir Davydov 			SLAB_PANIC|SLAB_ACCOUNT);
4461da177e4SLinus Torvalds }
4471da177e4SLinus Torvalds 
4481da177e4SLinus Torvalds /*
4496111e4caSPeter Zijlstra  * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
4506111e4caSPeter Zijlstra  *
4516111e4caSPeter Zijlstra  * Since there is no serialization what so ever against page_remove_rmap()
4526111e4caSPeter Zijlstra  * the best this function can do is return a locked anon_vma that might
4536111e4caSPeter Zijlstra  * have been relevant to this page.
4546111e4caSPeter Zijlstra  *
4556111e4caSPeter Zijlstra  * The page might have been remapped to a different anon_vma or the anon_vma
4566111e4caSPeter Zijlstra  * returned may already be freed (and even reused).
4576111e4caSPeter Zijlstra  *
458bc658c96SPeter Zijlstra  * In case it was remapped to a different anon_vma, the new anon_vma will be a
459bc658c96SPeter Zijlstra  * child of the old anon_vma, and the anon_vma lifetime rules will therefore
460bc658c96SPeter Zijlstra  * ensure that any anon_vma obtained from the page will still be valid for as
461bc658c96SPeter Zijlstra  * long as we observe page_mapped() [ hence all those page_mapped() tests ].
462bc658c96SPeter Zijlstra  *
4636111e4caSPeter Zijlstra  * All users of this function must be very careful when walking the anon_vma
4646111e4caSPeter Zijlstra  * chain and verify that the page in question is indeed mapped in it
4656111e4caSPeter Zijlstra  * [ something equivalent to page_mapped_in_vma() ].
4666111e4caSPeter Zijlstra  *
4676111e4caSPeter Zijlstra  * Since anon_vma's slab is DESTROY_BY_RCU and we know from page_remove_rmap()
4686111e4caSPeter Zijlstra  * that the anon_vma pointer from page->mapping is valid if there is a
4696111e4caSPeter Zijlstra  * mapcount, we can dereference the anon_vma after observing those.
4701da177e4SLinus Torvalds  */
471746b18d4SPeter Zijlstra struct anon_vma *page_get_anon_vma(struct page *page)
4721da177e4SLinus Torvalds {
473746b18d4SPeter Zijlstra 	struct anon_vma *anon_vma = NULL;
4741da177e4SLinus Torvalds 	unsigned long anon_mapping;
4751da177e4SLinus Torvalds 
4761da177e4SLinus Torvalds 	rcu_read_lock();
4774db0c3c2SJason Low 	anon_mapping = (unsigned long)READ_ONCE(page->mapping);
4783ca7b3c5SHugh Dickins 	if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
4791da177e4SLinus Torvalds 		goto out;
4801da177e4SLinus Torvalds 	if (!page_mapped(page))
4811da177e4SLinus Torvalds 		goto out;
4821da177e4SLinus Torvalds 
4831da177e4SLinus Torvalds 	anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
484746b18d4SPeter Zijlstra 	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
485746b18d4SPeter Zijlstra 		anon_vma = NULL;
486746b18d4SPeter Zijlstra 		goto out;
487746b18d4SPeter Zijlstra 	}
488f1819427SHugh Dickins 
489f1819427SHugh Dickins 	/*
490f1819427SHugh Dickins 	 * If this page is still mapped, then its anon_vma cannot have been
491746b18d4SPeter Zijlstra 	 * freed.  But if it has been unmapped, we have no security against the
492746b18d4SPeter Zijlstra 	 * anon_vma structure being freed and reused (for another anon_vma:
4935f0d5a3aSPaul E. McKenney 	 * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
494746b18d4SPeter Zijlstra 	 * above cannot corrupt).
495f1819427SHugh Dickins 	 */
496746b18d4SPeter Zijlstra 	if (!page_mapped(page)) {
4977f39dda9SHugh Dickins 		rcu_read_unlock();
498746b18d4SPeter Zijlstra 		put_anon_vma(anon_vma);
4997f39dda9SHugh Dickins 		return NULL;
500746b18d4SPeter Zijlstra 	}
5011da177e4SLinus Torvalds out:
5021da177e4SLinus Torvalds 	rcu_read_unlock();
503746b18d4SPeter Zijlstra 
504746b18d4SPeter Zijlstra 	return anon_vma;
505746b18d4SPeter Zijlstra }
506746b18d4SPeter Zijlstra 
50788c22088SPeter Zijlstra /*
50888c22088SPeter Zijlstra  * Similar to page_get_anon_vma() except it locks the anon_vma.
50988c22088SPeter Zijlstra  *
51088c22088SPeter Zijlstra  * Its a little more complex as it tries to keep the fast path to a single
51188c22088SPeter Zijlstra  * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
51288c22088SPeter Zijlstra  * reference like with page_get_anon_vma() and then block on the mutex.
51388c22088SPeter Zijlstra  */
5144fc3f1d6SIngo Molnar struct anon_vma *page_lock_anon_vma_read(struct page *page)
515746b18d4SPeter Zijlstra {
51688c22088SPeter Zijlstra 	struct anon_vma *anon_vma = NULL;
517eee0f252SHugh Dickins 	struct anon_vma *root_anon_vma;
51888c22088SPeter Zijlstra 	unsigned long anon_mapping;
519746b18d4SPeter Zijlstra 
52088c22088SPeter Zijlstra 	rcu_read_lock();
5214db0c3c2SJason Low 	anon_mapping = (unsigned long)READ_ONCE(page->mapping);
52288c22088SPeter Zijlstra 	if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
52388c22088SPeter Zijlstra 		goto out;
52488c22088SPeter Zijlstra 	if (!page_mapped(page))
52588c22088SPeter Zijlstra 		goto out;
52688c22088SPeter Zijlstra 
52788c22088SPeter Zijlstra 	anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
5284db0c3c2SJason Low 	root_anon_vma = READ_ONCE(anon_vma->root);
5294fc3f1d6SIngo Molnar 	if (down_read_trylock(&root_anon_vma->rwsem)) {
53088c22088SPeter Zijlstra 		/*
531eee0f252SHugh Dickins 		 * If the page is still mapped, then this anon_vma is still
532eee0f252SHugh Dickins 		 * its anon_vma, and holding the mutex ensures that it will
533bc658c96SPeter Zijlstra 		 * not go away, see anon_vma_free().
53488c22088SPeter Zijlstra 		 */
535eee0f252SHugh Dickins 		if (!page_mapped(page)) {
5364fc3f1d6SIngo Molnar 			up_read(&root_anon_vma->rwsem);
53788c22088SPeter Zijlstra 			anon_vma = NULL;
53888c22088SPeter Zijlstra 		}
53988c22088SPeter Zijlstra 		goto out;
54088c22088SPeter Zijlstra 	}
54188c22088SPeter Zijlstra 
54288c22088SPeter Zijlstra 	/* trylock failed, we got to sleep */
54388c22088SPeter Zijlstra 	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
54488c22088SPeter Zijlstra 		anon_vma = NULL;
54588c22088SPeter Zijlstra 		goto out;
54688c22088SPeter Zijlstra 	}
54788c22088SPeter Zijlstra 
54888c22088SPeter Zijlstra 	if (!page_mapped(page)) {
5497f39dda9SHugh Dickins 		rcu_read_unlock();
55088c22088SPeter Zijlstra 		put_anon_vma(anon_vma);
5517f39dda9SHugh Dickins 		return NULL;
55288c22088SPeter Zijlstra 	}
55388c22088SPeter Zijlstra 
55488c22088SPeter Zijlstra 	/* we pinned the anon_vma, its safe to sleep */
55588c22088SPeter Zijlstra 	rcu_read_unlock();
5564fc3f1d6SIngo Molnar 	anon_vma_lock_read(anon_vma);
557746b18d4SPeter Zijlstra 
55888c22088SPeter Zijlstra 	if (atomic_dec_and_test(&anon_vma->refcount)) {
55988c22088SPeter Zijlstra 		/*
56088c22088SPeter Zijlstra 		 * Oops, we held the last refcount, release the lock
56188c22088SPeter Zijlstra 		 * and bail -- can't simply use put_anon_vma() because
5624fc3f1d6SIngo Molnar 		 * we'll deadlock on the anon_vma_lock_write() recursion.
56388c22088SPeter Zijlstra 		 */
5644fc3f1d6SIngo Molnar 		anon_vma_unlock_read(anon_vma);
56588c22088SPeter Zijlstra 		__put_anon_vma(anon_vma);
56688c22088SPeter Zijlstra 		anon_vma = NULL;
56788c22088SPeter Zijlstra 	}
56888c22088SPeter Zijlstra 
56988c22088SPeter Zijlstra 	return anon_vma;
57088c22088SPeter Zijlstra 
57188c22088SPeter Zijlstra out:
57288c22088SPeter Zijlstra 	rcu_read_unlock();
573746b18d4SPeter Zijlstra 	return anon_vma;
57434bbd704SOleg Nesterov }
57534bbd704SOleg Nesterov 
5764fc3f1d6SIngo Molnar void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
57734bbd704SOleg Nesterov {
5784fc3f1d6SIngo Molnar 	anon_vma_unlock_read(anon_vma);
5791da177e4SLinus Torvalds }
5801da177e4SLinus Torvalds 
58172b252aeSMel Gorman #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
58272b252aeSMel Gorman /*
58372b252aeSMel Gorman  * Flush TLB entries for recently unmapped pages from remote CPUs. It is
58472b252aeSMel Gorman  * important if a PTE was dirty when it was unmapped that it's flushed
58572b252aeSMel Gorman  * before any IO is initiated on the page to prevent lost writes. Similarly,
58672b252aeSMel Gorman  * it must be flushed before freeing to prevent data leakage.
58772b252aeSMel Gorman  */
58872b252aeSMel Gorman void try_to_unmap_flush(void)
58972b252aeSMel Gorman {
59072b252aeSMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
59172b252aeSMel Gorman 
59272b252aeSMel Gorman 	if (!tlb_ubc->flush_required)
59372b252aeSMel Gorman 		return;
59472b252aeSMel Gorman 
595e73ad5ffSAndy Lutomirski 	arch_tlbbatch_flush(&tlb_ubc->arch);
59672b252aeSMel Gorman 	tlb_ubc->flush_required = false;
597d950c947SMel Gorman 	tlb_ubc->writable = false;
59872b252aeSMel Gorman }
59972b252aeSMel Gorman 
600d950c947SMel Gorman /* Flush iff there are potentially writable TLB entries that can race with IO */
601d950c947SMel Gorman void try_to_unmap_flush_dirty(void)
602d950c947SMel Gorman {
603d950c947SMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
604d950c947SMel Gorman 
605d950c947SMel Gorman 	if (tlb_ubc->writable)
606d950c947SMel Gorman 		try_to_unmap_flush();
607d950c947SMel Gorman }
608d950c947SMel Gorman 
609c7ab0d2fSKirill A. Shutemov static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
61072b252aeSMel Gorman {
61172b252aeSMel Gorman 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
61272b252aeSMel Gorman 
613e73ad5ffSAndy Lutomirski 	arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
61472b252aeSMel Gorman 	tlb_ubc->flush_required = true;
615d950c947SMel Gorman 
616d950c947SMel Gorman 	/*
6173ea27719SMel Gorman 	 * Ensure compiler does not re-order the setting of tlb_flush_batched
6183ea27719SMel Gorman 	 * before the PTE is cleared.
6193ea27719SMel Gorman 	 */
6203ea27719SMel Gorman 	barrier();
6213ea27719SMel Gorman 	mm->tlb_flush_batched = true;
6223ea27719SMel Gorman 
6233ea27719SMel Gorman 	/*
624d950c947SMel Gorman 	 * If the PTE was dirty then it's best to assume it's writable. The
625d950c947SMel Gorman 	 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
626d950c947SMel Gorman 	 * before the page is queued for IO.
627d950c947SMel Gorman 	 */
628d950c947SMel Gorman 	if (writable)
629d950c947SMel Gorman 		tlb_ubc->writable = true;
63072b252aeSMel Gorman }
63172b252aeSMel Gorman 
63272b252aeSMel Gorman /*
63372b252aeSMel Gorman  * Returns true if the TLB flush should be deferred to the end of a batch of
63472b252aeSMel Gorman  * unmap operations to reduce IPIs.
63572b252aeSMel Gorman  */
63672b252aeSMel Gorman static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
63772b252aeSMel Gorman {
63872b252aeSMel Gorman 	bool should_defer = false;
63972b252aeSMel Gorman 
64072b252aeSMel Gorman 	if (!(flags & TTU_BATCH_FLUSH))
64172b252aeSMel Gorman 		return false;
64272b252aeSMel Gorman 
64372b252aeSMel Gorman 	/* If remote CPUs need to be flushed then defer batch the flush */
64472b252aeSMel Gorman 	if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
64572b252aeSMel Gorman 		should_defer = true;
64672b252aeSMel Gorman 	put_cpu();
64772b252aeSMel Gorman 
64872b252aeSMel Gorman 	return should_defer;
64972b252aeSMel Gorman }
6503ea27719SMel Gorman 
6513ea27719SMel Gorman /*
6523ea27719SMel Gorman  * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
6533ea27719SMel Gorman  * releasing the PTL if TLB flushes are batched. It's possible for a parallel
6543ea27719SMel Gorman  * operation such as mprotect or munmap to race between reclaim unmapping
6553ea27719SMel Gorman  * the page and flushing the page. If this race occurs, it potentially allows
6563ea27719SMel Gorman  * access to data via a stale TLB entry. Tracking all mm's that have TLB
6573ea27719SMel Gorman  * batching in flight would be expensive during reclaim so instead track
6583ea27719SMel Gorman  * whether TLB batching occurred in the past and if so then do a flush here
6593ea27719SMel Gorman  * if required. This will cost one additional flush per reclaim cycle paid
6603ea27719SMel Gorman  * by the first operation at risk such as mprotect and mumap.
6613ea27719SMel Gorman  *
6623ea27719SMel Gorman  * This must be called under the PTL so that an access to tlb_flush_batched
6633ea27719SMel Gorman  * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
6643ea27719SMel Gorman  * via the PTL.
6653ea27719SMel Gorman  */
6663ea27719SMel Gorman void flush_tlb_batched_pending(struct mm_struct *mm)
6673ea27719SMel Gorman {
6683ea27719SMel Gorman 	if (mm->tlb_flush_batched) {
6693ea27719SMel Gorman 		flush_tlb_mm(mm);
6703ea27719SMel Gorman 
6713ea27719SMel Gorman 		/*
6723ea27719SMel Gorman 		 * Do not allow the compiler to re-order the clearing of
6733ea27719SMel Gorman 		 * tlb_flush_batched before the tlb is flushed.
6743ea27719SMel Gorman 		 */
6753ea27719SMel Gorman 		barrier();
6763ea27719SMel Gorman 		mm->tlb_flush_batched = false;
6773ea27719SMel Gorman 	}
6783ea27719SMel Gorman }
67972b252aeSMel Gorman #else
680c7ab0d2fSKirill A. Shutemov static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
68172b252aeSMel Gorman {
68272b252aeSMel Gorman }
68372b252aeSMel Gorman 
68472b252aeSMel Gorman static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
68572b252aeSMel Gorman {
68672b252aeSMel Gorman 	return false;
68772b252aeSMel Gorman }
68872b252aeSMel Gorman #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
68972b252aeSMel Gorman 
6901da177e4SLinus Torvalds /*
691bf89c8c8SHuang Shijie  * At what user virtual address is page expected in vma?
692ab941e0fSNaoya Horiguchi  * Caller should check the page is actually part of the vma.
6931da177e4SLinus Torvalds  */
6941da177e4SLinus Torvalds unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
6951da177e4SLinus Torvalds {
69686c2ad19SMichel Lespinasse 	unsigned long address;
69721d0d443SAndrea Arcangeli 	if (PageAnon(page)) {
6984829b906SHugh Dickins 		struct anon_vma *page__anon_vma = page_anon_vma(page);
6994829b906SHugh Dickins 		/*
7004829b906SHugh Dickins 		 * Note: swapoff's unuse_vma() is more efficient with this
7014829b906SHugh Dickins 		 * check, and needs it to match anon_vma when KSM is active.
7024829b906SHugh Dickins 		 */
7034829b906SHugh Dickins 		if (!vma->anon_vma || !page__anon_vma ||
7044829b906SHugh Dickins 		    vma->anon_vma->root != page__anon_vma->root)
70521d0d443SAndrea Arcangeli 			return -EFAULT;
70627ba0644SKirill A. Shutemov 	} else if (page->mapping) {
70727ba0644SKirill A. Shutemov 		if (!vma->vm_file || vma->vm_file->f_mapping != page->mapping)
7081da177e4SLinus Torvalds 			return -EFAULT;
7091da177e4SLinus Torvalds 	} else
7101da177e4SLinus Torvalds 		return -EFAULT;
71186c2ad19SMichel Lespinasse 	address = __vma_address(page, vma);
71286c2ad19SMichel Lespinasse 	if (unlikely(address < vma->vm_start || address >= vma->vm_end))
71386c2ad19SMichel Lespinasse 		return -EFAULT;
71486c2ad19SMichel Lespinasse 	return address;
7151da177e4SLinus Torvalds }
7161da177e4SLinus Torvalds 
7176219049aSBob Liu pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
7186219049aSBob Liu {
7196219049aSBob Liu 	pgd_t *pgd;
720c2febafcSKirill A. Shutemov 	p4d_t *p4d;
7216219049aSBob Liu 	pud_t *pud;
7226219049aSBob Liu 	pmd_t *pmd = NULL;
723f72e7dcdSHugh Dickins 	pmd_t pmde;
7246219049aSBob Liu 
7256219049aSBob Liu 	pgd = pgd_offset(mm, address);
7266219049aSBob Liu 	if (!pgd_present(*pgd))
7276219049aSBob Liu 		goto out;
7286219049aSBob Liu 
729c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, address);
730c2febafcSKirill A. Shutemov 	if (!p4d_present(*p4d))
731c2febafcSKirill A. Shutemov 		goto out;
732c2febafcSKirill A. Shutemov 
733c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, address);
7346219049aSBob Liu 	if (!pud_present(*pud))
7356219049aSBob Liu 		goto out;
7366219049aSBob Liu 
7376219049aSBob Liu 	pmd = pmd_offset(pud, address);
738f72e7dcdSHugh Dickins 	/*
7398809aa2dSAneesh Kumar K.V 	 * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
740f72e7dcdSHugh Dickins 	 * without holding anon_vma lock for write.  So when looking for a
741f72e7dcdSHugh Dickins 	 * genuine pmde (in which to find pte), test present and !THP together.
742f72e7dcdSHugh Dickins 	 */
743e37c6982SChristian Borntraeger 	pmde = *pmd;
744e37c6982SChristian Borntraeger 	barrier();
745f72e7dcdSHugh Dickins 	if (!pmd_present(pmde) || pmd_trans_huge(pmde))
7466219049aSBob Liu 		pmd = NULL;
7476219049aSBob Liu out:
7486219049aSBob Liu 	return pmd;
7496219049aSBob Liu }
7506219049aSBob Liu 
7519f32624bSJoonsoo Kim struct page_referenced_arg {
7529f32624bSJoonsoo Kim 	int mapcount;
7539f32624bSJoonsoo Kim 	int referenced;
7549f32624bSJoonsoo Kim 	unsigned long vm_flags;
7559f32624bSJoonsoo Kim 	struct mem_cgroup *memcg;
7569f32624bSJoonsoo Kim };
75781b4082dSNikita Danilov /*
7589f32624bSJoonsoo Kim  * arg: page_referenced_arg will be passed
7591da177e4SLinus Torvalds  */
760e4b82222SMinchan Kim static bool page_referenced_one(struct page *page, struct vm_area_struct *vma,
7619f32624bSJoonsoo Kim 			unsigned long address, void *arg)
7621da177e4SLinus Torvalds {
7639f32624bSJoonsoo Kim 	struct page_referenced_arg *pra = arg;
7648eaededeSKirill A. Shutemov 	struct page_vma_mapped_walk pvmw = {
7658eaededeSKirill A. Shutemov 		.page = page,
7668eaededeSKirill A. Shutemov 		.vma = vma,
7678eaededeSKirill A. Shutemov 		.address = address,
7688eaededeSKirill A. Shutemov 	};
7698749cfeaSVladimir Davydov 	int referenced = 0;
7702da28bfdSAndrea Arcangeli 
7718eaededeSKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
7728eaededeSKirill A. Shutemov 		address = pvmw.address;
7732da28bfdSAndrea Arcangeli 
774b20ce5e0SKirill A. Shutemov 		if (vma->vm_flags & VM_LOCKED) {
7758eaededeSKirill A. Shutemov 			page_vma_mapped_walk_done(&pvmw);
7769f32624bSJoonsoo Kim 			pra->vm_flags |= VM_LOCKED;
777e4b82222SMinchan Kim 			return false; /* To break the loop */
7782da28bfdSAndrea Arcangeli 		}
7792da28bfdSAndrea Arcangeli 
7808eaededeSKirill A. Shutemov 		if (pvmw.pte) {
7818eaededeSKirill A. Shutemov 			if (ptep_clear_flush_young_notify(vma, address,
7828eaededeSKirill A. Shutemov 						pvmw.pte)) {
7834917e5d0SJohannes Weiner 				/*
7848eaededeSKirill A. Shutemov 				 * Don't treat a reference through
7858eaededeSKirill A. Shutemov 				 * a sequentially read mapping as such.
7868eaededeSKirill A. Shutemov 				 * If the page has been used in another mapping,
7878eaededeSKirill A. Shutemov 				 * we will catch it; if this other mapping is
7888eaededeSKirill A. Shutemov 				 * already gone, the unmap path will have set
7898eaededeSKirill A. Shutemov 				 * PG_referenced or activated the page.
7904917e5d0SJohannes Weiner 				 */
79164363aadSJoe Perches 				if (likely(!(vma->vm_flags & VM_SEQ_READ)))
7921da177e4SLinus Torvalds 					referenced++;
7934917e5d0SJohannes Weiner 			}
7948749cfeaSVladimir Davydov 		} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
7958eaededeSKirill A. Shutemov 			if (pmdp_clear_flush_young_notify(vma, address,
7968eaededeSKirill A. Shutemov 						pvmw.pmd))
7978749cfeaSVladimir Davydov 				referenced++;
7988749cfeaSVladimir Davydov 		} else {
7998749cfeaSVladimir Davydov 			/* unexpected pmd-mapped page? */
8008749cfeaSVladimir Davydov 			WARN_ON_ONCE(1);
8018749cfeaSVladimir Davydov 		}
8028eaededeSKirill A. Shutemov 
8038eaededeSKirill A. Shutemov 		pra->mapcount--;
8048eaededeSKirill A. Shutemov 	}
80571e3aac0SAndrea Arcangeli 
80633c3fc71SVladimir Davydov 	if (referenced)
80733c3fc71SVladimir Davydov 		clear_page_idle(page);
80833c3fc71SVladimir Davydov 	if (test_and_clear_page_young(page))
80933c3fc71SVladimir Davydov 		referenced++;
81033c3fc71SVladimir Davydov 
8119f32624bSJoonsoo Kim 	if (referenced) {
8129f32624bSJoonsoo Kim 		pra->referenced++;
8139f32624bSJoonsoo Kim 		pra->vm_flags |= vma->vm_flags;
8141da177e4SLinus Torvalds 	}
8151da177e4SLinus Torvalds 
8169f32624bSJoonsoo Kim 	if (!pra->mapcount)
817e4b82222SMinchan Kim 		return false; /* To break the loop */
8189f32624bSJoonsoo Kim 
819e4b82222SMinchan Kim 	return true;
8209f32624bSJoonsoo Kim }
8219f32624bSJoonsoo Kim 
8229f32624bSJoonsoo Kim static bool invalid_page_referenced_vma(struct vm_area_struct *vma, void *arg)
8231da177e4SLinus Torvalds {
8249f32624bSJoonsoo Kim 	struct page_referenced_arg *pra = arg;
8259f32624bSJoonsoo Kim 	struct mem_cgroup *memcg = pra->memcg;
8261da177e4SLinus Torvalds 
8279f32624bSJoonsoo Kim 	if (!mm_match_cgroup(vma->vm_mm, memcg))
8289f32624bSJoonsoo Kim 		return true;
8291da177e4SLinus Torvalds 
8309f32624bSJoonsoo Kim 	return false;
8311da177e4SLinus Torvalds }
8321da177e4SLinus Torvalds 
8331da177e4SLinus Torvalds /**
8341da177e4SLinus Torvalds  * page_referenced - test if the page was referenced
8351da177e4SLinus Torvalds  * @page: the page to test
8361da177e4SLinus Torvalds  * @is_locked: caller holds lock on the page
83772835c86SJohannes Weiner  * @memcg: target memory cgroup
8386fe6b7e3SWu Fengguang  * @vm_flags: collect encountered vma->vm_flags who actually referenced the page
8391da177e4SLinus Torvalds  *
8401da177e4SLinus Torvalds  * Quick test_and_clear_referenced for all mappings to a page,
8411da177e4SLinus Torvalds  * returns the number of ptes which referenced the page.
8421da177e4SLinus Torvalds  */
8436fe6b7e3SWu Fengguang int page_referenced(struct page *page,
8446fe6b7e3SWu Fengguang 		    int is_locked,
84572835c86SJohannes Weiner 		    struct mem_cgroup *memcg,
8466fe6b7e3SWu Fengguang 		    unsigned long *vm_flags)
8471da177e4SLinus Torvalds {
8485ad64688SHugh Dickins 	int we_locked = 0;
8499f32624bSJoonsoo Kim 	struct page_referenced_arg pra = {
850b20ce5e0SKirill A. Shutemov 		.mapcount = total_mapcount(page),
8519f32624bSJoonsoo Kim 		.memcg = memcg,
8529f32624bSJoonsoo Kim 	};
8539f32624bSJoonsoo Kim 	struct rmap_walk_control rwc = {
8549f32624bSJoonsoo Kim 		.rmap_one = page_referenced_one,
8559f32624bSJoonsoo Kim 		.arg = (void *)&pra,
8569f32624bSJoonsoo Kim 		.anon_lock = page_lock_anon_vma_read,
8579f32624bSJoonsoo Kim 	};
8581da177e4SLinus Torvalds 
8596fe6b7e3SWu Fengguang 	*vm_flags = 0;
860059d8442SHuang Shijie 	if (!pra.mapcount)
8619f32624bSJoonsoo Kim 		return 0;
8629f32624bSJoonsoo Kim 
8639f32624bSJoonsoo Kim 	if (!page_rmapping(page))
8649f32624bSJoonsoo Kim 		return 0;
8659f32624bSJoonsoo Kim 
8665ad64688SHugh Dickins 	if (!is_locked && (!PageAnon(page) || PageKsm(page))) {
8675ad64688SHugh Dickins 		we_locked = trylock_page(page);
8689f32624bSJoonsoo Kim 		if (!we_locked)
8699f32624bSJoonsoo Kim 			return 1;
8705ad64688SHugh Dickins 	}
8719f32624bSJoonsoo Kim 
8729f32624bSJoonsoo Kim 	/*
8739f32624bSJoonsoo Kim 	 * If we are reclaiming on behalf of a cgroup, skip
8749f32624bSJoonsoo Kim 	 * counting on behalf of references from different
8759f32624bSJoonsoo Kim 	 * cgroups
8769f32624bSJoonsoo Kim 	 */
8779f32624bSJoonsoo Kim 	if (memcg) {
8789f32624bSJoonsoo Kim 		rwc.invalid_vma = invalid_page_referenced_vma;
8795ad64688SHugh Dickins 	}
8809f32624bSJoonsoo Kim 
881c24f386cSMinchan Kim 	rmap_walk(page, &rwc);
8829f32624bSJoonsoo Kim 	*vm_flags = pra.vm_flags;
8839f32624bSJoonsoo Kim 
8845ad64688SHugh Dickins 	if (we_locked)
8851da177e4SLinus Torvalds 		unlock_page(page);
8869f32624bSJoonsoo Kim 
8879f32624bSJoonsoo Kim 	return pra.referenced;
8881da177e4SLinus Torvalds }
8891da177e4SLinus Torvalds 
890e4b82222SMinchan Kim static bool page_mkclean_one(struct page *page, struct vm_area_struct *vma,
8919853a407SJoonsoo Kim 			    unsigned long address, void *arg)
892d08b3851SPeter Zijlstra {
893f27176cfSKirill A. Shutemov 	struct page_vma_mapped_walk pvmw = {
894f27176cfSKirill A. Shutemov 		.page = page,
895f27176cfSKirill A. Shutemov 		.vma = vma,
896f27176cfSKirill A. Shutemov 		.address = address,
897f27176cfSKirill A. Shutemov 		.flags = PVMW_SYNC,
898f27176cfSKirill A. Shutemov 	};
899ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
9009853a407SJoonsoo Kim 	int *cleaned = arg;
901d08b3851SPeter Zijlstra 
902369ea824SJérôme Glisse 	/*
903369ea824SJérôme Glisse 	 * We have to assume the worse case ie pmd for invalidation. Note that
904369ea824SJérôme Glisse 	 * the page can not be free from this function.
905369ea824SJérôme Glisse 	 */
9067269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
9077269f999SJérôme Glisse 				0, vma, vma->vm_mm, address,
908a50b854eSMatthew Wilcox (Oracle) 				min(vma->vm_end, address + page_size(page)));
909ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
910369ea824SJérôme Glisse 
911f27176cfSKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
912f27176cfSKirill A. Shutemov 		int ret = 0;
913369ea824SJérôme Glisse 
9141f18b296SYueHaibing 		address = pvmw.address;
915f27176cfSKirill A. Shutemov 		if (pvmw.pte) {
916c2fda5feSPeter Zijlstra 			pte_t entry;
917f27176cfSKirill A. Shutemov 			pte_t *pte = pvmw.pte;
918f27176cfSKirill A. Shutemov 
919f27176cfSKirill A. Shutemov 			if (!pte_dirty(*pte) && !pte_write(*pte))
920f27176cfSKirill A. Shutemov 				continue;
921d08b3851SPeter Zijlstra 
922785373b4SLinus Torvalds 			flush_cache_page(vma, address, pte_pfn(*pte));
923785373b4SLinus Torvalds 			entry = ptep_clear_flush(vma, address, pte);
924d08b3851SPeter Zijlstra 			entry = pte_wrprotect(entry);
925c2fda5feSPeter Zijlstra 			entry = pte_mkclean(entry);
926785373b4SLinus Torvalds 			set_pte_at(vma->vm_mm, address, pte, entry);
927d08b3851SPeter Zijlstra 			ret = 1;
928f27176cfSKirill A. Shutemov 		} else {
929f27176cfSKirill A. Shutemov #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
930f27176cfSKirill A. Shutemov 			pmd_t *pmd = pvmw.pmd;
931f27176cfSKirill A. Shutemov 			pmd_t entry;
932d08b3851SPeter Zijlstra 
933f27176cfSKirill A. Shutemov 			if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
934f27176cfSKirill A. Shutemov 				continue;
935f27176cfSKirill A. Shutemov 
936785373b4SLinus Torvalds 			flush_cache_page(vma, address, page_to_pfn(page));
937024eee0eSAneesh Kumar K.V 			entry = pmdp_invalidate(vma, address, pmd);
938f27176cfSKirill A. Shutemov 			entry = pmd_wrprotect(entry);
939f27176cfSKirill A. Shutemov 			entry = pmd_mkclean(entry);
940785373b4SLinus Torvalds 			set_pmd_at(vma->vm_mm, address, pmd, entry);
941f27176cfSKirill A. Shutemov 			ret = 1;
942f27176cfSKirill A. Shutemov #else
943f27176cfSKirill A. Shutemov 			/* unexpected pmd-mapped page? */
944f27176cfSKirill A. Shutemov 			WARN_ON_ONCE(1);
945f27176cfSKirill A. Shutemov #endif
946f27176cfSKirill A. Shutemov 		}
9472ec74c3eSSagi Grimberg 
9480f10851eSJérôme Glisse 		/*
9490f10851eSJérôme Glisse 		 * No need to call mmu_notifier_invalidate_range() as we are
9500f10851eSJérôme Glisse 		 * downgrading page table protection not changing it to point
9510f10851eSJérôme Glisse 		 * to a new page.
9520f10851eSJérôme Glisse 		 *
953ad56b738SMike Rapoport 		 * See Documentation/vm/mmu_notifier.rst
9540f10851eSJérôme Glisse 		 */
9550f10851eSJérôme Glisse 		if (ret)
9569853a407SJoonsoo Kim 			(*cleaned)++;
9579853a407SJoonsoo Kim 	}
958f27176cfSKirill A. Shutemov 
959ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
960369ea824SJérôme Glisse 
961e4b82222SMinchan Kim 	return true;
962d08b3851SPeter Zijlstra }
963d08b3851SPeter Zijlstra 
9649853a407SJoonsoo Kim static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
965d08b3851SPeter Zijlstra {
9669853a407SJoonsoo Kim 	if (vma->vm_flags & VM_SHARED)
967871beb8cSFengguang Wu 		return false;
968d08b3851SPeter Zijlstra 
969871beb8cSFengguang Wu 	return true;
970d08b3851SPeter Zijlstra }
971d08b3851SPeter Zijlstra 
972d08b3851SPeter Zijlstra int page_mkclean(struct page *page)
973d08b3851SPeter Zijlstra {
9749853a407SJoonsoo Kim 	int cleaned = 0;
9759853a407SJoonsoo Kim 	struct address_space *mapping;
9769853a407SJoonsoo Kim 	struct rmap_walk_control rwc = {
9779853a407SJoonsoo Kim 		.arg = (void *)&cleaned,
9789853a407SJoonsoo Kim 		.rmap_one = page_mkclean_one,
9799853a407SJoonsoo Kim 		.invalid_vma = invalid_mkclean_vma,
9809853a407SJoonsoo Kim 	};
981d08b3851SPeter Zijlstra 
982d08b3851SPeter Zijlstra 	BUG_ON(!PageLocked(page));
983d08b3851SPeter Zijlstra 
9849853a407SJoonsoo Kim 	if (!page_mapped(page))
9859853a407SJoonsoo Kim 		return 0;
986d08b3851SPeter Zijlstra 
9879853a407SJoonsoo Kim 	mapping = page_mapping(page);
9889853a407SJoonsoo Kim 	if (!mapping)
9899853a407SJoonsoo Kim 		return 0;
9909853a407SJoonsoo Kim 
9919853a407SJoonsoo Kim 	rmap_walk(page, &rwc);
9929853a407SJoonsoo Kim 
9939853a407SJoonsoo Kim 	return cleaned;
994d08b3851SPeter Zijlstra }
99560b59beaSJaya Kumar EXPORT_SYMBOL_GPL(page_mkclean);
996d08b3851SPeter Zijlstra 
9971da177e4SLinus Torvalds /**
998c44b6743SRik van Riel  * page_move_anon_rmap - move a page to our anon_vma
999c44b6743SRik van Riel  * @page:	the page to move to our anon_vma
1000c44b6743SRik van Riel  * @vma:	the vma the page belongs to
1001c44b6743SRik van Riel  *
1002c44b6743SRik van Riel  * When a page belongs exclusively to one process after a COW event,
1003c44b6743SRik van Riel  * that page can be moved into the anon_vma that belongs to just that
1004c44b6743SRik van Riel  * process, so the rmap code will not search the parent or sibling
1005c44b6743SRik van Riel  * processes.
1006c44b6743SRik van Riel  */
10075a49973dSHugh Dickins void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
1008c44b6743SRik van Riel {
1009c44b6743SRik van Riel 	struct anon_vma *anon_vma = vma->anon_vma;
1010c44b6743SRik van Riel 
10115a49973dSHugh Dickins 	page = compound_head(page);
10125a49973dSHugh Dickins 
1013309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
101481d1b09cSSasha Levin 	VM_BUG_ON_VMA(!anon_vma, vma);
1015c44b6743SRik van Riel 
1016c44b6743SRik van Riel 	anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
1017414e2fb8SVladimir Davydov 	/*
1018414e2fb8SVladimir Davydov 	 * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
1019414e2fb8SVladimir Davydov 	 * simultaneously, so a concurrent reader (eg page_referenced()'s
1020414e2fb8SVladimir Davydov 	 * PageAnon()) will not see one without the other.
1021414e2fb8SVladimir Davydov 	 */
1022414e2fb8SVladimir Davydov 	WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
1023c44b6743SRik van Riel }
1024c44b6743SRik van Riel 
1025c44b6743SRik van Riel /**
102643d8eac4SRandy Dunlap  * __page_set_anon_rmap - set up new anonymous rmap
1027451b9514SKirill Tkhai  * @page:	Page or Hugepage to add to rmap
10284e1c1975SAndi Kleen  * @vma:	VM area to add page to.
10294e1c1975SAndi Kleen  * @address:	User virtual address of the mapping
1030e8a03febSRik van Riel  * @exclusive:	the page is exclusively owned by the current process
10311da177e4SLinus Torvalds  */
10329617d95eSNick Piggin static void __page_set_anon_rmap(struct page *page,
1033e8a03febSRik van Riel 	struct vm_area_struct *vma, unsigned long address, int exclusive)
10341da177e4SLinus Torvalds {
1035e8a03febSRik van Riel 	struct anon_vma *anon_vma = vma->anon_vma;
10362822c1aaSNick Piggin 
1037e8a03febSRik van Riel 	BUG_ON(!anon_vma);
1038ea90002bSLinus Torvalds 
10394e1c1975SAndi Kleen 	if (PageAnon(page))
10404e1c1975SAndi Kleen 		return;
10414e1c1975SAndi Kleen 
1042ea90002bSLinus Torvalds 	/*
1043e8a03febSRik van Riel 	 * If the page isn't exclusively mapped into this vma,
1044e8a03febSRik van Riel 	 * we must use the _oldest_ possible anon_vma for the
1045e8a03febSRik van Riel 	 * page mapping!
1046ea90002bSLinus Torvalds 	 */
10474e1c1975SAndi Kleen 	if (!exclusive)
1048288468c3SAndrea Arcangeli 		anon_vma = anon_vma->root;
1049ea90002bSLinus Torvalds 
10501da177e4SLinus Torvalds 	anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
10512822c1aaSNick Piggin 	page->mapping = (struct address_space *) anon_vma;
10524d7670e0SNick Piggin 	page->index = linear_page_index(vma, address);
10531da177e4SLinus Torvalds }
10549617d95eSNick Piggin 
10559617d95eSNick Piggin /**
105643d8eac4SRandy Dunlap  * __page_check_anon_rmap - sanity check anonymous rmap addition
1057c97a9e10SNick Piggin  * @page:	the page to add the mapping to
1058c97a9e10SNick Piggin  * @vma:	the vm area in which the mapping is added
1059c97a9e10SNick Piggin  * @address:	the user virtual address mapped
1060c97a9e10SNick Piggin  */
1061c97a9e10SNick Piggin static void __page_check_anon_rmap(struct page *page,
1062c97a9e10SNick Piggin 	struct vm_area_struct *vma, unsigned long address)
1063c97a9e10SNick Piggin {
1064c97a9e10SNick Piggin #ifdef CONFIG_DEBUG_VM
1065c97a9e10SNick Piggin 	/*
1066c97a9e10SNick Piggin 	 * The page's anon-rmap details (mapping and index) are guaranteed to
1067c97a9e10SNick Piggin 	 * be set up correctly at this point.
1068c97a9e10SNick Piggin 	 *
1069c97a9e10SNick Piggin 	 * We have exclusion against page_add_anon_rmap because the caller
1070c97a9e10SNick Piggin 	 * always holds the page locked, except if called from page_dup_rmap,
1071c97a9e10SNick Piggin 	 * in which case the page is already known to be setup.
1072c97a9e10SNick Piggin 	 *
1073c97a9e10SNick Piggin 	 * We have exclusion against page_add_new_anon_rmap because those pages
1074c97a9e10SNick Piggin 	 * are initially only visible via the pagetables, and the pte is locked
1075c97a9e10SNick Piggin 	 * over the call to page_add_new_anon_rmap.
1076c97a9e10SNick Piggin 	 */
107744ab57a0SAndrea Arcangeli 	BUG_ON(page_anon_vma(page)->root != vma->anon_vma->root);
107853f9263bSKirill A. Shutemov 	BUG_ON(page_to_pgoff(page) != linear_page_index(vma, address));
1079c97a9e10SNick Piggin #endif
1080c97a9e10SNick Piggin }
1081c97a9e10SNick Piggin 
1082c97a9e10SNick Piggin /**
10839617d95eSNick Piggin  * page_add_anon_rmap - add pte mapping to an anonymous page
10849617d95eSNick Piggin  * @page:	the page to add the mapping to
10859617d95eSNick Piggin  * @vma:	the vm area in which the mapping is added
10869617d95eSNick Piggin  * @address:	the user virtual address mapped
1087d281ee61SKirill A. Shutemov  * @compound:	charge the page as compound or small page
10889617d95eSNick Piggin  *
10895ad64688SHugh Dickins  * The caller needs to hold the pte lock, and the page must be locked in
109080e14822SHugh Dickins  * the anon_vma case: to serialize mapping,index checking after setting,
109180e14822SHugh Dickins  * and to ensure that PageAnon is not being upgraded racily to PageKsm
109280e14822SHugh Dickins  * (but PageKsm is never downgraded to PageAnon).
10939617d95eSNick Piggin  */
10949617d95eSNick Piggin void page_add_anon_rmap(struct page *page,
1095d281ee61SKirill A. Shutemov 	struct vm_area_struct *vma, unsigned long address, bool compound)
10969617d95eSNick Piggin {
1097d281ee61SKirill A. Shutemov 	do_page_add_anon_rmap(page, vma, address, compound ? RMAP_COMPOUND : 0);
1098ad8c2ee8SRik van Riel }
1099ad8c2ee8SRik van Riel 
1100ad8c2ee8SRik van Riel /*
1101ad8c2ee8SRik van Riel  * Special version of the above for do_swap_page, which often runs
1102ad8c2ee8SRik van Riel  * into pages that are exclusively owned by the current process.
1103ad8c2ee8SRik van Riel  * Everybody else should continue to use page_add_anon_rmap above.
1104ad8c2ee8SRik van Riel  */
1105ad8c2ee8SRik van Riel void do_page_add_anon_rmap(struct page *page,
1106d281ee61SKirill A. Shutemov 	struct vm_area_struct *vma, unsigned long address, int flags)
1107ad8c2ee8SRik van Riel {
1108d281ee61SKirill A. Shutemov 	bool compound = flags & RMAP_COMPOUND;
110953f9263bSKirill A. Shutemov 	bool first;
111053f9263bSKirill A. Shutemov 
111153f9263bSKirill A. Shutemov 	if (compound) {
111253f9263bSKirill A. Shutemov 		atomic_t *mapcount;
1113e9b61f19SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageLocked(page), page);
111453f9263bSKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageTransHuge(page), page);
111553f9263bSKirill A. Shutemov 		mapcount = compound_mapcount_ptr(page);
111653f9263bSKirill A. Shutemov 		first = atomic_inc_and_test(mapcount);
111753f9263bSKirill A. Shutemov 	} else {
111853f9263bSKirill A. Shutemov 		first = atomic_inc_and_test(&page->_mapcount);
111953f9263bSKirill A. Shutemov 	}
112053f9263bSKirill A. Shutemov 
112153f9263bSKirill A. Shutemov 	if (first) {
1122d281ee61SKirill A. Shutemov 		int nr = compound ? hpage_nr_pages(page) : 1;
1123bea04b07SJianyu Zhan 		/*
1124bea04b07SJianyu Zhan 		 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1125bea04b07SJianyu Zhan 		 * these counters are not modified in interrupt context, and
1126bea04b07SJianyu Zhan 		 * pte lock(a spinlock) is held, which implies preemption
1127bea04b07SJianyu Zhan 		 * disabled.
1128bea04b07SJianyu Zhan 		 */
112965c45377SKirill A. Shutemov 		if (compound)
113011fb9989SMel Gorman 			__inc_node_page_state(page, NR_ANON_THPS);
11314b9d0fabSMel Gorman 		__mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, nr);
113279134171SAndrea Arcangeli 	}
11335ad64688SHugh Dickins 	if (unlikely(PageKsm(page)))
11345ad64688SHugh Dickins 		return;
11355ad64688SHugh Dickins 
1136309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
113753f9263bSKirill A. Shutemov 
11385dbe0af4SHugh Dickins 	/* address might be in next vma when migration races vma_adjust */
11395ad64688SHugh Dickins 	if (first)
1140d281ee61SKirill A. Shutemov 		__page_set_anon_rmap(page, vma, address,
1141d281ee61SKirill A. Shutemov 				flags & RMAP_EXCLUSIVE);
114269029cd5SKAMEZAWA Hiroyuki 	else
1143c97a9e10SNick Piggin 		__page_check_anon_rmap(page, vma, address);
11441da177e4SLinus Torvalds }
11451da177e4SLinus Torvalds 
114643d8eac4SRandy Dunlap /**
11479617d95eSNick Piggin  * page_add_new_anon_rmap - add pte mapping to a new anonymous page
11489617d95eSNick Piggin  * @page:	the page to add the mapping to
11499617d95eSNick Piggin  * @vma:	the vm area in which the mapping is added
11509617d95eSNick Piggin  * @address:	the user virtual address mapped
1151d281ee61SKirill A. Shutemov  * @compound:	charge the page as compound or small page
11529617d95eSNick Piggin  *
11539617d95eSNick Piggin  * Same as page_add_anon_rmap but must only be called on *new* pages.
11549617d95eSNick Piggin  * This means the inc-and-test can be bypassed.
1155c97a9e10SNick Piggin  * Page does not have to be locked.
11569617d95eSNick Piggin  */
11579617d95eSNick Piggin void page_add_new_anon_rmap(struct page *page,
1158d281ee61SKirill A. Shutemov 	struct vm_area_struct *vma, unsigned long address, bool compound)
11599617d95eSNick Piggin {
1160d281ee61SKirill A. Shutemov 	int nr = compound ? hpage_nr_pages(page) : 1;
1161d281ee61SKirill A. Shutemov 
116281d1b09cSSasha Levin 	VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
1163fa9949daSHugh Dickins 	__SetPageSwapBacked(page);
1164d281ee61SKirill A. Shutemov 	if (compound) {
1165d281ee61SKirill A. Shutemov 		VM_BUG_ON_PAGE(!PageTransHuge(page), page);
116653f9263bSKirill A. Shutemov 		/* increment count (starts at -1) */
116753f9263bSKirill A. Shutemov 		atomic_set(compound_mapcount_ptr(page), 0);
116811fb9989SMel Gorman 		__inc_node_page_state(page, NR_ANON_THPS);
116953f9263bSKirill A. Shutemov 	} else {
117053f9263bSKirill A. Shutemov 		/* Anon THP always mapped first with PMD */
117153f9263bSKirill A. Shutemov 		VM_BUG_ON_PAGE(PageTransCompound(page), page);
117253f9263bSKirill A. Shutemov 		/* increment count (starts at -1) */
117353f9263bSKirill A. Shutemov 		atomic_set(&page->_mapcount, 0);
1174d281ee61SKirill A. Shutemov 	}
11754b9d0fabSMel Gorman 	__mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, nr);
1176e8a03febSRik van Riel 	__page_set_anon_rmap(page, vma, address, 1);
11779617d95eSNick Piggin }
11789617d95eSNick Piggin 
11791da177e4SLinus Torvalds /**
11801da177e4SLinus Torvalds  * page_add_file_rmap - add pte mapping to a file page
11811da177e4SLinus Torvalds  * @page: the page to add the mapping to
1182e8b098fcSMike Rapoport  * @compound: charge the page as compound or small page
11831da177e4SLinus Torvalds  *
1184b8072f09SHugh Dickins  * The caller needs to hold the pte lock.
11851da177e4SLinus Torvalds  */
1186dd78feddSKirill A. Shutemov void page_add_file_rmap(struct page *page, bool compound)
11871da177e4SLinus Torvalds {
1188dd78feddSKirill A. Shutemov 	int i, nr = 1;
1189dd78feddSKirill A. Shutemov 
1190dd78feddSKirill A. Shutemov 	VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
119162cccb8cSJohannes Weiner 	lock_page_memcg(page);
1192dd78feddSKirill A. Shutemov 	if (compound && PageTransHuge(page)) {
1193dd78feddSKirill A. Shutemov 		for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
1194dd78feddSKirill A. Shutemov 			if (atomic_inc_and_test(&page[i]._mapcount))
1195dd78feddSKirill A. Shutemov 				nr++;
1196d69b042fSBalbir Singh 		}
1197dd78feddSKirill A. Shutemov 		if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
1198dd78feddSKirill A. Shutemov 			goto out;
119999cb0dbdSSong Liu 		if (PageSwapBacked(page))
120011fb9989SMel Gorman 			__inc_node_page_state(page, NR_SHMEM_PMDMAPPED);
120199cb0dbdSSong Liu 		else
120299cb0dbdSSong Liu 			__inc_node_page_state(page, NR_FILE_PMDMAPPED);
1203dd78feddSKirill A. Shutemov 	} else {
1204c8efc390SKirill A. Shutemov 		if (PageTransCompound(page) && page_mapping(page)) {
1205c8efc390SKirill A. Shutemov 			VM_WARN_ON_ONCE(!PageLocked(page));
1206c8efc390SKirill A. Shutemov 
12079a73f61bSKirill A. Shutemov 			SetPageDoubleMap(compound_head(page));
12089a73f61bSKirill A. Shutemov 			if (PageMlocked(page))
12099a73f61bSKirill A. Shutemov 				clear_page_mlock(compound_head(page));
12109a73f61bSKirill A. Shutemov 		}
1211dd78feddSKirill A. Shutemov 		if (!atomic_inc_and_test(&page->_mapcount))
1212dd78feddSKirill A. Shutemov 			goto out;
1213dd78feddSKirill A. Shutemov 	}
121400f3ca2cSJohannes Weiner 	__mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
1215dd78feddSKirill A. Shutemov out:
121662cccb8cSJohannes Weiner 	unlock_page_memcg(page);
12171da177e4SLinus Torvalds }
12181da177e4SLinus Torvalds 
1219dd78feddSKirill A. Shutemov static void page_remove_file_rmap(struct page *page, bool compound)
12208186eb6aSJohannes Weiner {
1221dd78feddSKirill A. Shutemov 	int i, nr = 1;
1222dd78feddSKirill A. Shutemov 
122357dea93aSSteve Capper 	VM_BUG_ON_PAGE(compound && !PageHead(page), page);
122462cccb8cSJohannes Weiner 	lock_page_memcg(page);
12258186eb6aSJohannes Weiner 
122653f9263bSKirill A. Shutemov 	/* Hugepages are not counted in NR_FILE_MAPPED for now. */
122753f9263bSKirill A. Shutemov 	if (unlikely(PageHuge(page))) {
122853f9263bSKirill A. Shutemov 		/* hugetlb pages are always mapped with pmds */
122953f9263bSKirill A. Shutemov 		atomic_dec(compound_mapcount_ptr(page));
123053f9263bSKirill A. Shutemov 		goto out;
123153f9263bSKirill A. Shutemov 	}
123253f9263bSKirill A. Shutemov 
12338186eb6aSJohannes Weiner 	/* page still mapped by someone else? */
1234dd78feddSKirill A. Shutemov 	if (compound && PageTransHuge(page)) {
1235dd78feddSKirill A. Shutemov 		for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
1236dd78feddSKirill A. Shutemov 			if (atomic_add_negative(-1, &page[i]._mapcount))
1237dd78feddSKirill A. Shutemov 				nr++;
1238dd78feddSKirill A. Shutemov 		}
1239dd78feddSKirill A. Shutemov 		if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1240dd78feddSKirill A. Shutemov 			goto out;
124199cb0dbdSSong Liu 		if (PageSwapBacked(page))
124211fb9989SMel Gorman 			__dec_node_page_state(page, NR_SHMEM_PMDMAPPED);
124399cb0dbdSSong Liu 		else
124499cb0dbdSSong Liu 			__dec_node_page_state(page, NR_FILE_PMDMAPPED);
1245dd78feddSKirill A. Shutemov 	} else {
12468186eb6aSJohannes Weiner 		if (!atomic_add_negative(-1, &page->_mapcount))
12478186eb6aSJohannes Weiner 			goto out;
1248dd78feddSKirill A. Shutemov 	}
12498186eb6aSJohannes Weiner 
12508186eb6aSJohannes Weiner 	/*
125100f3ca2cSJohannes Weiner 	 * We use the irq-unsafe __{inc|mod}_lruvec_page_state because
12528186eb6aSJohannes Weiner 	 * these counters are not modified in interrupt context, and
12538186eb6aSJohannes Weiner 	 * pte lock(a spinlock) is held, which implies preemption disabled.
12548186eb6aSJohannes Weiner 	 */
125500f3ca2cSJohannes Weiner 	__mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
12568186eb6aSJohannes Weiner 
12578186eb6aSJohannes Weiner 	if (unlikely(PageMlocked(page)))
12588186eb6aSJohannes Weiner 		clear_page_mlock(page);
12598186eb6aSJohannes Weiner out:
126062cccb8cSJohannes Weiner 	unlock_page_memcg(page);
12618186eb6aSJohannes Weiner }
12628186eb6aSJohannes Weiner 
126353f9263bSKirill A. Shutemov static void page_remove_anon_compound_rmap(struct page *page)
126453f9263bSKirill A. Shutemov {
126553f9263bSKirill A. Shutemov 	int i, nr;
126653f9263bSKirill A. Shutemov 
126753f9263bSKirill A. Shutemov 	if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
126853f9263bSKirill A. Shutemov 		return;
126953f9263bSKirill A. Shutemov 
127053f9263bSKirill A. Shutemov 	/* Hugepages are not counted in NR_ANON_PAGES for now. */
127153f9263bSKirill A. Shutemov 	if (unlikely(PageHuge(page)))
127253f9263bSKirill A. Shutemov 		return;
127353f9263bSKirill A. Shutemov 
127453f9263bSKirill A. Shutemov 	if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
127553f9263bSKirill A. Shutemov 		return;
127653f9263bSKirill A. Shutemov 
127711fb9989SMel Gorman 	__dec_node_page_state(page, NR_ANON_THPS);
127853f9263bSKirill A. Shutemov 
127953f9263bSKirill A. Shutemov 	if (TestClearPageDoubleMap(page)) {
128053f9263bSKirill A. Shutemov 		/*
128153f9263bSKirill A. Shutemov 		 * Subpages can be mapped with PTEs too. Check how many of
128253f9263bSKirill A. Shutemov 		 * themi are still mapped.
128353f9263bSKirill A. Shutemov 		 */
128453f9263bSKirill A. Shutemov 		for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
128553f9263bSKirill A. Shutemov 			if (atomic_add_negative(-1, &page[i]._mapcount))
128653f9263bSKirill A. Shutemov 				nr++;
128753f9263bSKirill A. Shutemov 		}
128853f9263bSKirill A. Shutemov 	} else {
128953f9263bSKirill A. Shutemov 		nr = HPAGE_PMD_NR;
129053f9263bSKirill A. Shutemov 	}
129153f9263bSKirill A. Shutemov 
1292e90309c9SKirill A. Shutemov 	if (unlikely(PageMlocked(page)))
1293e90309c9SKirill A. Shutemov 		clear_page_mlock(page);
1294e90309c9SKirill A. Shutemov 
12959a982250SKirill A. Shutemov 	if (nr) {
12964b9d0fabSMel Gorman 		__mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, -nr);
12979a982250SKirill A. Shutemov 		deferred_split_huge_page(page);
12989a982250SKirill A. Shutemov 	}
129953f9263bSKirill A. Shutemov }
130053f9263bSKirill A. Shutemov 
13011da177e4SLinus Torvalds /**
13021da177e4SLinus Torvalds  * page_remove_rmap - take down pte mapping from a page
13031da177e4SLinus Torvalds  * @page:	page to remove mapping from
1304d281ee61SKirill A. Shutemov  * @compound:	uncharge the page as compound or small page
13051da177e4SLinus Torvalds  *
1306b8072f09SHugh Dickins  * The caller needs to hold the pte lock.
13071da177e4SLinus Torvalds  */
1308d281ee61SKirill A. Shutemov void page_remove_rmap(struct page *page, bool compound)
13091da177e4SLinus Torvalds {
1310dd78feddSKirill A. Shutemov 	if (!PageAnon(page))
1311dd78feddSKirill A. Shutemov 		return page_remove_file_rmap(page, compound);
131289c06bd5SKAMEZAWA Hiroyuki 
131353f9263bSKirill A. Shutemov 	if (compound)
131453f9263bSKirill A. Shutemov 		return page_remove_anon_compound_rmap(page);
131553f9263bSKirill A. Shutemov 
1316b904dcfeSKOSAKI Motohiro 	/* page still mapped by someone else? */
1317b904dcfeSKOSAKI Motohiro 	if (!atomic_add_negative(-1, &page->_mapcount))
13188186eb6aSJohannes Weiner 		return;
13198186eb6aSJohannes Weiner 
13201da177e4SLinus Torvalds 	/*
1321bea04b07SJianyu Zhan 	 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1322bea04b07SJianyu Zhan 	 * these counters are not modified in interrupt context, and
1323bea04b07SJianyu Zhan 	 * pte lock(a spinlock) is held, which implies preemption disabled.
13240fe6e20bSNaoya Horiguchi 	 */
13254b9d0fabSMel Gorman 	__dec_node_page_state(page, NR_ANON_MAPPED);
13268186eb6aSJohannes Weiner 
1327e6c509f8SHugh Dickins 	if (unlikely(PageMlocked(page)))
1328e6c509f8SHugh Dickins 		clear_page_mlock(page);
13298186eb6aSJohannes Weiner 
13309a982250SKirill A. Shutemov 	if (PageTransCompound(page))
13319a982250SKirill A. Shutemov 		deferred_split_huge_page(compound_head(page));
13329a982250SKirill A. Shutemov 
133316f8c5b2SHugh Dickins 	/*
13341da177e4SLinus Torvalds 	 * It would be tidy to reset the PageAnon mapping here,
13351da177e4SLinus Torvalds 	 * but that might overwrite a racing page_add_anon_rmap
13361da177e4SLinus Torvalds 	 * which increments mapcount after us but sets mapping
13372d4894b5SMel Gorman 	 * before us: so leave the reset to free_unref_page,
13381da177e4SLinus Torvalds 	 * and remember that it's only reliable while mapped.
13391da177e4SLinus Torvalds 	 * Leaving it set also helps swapoff to reinstate ptes
13401da177e4SLinus Torvalds 	 * faster for those pages still in swapcache.
13411da177e4SLinus Torvalds 	 */
13421da177e4SLinus Torvalds }
13431da177e4SLinus Torvalds 
13441da177e4SLinus Torvalds /*
134552629506SJoonsoo Kim  * @arg: enum ttu_flags will be passed to this argument
13461da177e4SLinus Torvalds  */
1347e4b82222SMinchan Kim static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,
134852629506SJoonsoo Kim 		     unsigned long address, void *arg)
13491da177e4SLinus Torvalds {
13501da177e4SLinus Torvalds 	struct mm_struct *mm = vma->vm_mm;
1351c7ab0d2fSKirill A. Shutemov 	struct page_vma_mapped_walk pvmw = {
1352c7ab0d2fSKirill A. Shutemov 		.page = page,
1353c7ab0d2fSKirill A. Shutemov 		.vma = vma,
1354c7ab0d2fSKirill A. Shutemov 		.address = address,
1355c7ab0d2fSKirill A. Shutemov 	};
13561da177e4SLinus Torvalds 	pte_t pteval;
1357c7ab0d2fSKirill A. Shutemov 	struct page *subpage;
1358785373b4SLinus Torvalds 	bool ret = true;
1359ac46d4f3SJérôme Glisse 	struct mmu_notifier_range range;
1360802a3a92SShaohua Li 	enum ttu_flags flags = (enum ttu_flags)arg;
13611da177e4SLinus Torvalds 
1362b87537d9SHugh Dickins 	/* munlock has nothing to gain from examining un-locked vmas */
1363b87537d9SHugh Dickins 	if ((flags & TTU_MUNLOCK) && !(vma->vm_flags & VM_LOCKED))
1364e4b82222SMinchan Kim 		return true;
1365b87537d9SHugh Dickins 
1366a5430ddaSJérôme Glisse 	if (IS_ENABLED(CONFIG_MIGRATION) && (flags & TTU_MIGRATION) &&
1367a5430ddaSJérôme Glisse 	    is_zone_device_page(page) && !is_device_private_page(page))
1368a5430ddaSJérôme Glisse 		return true;
1369a5430ddaSJérôme Glisse 
1370fec89c10SKirill A. Shutemov 	if (flags & TTU_SPLIT_HUGE_PMD) {
1371fec89c10SKirill A. Shutemov 		split_huge_pmd_address(vma, address,
1372b5ff8161SNaoya Horiguchi 				flags & TTU_SPLIT_FREEZE, page);
1373fec89c10SKirill A. Shutemov 	}
1374fec89c10SKirill A. Shutemov 
1375369ea824SJérôme Glisse 	/*
1376017b1660SMike Kravetz 	 * For THP, we have to assume the worse case ie pmd for invalidation.
1377017b1660SMike Kravetz 	 * For hugetlb, it could be much worse if we need to do pud
1378017b1660SMike Kravetz 	 * invalidation in the case of pmd sharing.
1379017b1660SMike Kravetz 	 *
1380017b1660SMike Kravetz 	 * Note that the page can not be free in this function as call of
1381017b1660SMike Kravetz 	 * try_to_unmap() must hold a reference on the page.
1382369ea824SJérôme Glisse 	 */
13837269f999SJérôme Glisse 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
13846f4f13e8SJérôme Glisse 				address,
1385a50b854eSMatthew Wilcox (Oracle) 				min(vma->vm_end, address + page_size(page)));
1386017b1660SMike Kravetz 	if (PageHuge(page)) {
1387017b1660SMike Kravetz 		/*
1388017b1660SMike Kravetz 		 * If sharing is possible, start and end will be adjusted
1389017b1660SMike Kravetz 		 * accordingly.
1390017b1660SMike Kravetz 		 */
1391ac46d4f3SJérôme Glisse 		adjust_range_if_pmd_sharing_possible(vma, &range.start,
1392ac46d4f3SJérôme Glisse 						     &range.end);
1393017b1660SMike Kravetz 	}
1394ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_start(&range);
1395369ea824SJérôme Glisse 
1396c7ab0d2fSKirill A. Shutemov 	while (page_vma_mapped_walk(&pvmw)) {
1397616b8371SZi Yan #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1398616b8371SZi Yan 		/* PMD-mapped THP migration entry */
1399616b8371SZi Yan 		if (!pvmw.pte && (flags & TTU_MIGRATION)) {
1400616b8371SZi Yan 			VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
1401616b8371SZi Yan 
1402616b8371SZi Yan 			set_pmd_migration_entry(&pvmw, page);
1403616b8371SZi Yan 			continue;
1404616b8371SZi Yan 		}
1405616b8371SZi Yan #endif
1406616b8371SZi Yan 
14071da177e4SLinus Torvalds 		/*
14081da177e4SLinus Torvalds 		 * If the page is mlock()d, we cannot swap it out.
14091da177e4SLinus Torvalds 		 * If it's recently referenced (perhaps page_referenced
14101da177e4SLinus Torvalds 		 * skipped over this mm) then we should reactivate it.
14111da177e4SLinus Torvalds 		 */
141214fa31b8SAndi Kleen 		if (!(flags & TTU_IGNORE_MLOCK)) {
1413b87537d9SHugh Dickins 			if (vma->vm_flags & VM_LOCKED) {
14149a73f61bSKirill A. Shutemov 				/* PTE-mapped THP are never mlocked */
14159a73f61bSKirill A. Shutemov 				if (!PageTransCompound(page)) {
14169a73f61bSKirill A. Shutemov 					/*
14179a73f61bSKirill A. Shutemov 					 * Holding pte lock, we do *not* need
14189a73f61bSKirill A. Shutemov 					 * mmap_sem here
14199a73f61bSKirill A. Shutemov 					 */
1420b87537d9SHugh Dickins 					mlock_vma_page(page);
14219a73f61bSKirill A. Shutemov 				}
1422e4b82222SMinchan Kim 				ret = false;
1423c7ab0d2fSKirill A. Shutemov 				page_vma_mapped_walk_done(&pvmw);
1424c7ab0d2fSKirill A. Shutemov 				break;
1425b87537d9SHugh Dickins 			}
1426daa5ba76SKonstantin Khlebnikov 			if (flags & TTU_MUNLOCK)
1427c7ab0d2fSKirill A. Shutemov 				continue;
142814fa31b8SAndi Kleen 		}
1429c7ab0d2fSKirill A. Shutemov 
14308346242aSKirill A. Shutemov 		/* Unexpected PMD-mapped THP? */
14318346242aSKirill A. Shutemov 		VM_BUG_ON_PAGE(!pvmw.pte, page);
14328346242aSKirill A. Shutemov 
14338346242aSKirill A. Shutemov 		subpage = page - page_to_pfn(page) + pte_pfn(*pvmw.pte);
1434785373b4SLinus Torvalds 		address = pvmw.address;
1435785373b4SLinus Torvalds 
1436017b1660SMike Kravetz 		if (PageHuge(page)) {
1437017b1660SMike Kravetz 			if (huge_pmd_unshare(mm, &address, pvmw.pte)) {
1438017b1660SMike Kravetz 				/*
1439017b1660SMike Kravetz 				 * huge_pmd_unshare unmapped an entire PMD
1440017b1660SMike Kravetz 				 * page.  There is no way of knowing exactly
1441017b1660SMike Kravetz 				 * which PMDs may be cached for this mm, so
1442017b1660SMike Kravetz 				 * we must flush them all.  start/end were
1443017b1660SMike Kravetz 				 * already adjusted above to cover this range.
1444017b1660SMike Kravetz 				 */
1445ac46d4f3SJérôme Glisse 				flush_cache_range(vma, range.start, range.end);
1446ac46d4f3SJérôme Glisse 				flush_tlb_range(vma, range.start, range.end);
1447ac46d4f3SJérôme Glisse 				mmu_notifier_invalidate_range(mm, range.start,
1448ac46d4f3SJérôme Glisse 							      range.end);
1449017b1660SMike Kravetz 
1450017b1660SMike Kravetz 				/*
1451017b1660SMike Kravetz 				 * The ref count of the PMD page was dropped
1452017b1660SMike Kravetz 				 * which is part of the way map counting
1453017b1660SMike Kravetz 				 * is done for shared PMDs.  Return 'true'
1454017b1660SMike Kravetz 				 * here.  When there is no other sharing,
1455017b1660SMike Kravetz 				 * huge_pmd_unshare returns false and we will
1456017b1660SMike Kravetz 				 * unmap the actual page and drop map count
1457017b1660SMike Kravetz 				 * to zero.
1458017b1660SMike Kravetz 				 */
1459017b1660SMike Kravetz 				page_vma_mapped_walk_done(&pvmw);
1460017b1660SMike Kravetz 				break;
1461017b1660SMike Kravetz 			}
1462017b1660SMike Kravetz 		}
14638346242aSKirill A. Shutemov 
1464a5430ddaSJérôme Glisse 		if (IS_ENABLED(CONFIG_MIGRATION) &&
1465a5430ddaSJérôme Glisse 		    (flags & TTU_MIGRATION) &&
1466a5430ddaSJérôme Glisse 		    is_zone_device_page(page)) {
1467a5430ddaSJérôme Glisse 			swp_entry_t entry;
1468a5430ddaSJérôme Glisse 			pte_t swp_pte;
1469a5430ddaSJérôme Glisse 
1470a5430ddaSJérôme Glisse 			pteval = ptep_get_and_clear(mm, pvmw.address, pvmw.pte);
1471a5430ddaSJérôme Glisse 
1472a5430ddaSJérôme Glisse 			/*
1473a5430ddaSJérôme Glisse 			 * Store the pfn of the page in a special migration
1474a5430ddaSJérôme Glisse 			 * pte. do_swap_page() will wait until the migration
1475a5430ddaSJérôme Glisse 			 * pte is removed and then restart fault handling.
1476a5430ddaSJérôme Glisse 			 */
1477a5430ddaSJérôme Glisse 			entry = make_migration_entry(page, 0);
1478a5430ddaSJérôme Glisse 			swp_pte = swp_entry_to_pte(entry);
1479a5430ddaSJérôme Glisse 			if (pte_soft_dirty(pteval))
1480a5430ddaSJérôme Glisse 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1481a5430ddaSJérôme Glisse 			set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
14820f10851eSJérôme Glisse 			/*
14830f10851eSJérôme Glisse 			 * No need to invalidate here it will synchronize on
14840f10851eSJérôme Glisse 			 * against the special swap migration pte.
14851de13ee5SRalph Campbell 			 *
14861de13ee5SRalph Campbell 			 * The assignment to subpage above was computed from a
14871de13ee5SRalph Campbell 			 * swap PTE which results in an invalid pointer.
14881de13ee5SRalph Campbell 			 * Since only PAGE_SIZE pages can currently be
14891de13ee5SRalph Campbell 			 * migrated, just set it to page. This will need to be
14901de13ee5SRalph Campbell 			 * changed when hugepage migrations to device private
14911de13ee5SRalph Campbell 			 * memory are supported.
14920f10851eSJérôme Glisse 			 */
14931de13ee5SRalph Campbell 			subpage = page;
1494a5430ddaSJérôme Glisse 			goto discard;
1495a5430ddaSJérôme Glisse 		}
1496a5430ddaSJérôme Glisse 
149714fa31b8SAndi Kleen 		if (!(flags & TTU_IGNORE_ACCESS)) {
1498785373b4SLinus Torvalds 			if (ptep_clear_flush_young_notify(vma, address,
1499c7ab0d2fSKirill A. Shutemov 						pvmw.pte)) {
1500e4b82222SMinchan Kim 				ret = false;
1501c7ab0d2fSKirill A. Shutemov 				page_vma_mapped_walk_done(&pvmw);
1502c7ab0d2fSKirill A. Shutemov 				break;
15031da177e4SLinus Torvalds 			}
1504b291f000SNick Piggin 		}
15051da177e4SLinus Torvalds 
15061da177e4SLinus Torvalds 		/* Nuke the page table entry. */
1507785373b4SLinus Torvalds 		flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
150872b252aeSMel Gorman 		if (should_defer_flush(mm, flags)) {
150972b252aeSMel Gorman 			/*
1510c7ab0d2fSKirill A. Shutemov 			 * We clear the PTE but do not flush so potentially
1511c7ab0d2fSKirill A. Shutemov 			 * a remote CPU could still be writing to the page.
1512c7ab0d2fSKirill A. Shutemov 			 * If the entry was previously clean then the
1513c7ab0d2fSKirill A. Shutemov 			 * architecture must guarantee that a clear->dirty
1514c7ab0d2fSKirill A. Shutemov 			 * transition on a cached TLB entry is written through
1515c7ab0d2fSKirill A. Shutemov 			 * and traps if the PTE is unmapped.
151672b252aeSMel Gorman 			 */
1517785373b4SLinus Torvalds 			pteval = ptep_get_and_clear(mm, address, pvmw.pte);
151872b252aeSMel Gorman 
1519c7ab0d2fSKirill A. Shutemov 			set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
152072b252aeSMel Gorman 		} else {
1521785373b4SLinus Torvalds 			pteval = ptep_clear_flush(vma, address, pvmw.pte);
152272b252aeSMel Gorman 		}
15231da177e4SLinus Torvalds 
1524c7ab0d2fSKirill A. Shutemov 		/* Move the dirty bit to the page. Now the pte is gone. */
15251da177e4SLinus Torvalds 		if (pte_dirty(pteval))
15261da177e4SLinus Torvalds 			set_page_dirty(page);
15271da177e4SLinus Torvalds 
1528365e9c87SHugh Dickins 		/* Update high watermark before we lower rss */
1529365e9c87SHugh Dickins 		update_hiwater_rss(mm);
1530365e9c87SHugh Dickins 
1531888b9f7cSAndi Kleen 		if (PageHWPoison(page) && !(flags & TTU_IGNORE_HWPOISON)) {
15325fd27b8eSPunit Agrawal 			pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
15335d317b2bSNaoya Horiguchi 			if (PageHuge(page)) {
1534d8c6546bSMatthew Wilcox (Oracle) 				hugetlb_count_sub(compound_nr(page), mm);
1535785373b4SLinus Torvalds 				set_huge_swap_pte_at(mm, address,
15365fd27b8eSPunit Agrawal 						     pvmw.pte, pteval,
15375fd27b8eSPunit Agrawal 						     vma_mmu_pagesize(vma));
15385d317b2bSNaoya Horiguchi 			} else {
1539eca56ff9SJerome Marchand 				dec_mm_counter(mm, mm_counter(page));
1540785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
15415f24ae58SNaoya Horiguchi 			}
1542c7ab0d2fSKirill A. Shutemov 
1543bce73e48SChristian Borntraeger 		} else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
154445961722SKonstantin Weitz 			/*
154545961722SKonstantin Weitz 			 * The guest indicated that the page content is of no
154645961722SKonstantin Weitz 			 * interest anymore. Simply discard the pte, vmscan
154745961722SKonstantin Weitz 			 * will take care of the rest.
1548bce73e48SChristian Borntraeger 			 * A future reference will then fault in a new zero
1549bce73e48SChristian Borntraeger 			 * page. When userfaultfd is active, we must not drop
1550bce73e48SChristian Borntraeger 			 * this page though, as its main user (postcopy
1551bce73e48SChristian Borntraeger 			 * migration) will not expect userfaults on already
1552bce73e48SChristian Borntraeger 			 * copied pages.
155345961722SKonstantin Weitz 			 */
1554eca56ff9SJerome Marchand 			dec_mm_counter(mm, mm_counter(page));
15550f10851eSJérôme Glisse 			/* We have to invalidate as we cleared the pte */
15560f10851eSJérôme Glisse 			mmu_notifier_invalidate_range(mm, address,
15570f10851eSJérôme Glisse 						      address + PAGE_SIZE);
1558c7ab0d2fSKirill A. Shutemov 		} else if (IS_ENABLED(CONFIG_MIGRATION) &&
1559b5ff8161SNaoya Horiguchi 				(flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))) {
1560470f119fSHugh Dickins 			swp_entry_t entry;
1561470f119fSHugh Dickins 			pte_t swp_pte;
1562ca827d55SKhalid Aziz 
1563ca827d55SKhalid Aziz 			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1564ca827d55SKhalid Aziz 				set_pte_at(mm, address, pvmw.pte, pteval);
1565ca827d55SKhalid Aziz 				ret = false;
1566ca827d55SKhalid Aziz 				page_vma_mapped_walk_done(&pvmw);
1567ca827d55SKhalid Aziz 				break;
1568ca827d55SKhalid Aziz 			}
1569ca827d55SKhalid Aziz 
1570470f119fSHugh Dickins 			/*
1571470f119fSHugh Dickins 			 * Store the pfn of the page in a special migration
1572470f119fSHugh Dickins 			 * pte. do_swap_page() will wait until the migration
1573470f119fSHugh Dickins 			 * pte is removed and then restart fault handling.
1574470f119fSHugh Dickins 			 */
1575c7ab0d2fSKirill A. Shutemov 			entry = make_migration_entry(subpage,
1576c7ab0d2fSKirill A. Shutemov 					pte_write(pteval));
1577470f119fSHugh Dickins 			swp_pte = swp_entry_to_pte(entry);
1578470f119fSHugh Dickins 			if (pte_soft_dirty(pteval))
1579470f119fSHugh Dickins 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1580785373b4SLinus Torvalds 			set_pte_at(mm, address, pvmw.pte, swp_pte);
15810f10851eSJérôme Glisse 			/*
15820f10851eSJérôme Glisse 			 * No need to invalidate here it will synchronize on
15830f10851eSJérôme Glisse 			 * against the special swap migration pte.
15840f10851eSJérôme Glisse 			 */
1585888b9f7cSAndi Kleen 		} else if (PageAnon(page)) {
1586c7ab0d2fSKirill A. Shutemov 			swp_entry_t entry = { .val = page_private(subpage) };
1587179ef71cSCyrill Gorcunov 			pte_t swp_pte;
15881da177e4SLinus Torvalds 			/*
15891da177e4SLinus Torvalds 			 * Store the swap location in the pte.
15901da177e4SLinus Torvalds 			 * See handle_pte_fault() ...
15911da177e4SLinus Torvalds 			 */
1592eb94a878SMinchan Kim 			if (unlikely(PageSwapBacked(page) != PageSwapCache(page))) {
1593eb94a878SMinchan Kim 				WARN_ON_ONCE(1);
159483612a94SMinchan Kim 				ret = false;
1595369ea824SJérôme Glisse 				/* We have to invalidate as we cleared the pte */
15960f10851eSJérôme Glisse 				mmu_notifier_invalidate_range(mm, address,
15970f10851eSJérôme Glisse 							address + PAGE_SIZE);
1598eb94a878SMinchan Kim 				page_vma_mapped_walk_done(&pvmw);
1599eb94a878SMinchan Kim 				break;
1600eb94a878SMinchan Kim 			}
1601854e9ed0SMinchan Kim 
1602802a3a92SShaohua Li 			/* MADV_FREE page check */
1603802a3a92SShaohua Li 			if (!PageSwapBacked(page)) {
1604a128ca71SShaohua Li 				if (!PageDirty(page)) {
16050f10851eSJérôme Glisse 					/* Invalidate as we cleared the pte */
16060f10851eSJérôme Glisse 					mmu_notifier_invalidate_range(mm,
16070f10851eSJérôme Glisse 						address, address + PAGE_SIZE);
1608854e9ed0SMinchan Kim 					dec_mm_counter(mm, MM_ANONPAGES);
1609854e9ed0SMinchan Kim 					goto discard;
1610854e9ed0SMinchan Kim 				}
1611854e9ed0SMinchan Kim 
1612802a3a92SShaohua Li 				/*
1613802a3a92SShaohua Li 				 * If the page was redirtied, it cannot be
1614802a3a92SShaohua Li 				 * discarded. Remap the page to page table.
1615802a3a92SShaohua Li 				 */
1616785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
161718863d3aSMinchan Kim 				SetPageSwapBacked(page);
1618e4b82222SMinchan Kim 				ret = false;
1619802a3a92SShaohua Li 				page_vma_mapped_walk_done(&pvmw);
1620802a3a92SShaohua Li 				break;
1621802a3a92SShaohua Li 			}
1622802a3a92SShaohua Li 
1623570a335bSHugh Dickins 			if (swap_duplicate(entry) < 0) {
1624785373b4SLinus Torvalds 				set_pte_at(mm, address, pvmw.pte, pteval);
1625e4b82222SMinchan Kim 				ret = false;
1626c7ab0d2fSKirill A. Shutemov 				page_vma_mapped_walk_done(&pvmw);
1627c7ab0d2fSKirill A. Shutemov 				break;
1628570a335bSHugh Dickins 			}
1629ca827d55SKhalid Aziz 			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1630ca827d55SKhalid Aziz 				set_pte_at(mm, address, pvmw.pte, pteval);
1631ca827d55SKhalid Aziz 				ret = false;
1632ca827d55SKhalid Aziz 				page_vma_mapped_walk_done(&pvmw);
1633ca827d55SKhalid Aziz 				break;
1634ca827d55SKhalid Aziz 			}
16351da177e4SLinus Torvalds 			if (list_empty(&mm->mmlist)) {
16361da177e4SLinus Torvalds 				spin_lock(&mmlist_lock);
1637f412ac08SHugh Dickins 				if (list_empty(&mm->mmlist))
16381da177e4SLinus Torvalds 					list_add(&mm->mmlist, &init_mm.mmlist);
16391da177e4SLinus Torvalds 				spin_unlock(&mmlist_lock);
16401da177e4SLinus Torvalds 			}
1641d559db08SKAMEZAWA Hiroyuki 			dec_mm_counter(mm, MM_ANONPAGES);
1642b084d435SKAMEZAWA Hiroyuki 			inc_mm_counter(mm, MM_SWAPENTS);
1643179ef71cSCyrill Gorcunov 			swp_pte = swp_entry_to_pte(entry);
1644179ef71cSCyrill Gorcunov 			if (pte_soft_dirty(pteval))
1645179ef71cSCyrill Gorcunov 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1646785373b4SLinus Torvalds 			set_pte_at(mm, address, pvmw.pte, swp_pte);
16470f10851eSJérôme Glisse 			/* Invalidate as we cleared the pte */
1648369ea824SJérôme Glisse 			mmu_notifier_invalidate_range(mm, address,
1649369ea824SJérôme Glisse 						      address + PAGE_SIZE);
16500f10851eSJérôme Glisse 		} else {
16510f10851eSJérôme Glisse 			/*
1652906f9cdfSHugh Dickins 			 * This is a locked file-backed page, thus it cannot
1653906f9cdfSHugh Dickins 			 * be removed from the page cache and replaced by a new
1654906f9cdfSHugh Dickins 			 * page before mmu_notifier_invalidate_range_end, so no
16550f10851eSJérôme Glisse 			 * concurrent thread might update its page table to
16560f10851eSJérôme Glisse 			 * point at new page while a device still is using this
16570f10851eSJérôme Glisse 			 * page.
16580f10851eSJérôme Glisse 			 *
1659ad56b738SMike Rapoport 			 * See Documentation/vm/mmu_notifier.rst
16600f10851eSJérôme Glisse 			 */
16610f10851eSJérôme Glisse 			dec_mm_counter(mm, mm_counter_file(page));
16620f10851eSJérôme Glisse 		}
16630f10851eSJérôme Glisse discard:
16640f10851eSJérôme Glisse 		/*
16650f10851eSJérôme Glisse 		 * No need to call mmu_notifier_invalidate_range() it has be
16660f10851eSJérôme Glisse 		 * done above for all cases requiring it to happen under page
16670f10851eSJérôme Glisse 		 * table lock before mmu_notifier_invalidate_range_end()
16680f10851eSJérôme Glisse 		 *
1669ad56b738SMike Rapoport 		 * See Documentation/vm/mmu_notifier.rst
16700f10851eSJérôme Glisse 		 */
16710f10851eSJérôme Glisse 		page_remove_rmap(subpage, PageHuge(page));
16720f10851eSJérôme Glisse 		put_page(page);
1673c7ab0d2fSKirill A. Shutemov 	}
1674369ea824SJérôme Glisse 
1675ac46d4f3SJérôme Glisse 	mmu_notifier_invalidate_range_end(&range);
1676369ea824SJérôme Glisse 
1677caed0f48SKOSAKI Motohiro 	return ret;
16781da177e4SLinus Torvalds }
16791da177e4SLinus Torvalds 
168071e3aac0SAndrea Arcangeli bool is_vma_temporary_stack(struct vm_area_struct *vma)
1681a8bef8ffSMel Gorman {
1682a8bef8ffSMel Gorman 	int maybe_stack = vma->vm_flags & (VM_GROWSDOWN | VM_GROWSUP);
1683a8bef8ffSMel Gorman 
1684a8bef8ffSMel Gorman 	if (!maybe_stack)
1685a8bef8ffSMel Gorman 		return false;
1686a8bef8ffSMel Gorman 
1687a8bef8ffSMel Gorman 	if ((vma->vm_flags & VM_STACK_INCOMPLETE_SETUP) ==
1688a8bef8ffSMel Gorman 						VM_STACK_INCOMPLETE_SETUP)
1689a8bef8ffSMel Gorman 		return true;
1690a8bef8ffSMel Gorman 
1691a8bef8ffSMel Gorman 	return false;
1692a8bef8ffSMel Gorman }
1693a8bef8ffSMel Gorman 
169452629506SJoonsoo Kim static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
169552629506SJoonsoo Kim {
169652629506SJoonsoo Kim 	return is_vma_temporary_stack(vma);
169752629506SJoonsoo Kim }
169852629506SJoonsoo Kim 
16992a52bcbcSKirill A. Shutemov static int page_mapcount_is_zero(struct page *page)
170052629506SJoonsoo Kim {
1701c7ab0d2fSKirill A. Shutemov 	return !total_mapcount(page);
17022a52bcbcSKirill A. Shutemov }
170352629506SJoonsoo Kim 
17041da177e4SLinus Torvalds /**
17051da177e4SLinus Torvalds  * try_to_unmap - try to remove all page table mappings to a page
17061da177e4SLinus Torvalds  * @page: the page to get unmapped
170714fa31b8SAndi Kleen  * @flags: action and flags
17081da177e4SLinus Torvalds  *
17091da177e4SLinus Torvalds  * Tries to remove all the page table entries which are mapping this
17101da177e4SLinus Torvalds  * page, used in the pageout path.  Caller must hold the page lock.
17111da177e4SLinus Torvalds  *
1712666e5a40SMinchan Kim  * If unmap is successful, return true. Otherwise, false.
17131da177e4SLinus Torvalds  */
1714666e5a40SMinchan Kim bool try_to_unmap(struct page *page, enum ttu_flags flags)
17151da177e4SLinus Torvalds {
171652629506SJoonsoo Kim 	struct rmap_walk_control rwc = {
171752629506SJoonsoo Kim 		.rmap_one = try_to_unmap_one,
1718802a3a92SShaohua Li 		.arg = (void *)flags,
17192a52bcbcSKirill A. Shutemov 		.done = page_mapcount_is_zero,
172052629506SJoonsoo Kim 		.anon_lock = page_lock_anon_vma_read,
172152629506SJoonsoo Kim 	};
17221da177e4SLinus Torvalds 
172352629506SJoonsoo Kim 	/*
172452629506SJoonsoo Kim 	 * During exec, a temporary VMA is setup and later moved.
172552629506SJoonsoo Kim 	 * The VMA is moved under the anon_vma lock but not the
172652629506SJoonsoo Kim 	 * page tables leading to a race where migration cannot
172752629506SJoonsoo Kim 	 * find the migration ptes. Rather than increasing the
172852629506SJoonsoo Kim 	 * locking requirements of exec(), migration skips
172952629506SJoonsoo Kim 	 * temporary VMAs until after exec() completes.
173052629506SJoonsoo Kim 	 */
1731b5ff8161SNaoya Horiguchi 	if ((flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))
1732b5ff8161SNaoya Horiguchi 	    && !PageKsm(page) && PageAnon(page))
173352629506SJoonsoo Kim 		rwc.invalid_vma = invalid_migration_vma;
173452629506SJoonsoo Kim 
17352a52bcbcSKirill A. Shutemov 	if (flags & TTU_RMAP_LOCKED)
173633fc80e2SMinchan Kim 		rmap_walk_locked(page, &rwc);
17372a52bcbcSKirill A. Shutemov 	else
173833fc80e2SMinchan Kim 		rmap_walk(page, &rwc);
173952629506SJoonsoo Kim 
1740666e5a40SMinchan Kim 	return !page_mapcount(page) ? true : false;
17411da177e4SLinus Torvalds }
174281b4082dSNikita Danilov 
17432a52bcbcSKirill A. Shutemov static int page_not_mapped(struct page *page)
17442a52bcbcSKirill A. Shutemov {
17452a52bcbcSKirill A. Shutemov 	return !page_mapped(page);
17462a52bcbcSKirill A. Shutemov };
17472a52bcbcSKirill A. Shutemov 
1748b291f000SNick Piggin /**
1749b291f000SNick Piggin  * try_to_munlock - try to munlock a page
1750b291f000SNick Piggin  * @page: the page to be munlocked
1751b291f000SNick Piggin  *
1752b291f000SNick Piggin  * Called from munlock code.  Checks all of the VMAs mapping the page
1753b291f000SNick Piggin  * to make sure nobody else has this page mlocked. The page will be
1754b291f000SNick Piggin  * returned with PG_mlocked cleared if no other vmas have it mlocked.
1755b291f000SNick Piggin  */
1756854e9ed0SMinchan Kim 
1757192d7232SMinchan Kim void try_to_munlock(struct page *page)
1758192d7232SMinchan Kim {
1759e8351ac9SJoonsoo Kim 	struct rmap_walk_control rwc = {
1760e8351ac9SJoonsoo Kim 		.rmap_one = try_to_unmap_one,
1761802a3a92SShaohua Li 		.arg = (void *)TTU_MUNLOCK,
1762e8351ac9SJoonsoo Kim 		.done = page_not_mapped,
1763e8351ac9SJoonsoo Kim 		.anon_lock = page_lock_anon_vma_read,
1764e8351ac9SJoonsoo Kim 
1765e8351ac9SJoonsoo Kim 	};
1766e8351ac9SJoonsoo Kim 
1767309381feSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page) || PageLRU(page), page);
1768192d7232SMinchan Kim 	VM_BUG_ON_PAGE(PageCompound(page) && PageDoubleMap(page), page);
1769b291f000SNick Piggin 
1770192d7232SMinchan Kim 	rmap_walk(page, &rwc);
1771b291f000SNick Piggin }
1772e9995ef9SHugh Dickins 
177301d8b20dSPeter Zijlstra void __put_anon_vma(struct anon_vma *anon_vma)
177476545066SRik van Riel {
177576545066SRik van Riel 	struct anon_vma *root = anon_vma->root;
177676545066SRik van Riel 
1777624483f3SAndrey Ryabinin 	anon_vma_free(anon_vma);
177801d8b20dSPeter Zijlstra 	if (root != anon_vma && atomic_dec_and_test(&root->refcount))
177976545066SRik van Riel 		anon_vma_free(root);
178076545066SRik van Riel }
178176545066SRik van Riel 
17820dd1c7bbSJoonsoo Kim static struct anon_vma *rmap_walk_anon_lock(struct page *page,
17830dd1c7bbSJoonsoo Kim 					struct rmap_walk_control *rwc)
1784faecd8ddSJoonsoo Kim {
1785faecd8ddSJoonsoo Kim 	struct anon_vma *anon_vma;
1786faecd8ddSJoonsoo Kim 
17870dd1c7bbSJoonsoo Kim 	if (rwc->anon_lock)
17880dd1c7bbSJoonsoo Kim 		return rwc->anon_lock(page);
17890dd1c7bbSJoonsoo Kim 
1790faecd8ddSJoonsoo Kim 	/*
1791faecd8ddSJoonsoo Kim 	 * Note: remove_migration_ptes() cannot use page_lock_anon_vma_read()
1792faecd8ddSJoonsoo Kim 	 * because that depends on page_mapped(); but not all its usages
1793faecd8ddSJoonsoo Kim 	 * are holding mmap_sem. Users without mmap_sem are required to
1794faecd8ddSJoonsoo Kim 	 * take a reference count to prevent the anon_vma disappearing
1795faecd8ddSJoonsoo Kim 	 */
1796faecd8ddSJoonsoo Kim 	anon_vma = page_anon_vma(page);
1797faecd8ddSJoonsoo Kim 	if (!anon_vma)
1798faecd8ddSJoonsoo Kim 		return NULL;
1799faecd8ddSJoonsoo Kim 
1800faecd8ddSJoonsoo Kim 	anon_vma_lock_read(anon_vma);
1801faecd8ddSJoonsoo Kim 	return anon_vma;
1802faecd8ddSJoonsoo Kim }
1803faecd8ddSJoonsoo Kim 
1804e9995ef9SHugh Dickins /*
1805e8351ac9SJoonsoo Kim  * rmap_walk_anon - do something to anonymous page using the object-based
1806e8351ac9SJoonsoo Kim  * rmap method
1807e8351ac9SJoonsoo Kim  * @page: the page to be handled
1808e8351ac9SJoonsoo Kim  * @rwc: control variable according to each walk type
1809e8351ac9SJoonsoo Kim  *
1810e8351ac9SJoonsoo Kim  * Find all the mappings of a page using the mapping pointer and the vma chains
1811e8351ac9SJoonsoo Kim  * contained in the anon_vma struct it points to.
1812e8351ac9SJoonsoo Kim  *
1813e8351ac9SJoonsoo Kim  * When called from try_to_munlock(), the mmap_sem of the mm containing the vma
1814e8351ac9SJoonsoo Kim  * where the page was found will be held for write.  So, we won't recheck
1815e8351ac9SJoonsoo Kim  * vm_flags for that VMA.  That should be OK, because that vma shouldn't be
1816e8351ac9SJoonsoo Kim  * LOCKED.
1817e9995ef9SHugh Dickins  */
18181df631aeSMinchan Kim static void rmap_walk_anon(struct page *page, struct rmap_walk_control *rwc,
1819b9773199SKirill A. Shutemov 		bool locked)
1820e9995ef9SHugh Dickins {
1821e9995ef9SHugh Dickins 	struct anon_vma *anon_vma;
1822a8fa41adSKirill A. Shutemov 	pgoff_t pgoff_start, pgoff_end;
18235beb4930SRik van Riel 	struct anon_vma_chain *avc;
1824e9995ef9SHugh Dickins 
1825b9773199SKirill A. Shutemov 	if (locked) {
1826b9773199SKirill A. Shutemov 		anon_vma = page_anon_vma(page);
1827b9773199SKirill A. Shutemov 		/* anon_vma disappear under us? */
1828b9773199SKirill A. Shutemov 		VM_BUG_ON_PAGE(!anon_vma, page);
1829b9773199SKirill A. Shutemov 	} else {
18300dd1c7bbSJoonsoo Kim 		anon_vma = rmap_walk_anon_lock(page, rwc);
1831b9773199SKirill A. Shutemov 	}
1832e9995ef9SHugh Dickins 	if (!anon_vma)
18331df631aeSMinchan Kim 		return;
1834faecd8ddSJoonsoo Kim 
1835a8fa41adSKirill A. Shutemov 	pgoff_start = page_to_pgoff(page);
1836a8fa41adSKirill A. Shutemov 	pgoff_end = pgoff_start + hpage_nr_pages(page) - 1;
1837a8fa41adSKirill A. Shutemov 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
1838a8fa41adSKirill A. Shutemov 			pgoff_start, pgoff_end) {
18395beb4930SRik van Riel 		struct vm_area_struct *vma = avc->vma;
1840e9995ef9SHugh Dickins 		unsigned long address = vma_address(page, vma);
18410dd1c7bbSJoonsoo Kim 
1842ad12695fSAndrea Arcangeli 		cond_resched();
1843ad12695fSAndrea Arcangeli 
18440dd1c7bbSJoonsoo Kim 		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
18450dd1c7bbSJoonsoo Kim 			continue;
18460dd1c7bbSJoonsoo Kim 
1847e4b82222SMinchan Kim 		if (!rwc->rmap_one(page, vma, address, rwc->arg))
1848e9995ef9SHugh Dickins 			break;
18490dd1c7bbSJoonsoo Kim 		if (rwc->done && rwc->done(page))
18500dd1c7bbSJoonsoo Kim 			break;
1851e9995ef9SHugh Dickins 	}
1852b9773199SKirill A. Shutemov 
1853b9773199SKirill A. Shutemov 	if (!locked)
18544fc3f1d6SIngo Molnar 		anon_vma_unlock_read(anon_vma);
1855e9995ef9SHugh Dickins }
1856e9995ef9SHugh Dickins 
1857e8351ac9SJoonsoo Kim /*
1858e8351ac9SJoonsoo Kim  * rmap_walk_file - do something to file page using the object-based rmap method
1859e8351ac9SJoonsoo Kim  * @page: the page to be handled
1860e8351ac9SJoonsoo Kim  * @rwc: control variable according to each walk type
1861e8351ac9SJoonsoo Kim  *
1862e8351ac9SJoonsoo Kim  * Find all the mappings of a page using the mapping pointer and the vma chains
1863e8351ac9SJoonsoo Kim  * contained in the address_space struct it points to.
1864e8351ac9SJoonsoo Kim  *
1865e8351ac9SJoonsoo Kim  * When called from try_to_munlock(), the mmap_sem of the mm containing the vma
1866e8351ac9SJoonsoo Kim  * where the page was found will be held for write.  So, we won't recheck
1867e8351ac9SJoonsoo Kim  * vm_flags for that VMA.  That should be OK, because that vma shouldn't be
1868e8351ac9SJoonsoo Kim  * LOCKED.
1869e8351ac9SJoonsoo Kim  */
18701df631aeSMinchan Kim static void rmap_walk_file(struct page *page, struct rmap_walk_control *rwc,
1871b9773199SKirill A. Shutemov 		bool locked)
1872e9995ef9SHugh Dickins {
1873b9773199SKirill A. Shutemov 	struct address_space *mapping = page_mapping(page);
1874a8fa41adSKirill A. Shutemov 	pgoff_t pgoff_start, pgoff_end;
1875e9995ef9SHugh Dickins 	struct vm_area_struct *vma;
1876e9995ef9SHugh Dickins 
18779f32624bSJoonsoo Kim 	/*
18789f32624bSJoonsoo Kim 	 * The page lock not only makes sure that page->mapping cannot
18799f32624bSJoonsoo Kim 	 * suddenly be NULLified by truncation, it makes sure that the
18809f32624bSJoonsoo Kim 	 * structure at mapping cannot be freed and reused yet,
1881c8c06efaSDavidlohr Bueso 	 * so we can safely take mapping->i_mmap_rwsem.
18829f32624bSJoonsoo Kim 	 */
188381d1b09cSSasha Levin 	VM_BUG_ON_PAGE(!PageLocked(page), page);
18849f32624bSJoonsoo Kim 
1885e9995ef9SHugh Dickins 	if (!mapping)
18861df631aeSMinchan Kim 		return;
18873dec0ba0SDavidlohr Bueso 
1888a8fa41adSKirill A. Shutemov 	pgoff_start = page_to_pgoff(page);
1889a8fa41adSKirill A. Shutemov 	pgoff_end = pgoff_start + hpage_nr_pages(page) - 1;
1890b9773199SKirill A. Shutemov 	if (!locked)
18913dec0ba0SDavidlohr Bueso 		i_mmap_lock_read(mapping);
1892a8fa41adSKirill A. Shutemov 	vma_interval_tree_foreach(vma, &mapping->i_mmap,
1893a8fa41adSKirill A. Shutemov 			pgoff_start, pgoff_end) {
1894e9995ef9SHugh Dickins 		unsigned long address = vma_address(page, vma);
18950dd1c7bbSJoonsoo Kim 
1896ad12695fSAndrea Arcangeli 		cond_resched();
1897ad12695fSAndrea Arcangeli 
18980dd1c7bbSJoonsoo Kim 		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
18990dd1c7bbSJoonsoo Kim 			continue;
19000dd1c7bbSJoonsoo Kim 
1901e4b82222SMinchan Kim 		if (!rwc->rmap_one(page, vma, address, rwc->arg))
19020dd1c7bbSJoonsoo Kim 			goto done;
19030dd1c7bbSJoonsoo Kim 		if (rwc->done && rwc->done(page))
19040dd1c7bbSJoonsoo Kim 			goto done;
1905e9995ef9SHugh Dickins 	}
19060dd1c7bbSJoonsoo Kim 
19070dd1c7bbSJoonsoo Kim done:
1908b9773199SKirill A. Shutemov 	if (!locked)
19093dec0ba0SDavidlohr Bueso 		i_mmap_unlock_read(mapping);
1910e9995ef9SHugh Dickins }
1911e9995ef9SHugh Dickins 
19121df631aeSMinchan Kim void rmap_walk(struct page *page, struct rmap_walk_control *rwc)
1913e9995ef9SHugh Dickins {
1914e9995ef9SHugh Dickins 	if (unlikely(PageKsm(page)))
19151df631aeSMinchan Kim 		rmap_walk_ksm(page, rwc);
1916e9995ef9SHugh Dickins 	else if (PageAnon(page))
19171df631aeSMinchan Kim 		rmap_walk_anon(page, rwc, false);
1918e9995ef9SHugh Dickins 	else
19191df631aeSMinchan Kim 		rmap_walk_file(page, rwc, false);
1920b9773199SKirill A. Shutemov }
1921b9773199SKirill A. Shutemov 
1922b9773199SKirill A. Shutemov /* Like rmap_walk, but caller holds relevant rmap lock */
19231df631aeSMinchan Kim void rmap_walk_locked(struct page *page, struct rmap_walk_control *rwc)
1924b9773199SKirill A. Shutemov {
1925b9773199SKirill A. Shutemov 	/* no ksm support for now */
1926b9773199SKirill A. Shutemov 	VM_BUG_ON_PAGE(PageKsm(page), page);
1927b9773199SKirill A. Shutemov 	if (PageAnon(page))
19281df631aeSMinchan Kim 		rmap_walk_anon(page, rwc, true);
1929b9773199SKirill A. Shutemov 	else
19301df631aeSMinchan Kim 		rmap_walk_file(page, rwc, true);
1931e9995ef9SHugh Dickins }
19320fe6e20bSNaoya Horiguchi 
1933e3390f67SNaoya Horiguchi #ifdef CONFIG_HUGETLB_PAGE
19340fe6e20bSNaoya Horiguchi /*
1935451b9514SKirill Tkhai  * The following two functions are for anonymous (private mapped) hugepages.
19360fe6e20bSNaoya Horiguchi  * Unlike common anonymous pages, anonymous hugepages have no accounting code
19370fe6e20bSNaoya Horiguchi  * and no lru code, because we handle hugepages differently from common pages.
19380fe6e20bSNaoya Horiguchi  */
19390fe6e20bSNaoya Horiguchi void hugepage_add_anon_rmap(struct page *page,
19400fe6e20bSNaoya Horiguchi 			    struct vm_area_struct *vma, unsigned long address)
19410fe6e20bSNaoya Horiguchi {
19420fe6e20bSNaoya Horiguchi 	struct anon_vma *anon_vma = vma->anon_vma;
19430fe6e20bSNaoya Horiguchi 	int first;
1944a850ea30SNaoya Horiguchi 
1945a850ea30SNaoya Horiguchi 	BUG_ON(!PageLocked(page));
19460fe6e20bSNaoya Horiguchi 	BUG_ON(!anon_vma);
19475dbe0af4SHugh Dickins 	/* address might be in next vma when migration races vma_adjust */
194853f9263bSKirill A. Shutemov 	first = atomic_inc_and_test(compound_mapcount_ptr(page));
19490fe6e20bSNaoya Horiguchi 	if (first)
1950451b9514SKirill Tkhai 		__page_set_anon_rmap(page, vma, address, 0);
19510fe6e20bSNaoya Horiguchi }
19520fe6e20bSNaoya Horiguchi 
19530fe6e20bSNaoya Horiguchi void hugepage_add_new_anon_rmap(struct page *page,
19540fe6e20bSNaoya Horiguchi 			struct vm_area_struct *vma, unsigned long address)
19550fe6e20bSNaoya Horiguchi {
19560fe6e20bSNaoya Horiguchi 	BUG_ON(address < vma->vm_start || address >= vma->vm_end);
195753f9263bSKirill A. Shutemov 	atomic_set(compound_mapcount_ptr(page), 0);
1958451b9514SKirill Tkhai 	__page_set_anon_rmap(page, vma, address, 1);
19590fe6e20bSNaoya Horiguchi }
1960e3390f67SNaoya Horiguchi #endif /* CONFIG_HUGETLB_PAGE */
1961