• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * mm/rmap.c - physical to virtual reverse mappings
3  *
4  * Copyright 2001, Rik van Riel <riel@conectiva.com.br>
5  * Released under the General Public License (GPL).
6  *
7  * Simple, low overhead reverse mapping scheme.
8  * Please try to keep this thing as modular as possible.
9  *
10  * Provides methods for unmapping each kind of mapped page:
11  * the anon methods track anonymous pages, and
12  * the file methods track pages belonging to an inode.
13  *
14  * Original design by Rik van Riel <riel@conectiva.com.br> 2001
15  * File methods by Dave McCracken <dmccr@us.ibm.com> 2003, 2004
16  * Anonymous methods by Andrea Arcangeli <andrea@suse.de> 2004
17  * Contributions by Hugh Dickins 2003, 2004
18  */
19 
20 /*
21  * Lock ordering in mm:
22  *
23  * inode->i_rwsem	(while writing or truncating, not reading or faulting)
24  *   mm->mmap_lock
25  *     mapping->invalidate_lock (in filemap_fault)
26  *       folio_lock
27  *         hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share, see hugetlbfs below)
28  *           vma_start_write
29  *             mapping->i_mmap_rwsem
30  *               anon_vma->rwsem
31  *                 mm->page_table_lock or pte_lock
32  *                   swap_lock (in swap_duplicate, swap_info_get)
33  *                     mmlist_lock (in mmput, drain_mmlist and others)
34  *                     mapping->private_lock (in block_dirty_folio)
35  *                       folio_lock_memcg move_lock (in block_dirty_folio)
36  *                         i_pages lock (widely used)
37  *                           lruvec->lru_lock (in folio_lruvec_lock_irq)
38  *                     inode->i_lock (in set_page_dirty's __mark_inode_dirty)
39  *                     bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
40  *                       sb_lock (within inode_lock in fs/fs-writeback.c)
41  *                       i_pages lock (widely used, in set_page_dirty,
42  *                                 in arch-dependent flush_dcache_mmap_lock,
43  *                                 within bdi.wb->list_lock in __sync_single_inode)
44  *
45  * anon_vma->rwsem,mapping->i_mmap_rwsem   (memory_failure, collect_procs_anon)
46  *   ->tasklist_lock
47  *     pte map lock
48  *
49  * hugetlbfs PageHuge() take locks in this order:
50  *   hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
51  *     vma_lock (hugetlb specific lock for pmd_sharing)
52  *       mapping->i_mmap_rwsem (also used for hugetlb pmd sharing)
53  *         folio_lock
54  */
55 
56 #include <linux/mm.h>
57 #include <linux/sched/mm.h>
58 #include <linux/sched/task.h>
59 #include <linux/pagemap.h>
60 #include <linux/swap.h>
61 #include <linux/swapops.h>
62 #include <linux/slab.h>
63 #include <linux/init.h>
64 #include <linux/ksm.h>
65 #include <linux/rmap.h>
66 #include <linux/rcupdate.h>
67 #include <linux/export.h>
68 #include <linux/memcontrol.h>
69 #include <linux/mmu_notifier.h>
70 #include <linux/migrate.h>
71 #include <linux/hugetlb.h>
72 #include <linux/huge_mm.h>
73 #include <linux/backing-dev.h>
74 #include <linux/page_idle.h>
75 #include <linux/memremap.h>
76 #include <linux/userfaultfd_k.h>
77 #include <linux/mm_inline.h>
78 #include <linux/oom.h>
79 
80 #include <asm/tlbflush.h>
81 
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/tlb.h>
84 #include <trace/events/migrate.h>
85 #undef CREATE_TRACE_POINTS
86 #include <trace/hooks/mm.h>
87 
88 #undef CREATE_TRACE_POINTS
89 #include <trace/hooks/mm.h>
90 
91 #include "internal.h"
92 
93 static struct kmem_cache *anon_vma_cachep;
94 static struct kmem_cache *anon_vma_chain_cachep;
95 
anon_vma_alloc(void)96 static inline struct anon_vma *anon_vma_alloc(void)
97 {
98 	struct anon_vma *anon_vma;
99 
100 	anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
101 	if (anon_vma) {
102 		atomic_set(&anon_vma->refcount, 1);
103 		anon_vma->num_children = 0;
104 		anon_vma->num_active_vmas = 0;
105 		anon_vma->parent = anon_vma;
106 		/*
107 		 * Initialise the anon_vma root to point to itself. If called
108 		 * from fork, the root will be reset to the parents anon_vma.
109 		 */
110 		anon_vma->root = anon_vma;
111 	}
112 
113 	return anon_vma;
114 }
115 
anon_vma_free(struct anon_vma * anon_vma)116 static inline void anon_vma_free(struct anon_vma *anon_vma)
117 {
118 	VM_BUG_ON(atomic_read(&anon_vma->refcount));
119 
120 	/*
121 	 * Synchronize against folio_lock_anon_vma_read() such that
122 	 * we can safely hold the lock without the anon_vma getting
123 	 * freed.
124 	 *
125 	 * Relies on the full mb implied by the atomic_dec_and_test() from
126 	 * put_anon_vma() against the acquire barrier implied by
127 	 * down_read_trylock() from folio_lock_anon_vma_read(). This orders:
128 	 *
129 	 * folio_lock_anon_vma_read()	VS	put_anon_vma()
130 	 *   down_read_trylock()		  atomic_dec_and_test()
131 	 *   LOCK				  MB
132 	 *   atomic_read()			  rwsem_is_locked()
133 	 *
134 	 * LOCK should suffice since the actual taking of the lock must
135 	 * happen _before_ what follows.
136 	 */
137 	might_sleep();
138 	if (rwsem_is_locked(&anon_vma->root->rwsem)) {
139 		anon_vma_lock_write(anon_vma);
140 		anon_vma_unlock_write(anon_vma);
141 	}
142 
143 	kmem_cache_free(anon_vma_cachep, anon_vma);
144 }
145 
anon_vma_chain_alloc(gfp_t gfp)146 static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
147 {
148 	return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
149 }
150 
anon_vma_chain_free(struct anon_vma_chain * anon_vma_chain)151 static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
152 {
153 	kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
154 }
155 
anon_vma_chain_link(struct vm_area_struct * vma,struct anon_vma_chain * avc,struct anon_vma * anon_vma)156 static void anon_vma_chain_link(struct vm_area_struct *vma,
157 				struct anon_vma_chain *avc,
158 				struct anon_vma *anon_vma)
159 {
160 	avc->vma = vma;
161 	avc->anon_vma = anon_vma;
162 	list_add(&avc->same_vma, &vma->anon_vma_chain);
163 	anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
164 }
165 
166 /**
167  * __anon_vma_prepare - attach an anon_vma to a memory region
168  * @vma: the memory region in question
169  *
170  * This makes sure the memory mapping described by 'vma' has
171  * an 'anon_vma' attached to it, so that we can associate the
172  * anonymous pages mapped into it with that anon_vma.
173  *
174  * The common case will be that we already have one, which
175  * is handled inline by anon_vma_prepare(). But if
176  * not we either need to find an adjacent mapping that we
177  * can re-use the anon_vma from (very common when the only
178  * reason for splitting a vma has been mprotect()), or we
179  * allocate a new one.
180  *
181  * Anon-vma allocations are very subtle, because we may have
182  * optimistically looked up an anon_vma in folio_lock_anon_vma_read()
183  * and that may actually touch the rwsem even in the newly
184  * allocated vma (it depends on RCU to make sure that the
185  * anon_vma isn't actually destroyed).
186  *
187  * As a result, we need to do proper anon_vma locking even
188  * for the new allocation. At the same time, we do not want
189  * to do any locking for the common case of already having
190  * an anon_vma.
191  */
__anon_vma_prepare(struct vm_area_struct * vma)192 int __anon_vma_prepare(struct vm_area_struct *vma)
193 {
194 	struct mm_struct *mm = vma->vm_mm;
195 	struct anon_vma *anon_vma, *allocated;
196 	struct anon_vma_chain *avc;
197 
198 	mmap_assert_locked(mm);
199 	might_sleep();
200 
201 	avc = anon_vma_chain_alloc(GFP_KERNEL);
202 	if (!avc)
203 		goto out_enomem;
204 
205 	anon_vma = find_mergeable_anon_vma(vma);
206 	allocated = NULL;
207 	if (!anon_vma) {
208 		anon_vma = anon_vma_alloc();
209 		if (unlikely(!anon_vma))
210 			goto out_enomem_free_avc;
211 		anon_vma->num_children++; /* self-parent link for new root */
212 		allocated = anon_vma;
213 	}
214 
215 	anon_vma_lock_write(anon_vma);
216 	/* page_table_lock to protect against threads */
217 	spin_lock(&mm->page_table_lock);
218 	if (likely(!vma->anon_vma)) {
219 		vma->anon_vma = anon_vma;
220 		anon_vma_chain_link(vma, avc, anon_vma);
221 		anon_vma->num_active_vmas++;
222 		allocated = NULL;
223 		avc = NULL;
224 	}
225 	spin_unlock(&mm->page_table_lock);
226 	anon_vma_unlock_write(anon_vma);
227 
228 	if (unlikely(allocated))
229 		put_anon_vma(allocated);
230 	if (unlikely(avc))
231 		anon_vma_chain_free(avc);
232 
233 	return 0;
234 
235  out_enomem_free_avc:
236 	anon_vma_chain_free(avc);
237  out_enomem:
238 	return -ENOMEM;
239 }
240 
241 /*
242  * This is a useful helper function for locking the anon_vma root as
243  * we traverse the vma->anon_vma_chain, looping over anon_vma's that
244  * have the same vma.
245  *
246  * Such anon_vma's should have the same root, so you'd expect to see
247  * just a single mutex_lock for the whole traversal.
248  */
lock_anon_vma_root(struct anon_vma * root,struct anon_vma * anon_vma)249 static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
250 {
251 	struct anon_vma *new_root = anon_vma->root;
252 	if (new_root != root) {
253 		if (WARN_ON_ONCE(root))
254 			up_write(&root->rwsem);
255 		root = new_root;
256 		down_write(&root->rwsem);
257 	}
258 	return root;
259 }
260 
unlock_anon_vma_root(struct anon_vma * root)261 static inline void unlock_anon_vma_root(struct anon_vma *root)
262 {
263 	if (root)
264 		up_write(&root->rwsem);
265 }
266 
267 /*
268  * Attach the anon_vmas from src to dst.
269  * Returns 0 on success, -ENOMEM on failure.
270  *
271  * anon_vma_clone() is called by vma_expand(), vma_merge(), __split_vma(),
272  * copy_vma() and anon_vma_fork(). The first four want an exact copy of src,
273  * while the last one, anon_vma_fork(), may try to reuse an existing anon_vma to
274  * prevent endless growth of anon_vma. Since dst->anon_vma is set to NULL before
275  * call, we can identify this case by checking (!dst->anon_vma &&
276  * src->anon_vma).
277  *
278  * If (!dst->anon_vma && src->anon_vma) is true, this function tries to find
279  * and reuse existing anon_vma which has no vmas and only one child anon_vma.
280  * This prevents degradation of anon_vma hierarchy to endless linear chain in
281  * case of constantly forking task. On the other hand, an anon_vma with more
282  * than one child isn't reused even if there was no alive vma, thus rmap
283  * walker has a good chance of avoiding scanning the whole hierarchy when it
284  * searches where page is mapped.
285  */
anon_vma_clone(struct vm_area_struct * dst,struct vm_area_struct * src)286 int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
287 {
288 	struct anon_vma_chain *avc, *pavc;
289 	struct anon_vma *root = NULL;
290 
291 	list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
292 		struct anon_vma *anon_vma;
293 
294 		avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
295 		if (unlikely(!avc)) {
296 			unlock_anon_vma_root(root);
297 			root = NULL;
298 			avc = anon_vma_chain_alloc(GFP_KERNEL);
299 			if (!avc)
300 				goto enomem_failure;
301 		}
302 		anon_vma = pavc->anon_vma;
303 		root = lock_anon_vma_root(root, anon_vma);
304 		anon_vma_chain_link(dst, avc, anon_vma);
305 
306 		/*
307 		 * Reuse existing anon_vma if it has no vma and only one
308 		 * anon_vma child.
309 		 *
310 		 * Root anon_vma is never reused:
311 		 * it has self-parent reference and at least one child.
312 		 */
313 		if (!dst->anon_vma && src->anon_vma &&
314 		    anon_vma->num_children < 2 &&
315 		    anon_vma->num_active_vmas == 0)
316 			dst->anon_vma = anon_vma;
317 	}
318 	if (dst->anon_vma)
319 		dst->anon_vma->num_active_vmas++;
320 	unlock_anon_vma_root(root);
321 	return 0;
322 
323  enomem_failure:
324 	/*
325 	 * dst->anon_vma is dropped here otherwise its num_active_vmas can
326 	 * be incorrectly decremented in unlink_anon_vmas().
327 	 * We can safely do this because callers of anon_vma_clone() don't care
328 	 * about dst->anon_vma if anon_vma_clone() failed.
329 	 */
330 	dst->anon_vma = NULL;
331 	unlink_anon_vmas(dst);
332 	return -ENOMEM;
333 }
334 
335 /*
336  * Attach vma to its own anon_vma, as well as to the anon_vmas that
337  * the corresponding VMA in the parent process is attached to.
338  * Returns 0 on success, non-zero on failure.
339  */
anon_vma_fork(struct vm_area_struct * vma,struct vm_area_struct * pvma)340 int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
341 {
342 	struct anon_vma_chain *avc;
343 	struct anon_vma *anon_vma;
344 	int error;
345 
346 	/* Don't bother if the parent process has no anon_vma here. */
347 	if (!pvma->anon_vma)
348 		return 0;
349 
350 	/* Drop inherited anon_vma, we'll reuse existing or allocate new. */
351 	vma->anon_vma = NULL;
352 
353 	/*
354 	 * First, attach the new VMA to the parent VMA's anon_vmas,
355 	 * so rmap can find non-COWed pages in child processes.
356 	 */
357 	error = anon_vma_clone(vma, pvma);
358 	if (error)
359 		return error;
360 
361 	/* An existing anon_vma has been reused, all done then. */
362 	if (vma->anon_vma)
363 		return 0;
364 
365 	/* Then add our own anon_vma. */
366 	anon_vma = anon_vma_alloc();
367 	if (!anon_vma)
368 		goto out_error;
369 	anon_vma->num_active_vmas++;
370 	avc = anon_vma_chain_alloc(GFP_KERNEL);
371 	if (!avc)
372 		goto out_error_free_anon_vma;
373 
374 	/*
375 	 * The root anon_vma's rwsem is the lock actually used when we
376 	 * lock any of the anon_vmas in this anon_vma tree.
377 	 */
378 	anon_vma->root = pvma->anon_vma->root;
379 	anon_vma->parent = pvma->anon_vma;
380 	/*
381 	 * With refcounts, an anon_vma can stay around longer than the
382 	 * process it belongs to. The root anon_vma needs to be pinned until
383 	 * this anon_vma is freed, because the lock lives in the root.
384 	 */
385 	get_anon_vma(anon_vma->root);
386 	/* Mark this anon_vma as the one where our new (COWed) pages go. */
387 	vma->anon_vma = anon_vma;
388 	anon_vma_lock_write(anon_vma);
389 	anon_vma_chain_link(vma, avc, anon_vma);
390 	anon_vma->parent->num_children++;
391 	anon_vma_unlock_write(anon_vma);
392 
393 	return 0;
394 
395  out_error_free_anon_vma:
396 	put_anon_vma(anon_vma);
397  out_error:
398 	unlink_anon_vmas(vma);
399 	return -ENOMEM;
400 }
401 
unlink_anon_vmas(struct vm_area_struct * vma)402 void unlink_anon_vmas(struct vm_area_struct *vma)
403 {
404 	struct anon_vma_chain *avc, *next;
405 	struct anon_vma *root = NULL;
406 
407 	/*
408 	 * Unlink each anon_vma chained to the VMA.  This list is ordered
409 	 * from newest to oldest, ensuring the root anon_vma gets freed last.
410 	 */
411 	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
412 		struct anon_vma *anon_vma = avc->anon_vma;
413 
414 		root = lock_anon_vma_root(root, anon_vma);
415 		anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
416 
417 		/*
418 		 * Leave empty anon_vmas on the list - we'll need
419 		 * to free them outside the lock.
420 		 */
421 		if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
422 			anon_vma->parent->num_children--;
423 			continue;
424 		}
425 
426 		list_del(&avc->same_vma);
427 		anon_vma_chain_free(avc);
428 	}
429 	if (vma->anon_vma) {
430 		vma->anon_vma->num_active_vmas--;
431 
432 		/*
433 		 * vma would still be needed after unlink, and anon_vma will be prepared
434 		 * when handle fault.
435 		 */
436 		vma->anon_vma = NULL;
437 	}
438 	unlock_anon_vma_root(root);
439 
440 	/*
441 	 * Iterate the list once more, it now only contains empty and unlinked
442 	 * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
443 	 * needing to write-acquire the anon_vma->root->rwsem.
444 	 */
445 	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
446 		struct anon_vma *anon_vma = avc->anon_vma;
447 
448 		VM_WARN_ON(anon_vma->num_children);
449 		VM_WARN_ON(anon_vma->num_active_vmas);
450 		put_anon_vma(anon_vma);
451 
452 		list_del(&avc->same_vma);
453 		anon_vma_chain_free(avc);
454 	}
455 }
456 
anon_vma_ctor(void * data)457 static void anon_vma_ctor(void *data)
458 {
459 	struct anon_vma *anon_vma = data;
460 
461 	init_rwsem(&anon_vma->rwsem);
462 	atomic_set(&anon_vma->refcount, 0);
463 	anon_vma->rb_root = RB_ROOT_CACHED;
464 }
465 
anon_vma_init(void)466 void __init anon_vma_init(void)
467 {
468 	anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
469 			0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
470 			anon_vma_ctor);
471 	anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
472 			SLAB_PANIC|SLAB_ACCOUNT);
473 }
474 
475 /*
476  * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
477  *
478  * Since there is no serialization what so ever against folio_remove_rmap_*()
479  * the best this function can do is return a refcount increased anon_vma
480  * that might have been relevant to this page.
481  *
482  * The page might have been remapped to a different anon_vma or the anon_vma
483  * returned may already be freed (and even reused).
484  *
485  * In case it was remapped to a different anon_vma, the new anon_vma will be a
486  * child of the old anon_vma, and the anon_vma lifetime rules will therefore
487  * ensure that any anon_vma obtained from the page will still be valid for as
488  * long as we observe page_mapped() [ hence all those page_mapped() tests ].
489  *
490  * All users of this function must be very careful when walking the anon_vma
491  * chain and verify that the page in question is indeed mapped in it
492  * [ something equivalent to page_mapped_in_vma() ].
493  *
494  * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
495  * folio_remove_rmap_*() that the anon_vma pointer from page->mapping is valid
496  * if there is a mapcount, we can dereference the anon_vma after observing
497  * those.
498  *
499  * NOTE: the caller should normally hold folio lock when calling this.  If
500  * not, the caller needs to double check the anon_vma didn't change after
501  * taking the anon_vma lock for either read or write (UFFDIO_MOVE can modify it
502  * concurrently without folio lock protection). See folio_lock_anon_vma_read()
503  * which has already covered that, and comment above remap_pages().
504  */
folio_get_anon_vma(struct folio * folio)505 struct anon_vma *folio_get_anon_vma(struct folio *folio)
506 {
507 	struct anon_vma *anon_vma = NULL;
508 	unsigned long anon_mapping;
509 
510 	rcu_read_lock();
511 	anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
512 	if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
513 		goto out;
514 	if (!folio_mapped(folio))
515 		goto out;
516 
517 	anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
518 	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
519 		anon_vma = NULL;
520 		goto out;
521 	}
522 
523 	/*
524 	 * If this folio is still mapped, then its anon_vma cannot have been
525 	 * freed.  But if it has been unmapped, we have no security against the
526 	 * anon_vma structure being freed and reused (for another anon_vma:
527 	 * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
528 	 * above cannot corrupt).
529 	 */
530 	if (!folio_mapped(folio)) {
531 		rcu_read_unlock();
532 		put_anon_vma(anon_vma);
533 		return NULL;
534 	}
535 out:
536 	rcu_read_unlock();
537 
538 	return anon_vma;
539 }
540 
541 /*
542  * Similar to folio_get_anon_vma() except it locks the anon_vma.
543  *
544  * Its a little more complex as it tries to keep the fast path to a single
545  * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
546  * reference like with folio_get_anon_vma() and then block on the mutex
547  * on !rwc->try_lock case.
548  */
folio_lock_anon_vma_read(struct folio * folio,struct rmap_walk_control * rwc)549 struct anon_vma *folio_lock_anon_vma_read(struct folio *folio,
550 					  struct rmap_walk_control *rwc)
551 {
552 	struct anon_vma *anon_vma = NULL;
553 	struct anon_vma *root_anon_vma;
554 	unsigned long anon_mapping;
555 
556 retry:
557 	rcu_read_lock();
558 	anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
559 	if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
560 		goto out;
561 	if (!folio_mapped(folio))
562 		goto out;
563 
564 	anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
565 	root_anon_vma = READ_ONCE(anon_vma->root);
566 	if (down_read_trylock(&root_anon_vma->rwsem)) {
567 		/*
568 		 * folio_move_anon_rmap() might have changed the anon_vma as we
569 		 * might not hold the folio lock here.
570 		 */
571 		if (unlikely((unsigned long)READ_ONCE(folio->mapping) !=
572 			     anon_mapping)) {
573 			up_read(&root_anon_vma->rwsem);
574 			rcu_read_unlock();
575 			goto retry;
576 		}
577 
578 		/*
579 		 * If the folio is still mapped, then this anon_vma is still
580 		 * its anon_vma, and holding the mutex ensures that it will
581 		 * not go away, see anon_vma_free().
582 		 */
583 		if (!folio_mapped(folio)) {
584 			up_read(&root_anon_vma->rwsem);
585 			anon_vma = NULL;
586 		}
587 		goto out;
588 	}
589 
590 	if (rwc && rwc->try_lock) {
591 		anon_vma = NULL;
592 		rwc->contended = true;
593 		goto out;
594 	}
595 
596 	/* trylock failed, we got to sleep */
597 	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
598 		anon_vma = NULL;
599 		goto out;
600 	}
601 
602 	if (!folio_mapped(folio)) {
603 		rcu_read_unlock();
604 		put_anon_vma(anon_vma);
605 		return NULL;
606 	}
607 
608 	/* we pinned the anon_vma, its safe to sleep */
609 	rcu_read_unlock();
610 	anon_vma_lock_read(anon_vma);
611 
612 	/*
613 	 * folio_move_anon_rmap() might have changed the anon_vma as we might
614 	 * not hold the folio lock here.
615 	 */
616 	if (unlikely((unsigned long)READ_ONCE(folio->mapping) !=
617 		     anon_mapping)) {
618 		anon_vma_unlock_read(anon_vma);
619 		put_anon_vma(anon_vma);
620 		anon_vma = NULL;
621 		goto retry;
622 	}
623 
624 	if (atomic_dec_and_test(&anon_vma->refcount)) {
625 		/*
626 		 * Oops, we held the last refcount, release the lock
627 		 * and bail -- can't simply use put_anon_vma() because
628 		 * we'll deadlock on the anon_vma_lock_write() recursion.
629 		 */
630 		anon_vma_unlock_read(anon_vma);
631 		__put_anon_vma(anon_vma);
632 		anon_vma = NULL;
633 	}
634 
635 	return anon_vma;
636 
637 out:
638 	rcu_read_unlock();
639 	return anon_vma;
640 }
641 
642 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
643 /*
644  * Flush TLB entries for recently unmapped pages from remote CPUs. It is
645  * important if a PTE was dirty when it was unmapped that it's flushed
646  * before any IO is initiated on the page to prevent lost writes. Similarly,
647  * it must be flushed before freeing to prevent data leakage.
648  */
try_to_unmap_flush(void)649 void try_to_unmap_flush(void)
650 {
651 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
652 
653 	if (!tlb_ubc->flush_required)
654 		return;
655 
656 	arch_tlbbatch_flush(&tlb_ubc->arch);
657 	tlb_ubc->flush_required = false;
658 	tlb_ubc->writable = false;
659 }
660 
661 /* Flush iff there are potentially writable TLB entries that can race with IO */
try_to_unmap_flush_dirty(void)662 void try_to_unmap_flush_dirty(void)
663 {
664 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
665 
666 	if (tlb_ubc->writable)
667 		try_to_unmap_flush();
668 }
669 
670 /*
671  * Bits 0-14 of mm->tlb_flush_batched record pending generations.
672  * Bits 16-30 of mm->tlb_flush_batched bit record flushed generations.
673  */
674 #define TLB_FLUSH_BATCH_FLUSHED_SHIFT	16
675 #define TLB_FLUSH_BATCH_PENDING_MASK			\
676 	((1 << (TLB_FLUSH_BATCH_FLUSHED_SHIFT - 1)) - 1)
677 #define TLB_FLUSH_BATCH_PENDING_LARGE			\
678 	(TLB_FLUSH_BATCH_PENDING_MASK / 2)
679 
set_tlb_ubc_flush_pending(struct mm_struct * mm,pte_t pteval,unsigned long uaddr)680 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, pte_t pteval,
681 				      unsigned long uaddr)
682 {
683 	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
684 	int batch;
685 	bool writable = pte_dirty(pteval);
686 
687 	if (!pte_accessible(mm, pteval))
688 		return;
689 
690 	arch_tlbbatch_add_pending(&tlb_ubc->arch, mm, uaddr);
691 	tlb_ubc->flush_required = true;
692 
693 	/*
694 	 * Ensure compiler does not re-order the setting of tlb_flush_batched
695 	 * before the PTE is cleared.
696 	 */
697 	barrier();
698 	batch = atomic_read(&mm->tlb_flush_batched);
699 retry:
700 	if ((batch & TLB_FLUSH_BATCH_PENDING_MASK) > TLB_FLUSH_BATCH_PENDING_LARGE) {
701 		/*
702 		 * Prevent `pending' from catching up with `flushed' because of
703 		 * overflow.  Reset `pending' and `flushed' to be 1 and 0 if
704 		 * `pending' becomes large.
705 		 */
706 		if (!atomic_try_cmpxchg(&mm->tlb_flush_batched, &batch, 1))
707 			goto retry;
708 	} else {
709 		atomic_inc(&mm->tlb_flush_batched);
710 	}
711 
712 	/*
713 	 * If the PTE was dirty then it's best to assume it's writable. The
714 	 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
715 	 * before the page is queued for IO.
716 	 */
717 	if (writable)
718 		tlb_ubc->writable = true;
719 }
720 
721 /*
722  * Returns true if the TLB flush should be deferred to the end of a batch of
723  * unmap operations to reduce IPIs.
724  */
should_defer_flush(struct mm_struct * mm,enum ttu_flags flags)725 static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
726 {
727 	if (!(flags & TTU_BATCH_FLUSH))
728 		return false;
729 
730 	return arch_tlbbatch_should_defer(mm);
731 }
732 
733 /*
734  * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
735  * releasing the PTL if TLB flushes are batched. It's possible for a parallel
736  * operation such as mprotect or munmap to race between reclaim unmapping
737  * the page and flushing the page. If this race occurs, it potentially allows
738  * access to data via a stale TLB entry. Tracking all mm's that have TLB
739  * batching in flight would be expensive during reclaim so instead track
740  * whether TLB batching occurred in the past and if so then do a flush here
741  * if required. This will cost one additional flush per reclaim cycle paid
742  * by the first operation at risk such as mprotect and mumap.
743  *
744  * This must be called under the PTL so that an access to tlb_flush_batched
745  * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
746  * via the PTL.
747  */
flush_tlb_batched_pending(struct mm_struct * mm)748 void flush_tlb_batched_pending(struct mm_struct *mm)
749 {
750 	int batch = atomic_read(&mm->tlb_flush_batched);
751 	int pending = batch & TLB_FLUSH_BATCH_PENDING_MASK;
752 	int flushed = batch >> TLB_FLUSH_BATCH_FLUSHED_SHIFT;
753 
754 	if (pending != flushed) {
755 		arch_flush_tlb_batched_pending(mm);
756 		/*
757 		 * If the new TLB flushing is pending during flushing, leave
758 		 * mm->tlb_flush_batched as is, to avoid losing flushing.
759 		 */
760 		atomic_cmpxchg(&mm->tlb_flush_batched, batch,
761 			       pending | (pending << TLB_FLUSH_BATCH_FLUSHED_SHIFT));
762 	}
763 }
764 #else
set_tlb_ubc_flush_pending(struct mm_struct * mm,pte_t pteval,unsigned long uaddr)765 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, pte_t pteval,
766 				      unsigned long uaddr)
767 {
768 }
769 
should_defer_flush(struct mm_struct * mm,enum ttu_flags flags)770 static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
771 {
772 	return false;
773 }
774 #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
775 
776 /*
777  * At what user virtual address is page expected in vma?
778  * Caller should check the page is actually part of the vma.
779  */
page_address_in_vma(struct page * page,struct vm_area_struct * vma)780 unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
781 {
782 	struct folio *folio = page_folio(page);
783 	pgoff_t pgoff;
784 
785 	if (folio_test_anon(folio)) {
786 		struct anon_vma *page__anon_vma = folio_anon_vma(folio);
787 		/*
788 		 * Note: swapoff's unuse_vma() is more efficient with this
789 		 * check, and needs it to match anon_vma when KSM is active.
790 		 */
791 		if (!vma->anon_vma || !page__anon_vma ||
792 		    vma->anon_vma->root != page__anon_vma->root)
793 			return -EFAULT;
794 	} else if (!vma->vm_file) {
795 		return -EFAULT;
796 	} else if (vma->vm_file->f_mapping != folio->mapping) {
797 		return -EFAULT;
798 	}
799 
800 	/* The !page__anon_vma above handles KSM folios */
801 	pgoff = folio->index + folio_page_idx(folio, page);
802 	return vma_address(vma, pgoff, 1);
803 }
804 
805 /*
806  * Returns the actual pmd_t* where we expect 'address' to be mapped from, or
807  * NULL if it doesn't exist.  No guarantees / checks on what the pmd_t*
808  * represents.
809  */
mm_find_pmd(struct mm_struct * mm,unsigned long address)810 pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
811 {
812 	pgd_t *pgd;
813 	p4d_t *p4d;
814 	pud_t *pud;
815 	pmd_t *pmd = NULL;
816 
817 	pgd = pgd_offset(mm, address);
818 	if (!pgd_present(*pgd))
819 		goto out;
820 
821 	p4d = p4d_offset(pgd, address);
822 	if (!p4d_present(*p4d))
823 		goto out;
824 
825 	pud = pud_offset(p4d, address);
826 	if (!pud_present(*pud))
827 		goto out;
828 
829 	pmd = pmd_offset(pud, address);
830 out:
831 	return pmd;
832 }
833 
834 struct folio_referenced_arg {
835 	int mapcount;
836 	int referenced;
837 	unsigned long vm_flags;
838 	struct mem_cgroup *memcg;
839 };
840 
841 /*
842  * arg: folio_referenced_arg will be passed
843  */
folio_referenced_one(struct folio * folio,struct vm_area_struct * vma,unsigned long address,void * arg)844 static bool folio_referenced_one(struct folio *folio,
845 		struct vm_area_struct *vma, unsigned long address, void *arg)
846 {
847 	struct folio_referenced_arg *pra = arg;
848 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
849 	int referenced = 0;
850 	unsigned long start = address, ptes = 0;
851 
852 	while (page_vma_mapped_walk(&pvmw)) {
853 		address = pvmw.address;
854 
855 		if (vma->vm_flags & VM_LOCKED) {
856 			if (!folio_test_large(folio) || !pvmw.pte) {
857 				/* Restore the mlock which got missed */
858 				mlock_vma_folio(folio, vma);
859 				page_vma_mapped_walk_done(&pvmw);
860 				pra->vm_flags |= VM_LOCKED;
861 				return false; /* To break the loop */
862 			}
863 			/*
864 			 * For large folio fully mapped to VMA, will
865 			 * be handled after the pvmw loop.
866 			 *
867 			 * For large folio cross VMA boundaries, it's
868 			 * expected to be picked  by page reclaim. But
869 			 * should skip reference of pages which are in
870 			 * the range of VM_LOCKED vma. As page reclaim
871 			 * should just count the reference of pages out
872 			 * the range of VM_LOCKED vma.
873 			 */
874 			ptes++;
875 			pra->mapcount--;
876 			continue;
877 		}
878 
879 		/*
880 		 * Skip the non-shared swapbacked folio mapped solely by
881 		 * the exiting or OOM-reaped process. This avoids redundant
882 		 * swap-out followed by an immediate unmap.
883 		 */
884 		if ((!atomic_read(&vma->vm_mm->mm_users) ||
885 		    check_stable_address_space(vma->vm_mm)) &&
886 		    folio_test_anon(folio) && folio_test_swapbacked(folio) &&
887 		    !folio_likely_mapped_shared(folio)) {
888 			pra->referenced = -1;
889 			page_vma_mapped_walk_done(&pvmw);
890 			return false;
891 		}
892 
893 		if (lru_gen_enabled() && pvmw.pte) {
894 			trace_android_vh_look_around(&pvmw, folio, vma, &referenced);
895 			if (lru_gen_look_around(&pvmw))
896 				referenced++;
897 		} else if (pvmw.pte) {
898 			if (ptep_clear_flush_young_notify(vma, address,
899 						pvmw.pte))
900 				referenced++;
901 		} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
902 			if (pmdp_clear_flush_young_notify(vma, address,
903 						pvmw.pmd))
904 				referenced++;
905 		} else {
906 			/* unexpected pmd-mapped folio? */
907 			WARN_ON_ONCE(1);
908 		}
909 
910 		pra->mapcount--;
911 	}
912 
913 	if ((vma->vm_flags & VM_LOCKED) &&
914 			folio_test_large(folio) &&
915 			folio_within_vma(folio, vma)) {
916 		unsigned long s_align, e_align;
917 
918 		s_align = ALIGN_DOWN(start, PMD_SIZE);
919 		e_align = ALIGN_DOWN(start + folio_size(folio) - 1, PMD_SIZE);
920 
921 		/* folio doesn't cross page table boundary and fully mapped */
922 		if ((s_align == e_align) && (ptes == folio_nr_pages(folio))) {
923 			/* Restore the mlock which got missed */
924 			mlock_vma_folio(folio, vma);
925 			pra->vm_flags |= VM_LOCKED;
926 			return false; /* To break the loop */
927 		}
928 	}
929 
930 	if (referenced)
931 		folio_clear_idle(folio);
932 	if (folio_test_clear_young(folio))
933 		referenced++;
934 
935 	if (referenced) {
936 		pra->referenced++;
937 		pra->vm_flags |= vma->vm_flags & ~VM_LOCKED;
938 	}
939 
940 	if (!pra->mapcount)
941 		return false; /* To break the loop */
942 
943 	return true;
944 }
945 
invalid_folio_referenced_vma(struct vm_area_struct * vma,void * arg)946 static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
947 {
948 	struct folio_referenced_arg *pra = arg;
949 	struct mem_cgroup *memcg = pra->memcg;
950 
951 	/*
952 	 * Ignore references from this mapping if it has no recency. If the
953 	 * folio has been used in another mapping, we will catch it; if this
954 	 * other mapping is already gone, the unmap path will have set the
955 	 * referenced flag or activated the folio in zap_pte_range().
956 	 */
957 	if (!vma_has_recency(vma))
958 		return true;
959 
960 	/*
961 	 * If we are reclaiming on behalf of a cgroup, skip counting on behalf
962 	 * of references from different cgroups.
963 	 */
964 	if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
965 		return true;
966 
967 	return false;
968 }
969 
970 /**
971  * folio_referenced() - Test if the folio was referenced.
972  * @folio: The folio to test.
973  * @is_locked: Caller holds lock on the folio.
974  * @memcg: target memory cgroup
975  * @vm_flags: A combination of all the vma->vm_flags which referenced the folio.
976  *
977  * Quick test_and_clear_referenced for all mappings of a folio,
978  *
979  * Return: The number of mappings which referenced the folio. Return -1 if
980  * the function bailed out due to rmap lock contention.
981  */
folio_referenced(struct folio * folio,int is_locked,struct mem_cgroup * memcg,unsigned long * vm_flags)982 int folio_referenced(struct folio *folio, int is_locked,
983 		     struct mem_cgroup *memcg, unsigned long *vm_flags)
984 {
985 	bool we_locked = false;
986 	struct folio_referenced_arg pra = {
987 		.mapcount = folio_mapcount(folio),
988 		.memcg = memcg,
989 	};
990 	struct rmap_walk_control rwc = {
991 		.rmap_one = folio_referenced_one,
992 		.arg = (void *)&pra,
993 		.anon_lock = folio_lock_anon_vma_read,
994 		.try_lock = true,
995 		.invalid_vma = invalid_folio_referenced_vma,
996 	};
997 
998 	*vm_flags = 0;
999 	if (!pra.mapcount)
1000 		return 0;
1001 
1002 	if (!folio_raw_mapping(folio))
1003 		return 0;
1004 
1005 	if (!is_locked && (!folio_test_anon(folio) || folio_test_ksm(folio))) {
1006 		we_locked = folio_trylock(folio);
1007 		if (!we_locked)
1008 			return 1;
1009 	}
1010 
1011 	rmap_walk(folio, &rwc);
1012 	*vm_flags = pra.vm_flags;
1013 
1014 	if (we_locked)
1015 		folio_unlock(folio);
1016 
1017 	return rwc.contended ? -1 : pra.referenced;
1018 }
1019 EXPORT_SYMBOL_GPL(folio_referenced);
1020 
page_vma_mkclean_one(struct page_vma_mapped_walk * pvmw)1021 static int page_vma_mkclean_one(struct page_vma_mapped_walk *pvmw)
1022 {
1023 	int cleaned = 0;
1024 	struct vm_area_struct *vma = pvmw->vma;
1025 	struct mmu_notifier_range range;
1026 	unsigned long address = pvmw->address;
1027 
1028 	/*
1029 	 * We have to assume the worse case ie pmd for invalidation. Note that
1030 	 * the folio can not be freed from this function.
1031 	 */
1032 	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE, 0,
1033 				vma->vm_mm, address, vma_address_end(pvmw));
1034 	mmu_notifier_invalidate_range_start(&range);
1035 
1036 	while (page_vma_mapped_walk(pvmw)) {
1037 		int ret = 0;
1038 
1039 		address = pvmw->address;
1040 		if (pvmw->pte) {
1041 			pte_t *pte = pvmw->pte;
1042 			pte_t entry = ptep_get(pte);
1043 
1044 			if (!pte_dirty(entry) && !pte_write(entry))
1045 				continue;
1046 
1047 			flush_cache_page(vma, address, pte_pfn(entry));
1048 			entry = ptep_clear_flush(vma, address, pte);
1049 			entry = pte_wrprotect(entry);
1050 			entry = pte_mkclean(entry);
1051 			set_pte_at(vma->vm_mm, address, pte, entry);
1052 			ret = 1;
1053 		} else {
1054 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1055 			pmd_t *pmd = pvmw->pmd;
1056 			pmd_t entry;
1057 
1058 			if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
1059 				continue;
1060 
1061 			flush_cache_range(vma, address,
1062 					  address + HPAGE_PMD_SIZE);
1063 			entry = pmdp_invalidate(vma, address, pmd);
1064 			entry = pmd_wrprotect(entry);
1065 			entry = pmd_mkclean(entry);
1066 			set_pmd_at(vma->vm_mm, address, pmd, entry);
1067 			ret = 1;
1068 #else
1069 			/* unexpected pmd-mapped folio? */
1070 			WARN_ON_ONCE(1);
1071 #endif
1072 		}
1073 
1074 		if (ret)
1075 			cleaned++;
1076 	}
1077 
1078 	mmu_notifier_invalidate_range_end(&range);
1079 
1080 	return cleaned;
1081 }
1082 
page_mkclean_one(struct folio * folio,struct vm_area_struct * vma,unsigned long address,void * arg)1083 static bool page_mkclean_one(struct folio *folio, struct vm_area_struct *vma,
1084 			     unsigned long address, void *arg)
1085 {
1086 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, PVMW_SYNC);
1087 	int *cleaned = arg;
1088 
1089 	*cleaned += page_vma_mkclean_one(&pvmw);
1090 
1091 	return true;
1092 }
1093 
invalid_mkclean_vma(struct vm_area_struct * vma,void * arg)1094 static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
1095 {
1096 	if (vma->vm_flags & VM_SHARED)
1097 		return false;
1098 
1099 	return true;
1100 }
1101 
folio_mkclean(struct folio * folio)1102 int folio_mkclean(struct folio *folio)
1103 {
1104 	int cleaned = 0;
1105 	struct address_space *mapping;
1106 	struct rmap_walk_control rwc = {
1107 		.arg = (void *)&cleaned,
1108 		.rmap_one = page_mkclean_one,
1109 		.invalid_vma = invalid_mkclean_vma,
1110 	};
1111 
1112 	BUG_ON(!folio_test_locked(folio));
1113 
1114 	if (!folio_mapped(folio))
1115 		return 0;
1116 
1117 	mapping = folio_mapping(folio);
1118 	if (!mapping)
1119 		return 0;
1120 
1121 	rmap_walk(folio, &rwc);
1122 
1123 	return cleaned;
1124 }
1125 EXPORT_SYMBOL_GPL(folio_mkclean);
1126 
1127 /**
1128  * pfn_mkclean_range - Cleans the PTEs (including PMDs) mapped with range of
1129  *                     [@pfn, @pfn + @nr_pages) at the specific offset (@pgoff)
1130  *                     within the @vma of shared mappings. And since clean PTEs
1131  *                     should also be readonly, write protects them too.
1132  * @pfn: start pfn.
1133  * @nr_pages: number of physically contiguous pages srarting with @pfn.
1134  * @pgoff: page offset that the @pfn mapped with.
1135  * @vma: vma that @pfn mapped within.
1136  *
1137  * Returns the number of cleaned PTEs (including PMDs).
1138  */
pfn_mkclean_range(unsigned long pfn,unsigned long nr_pages,pgoff_t pgoff,struct vm_area_struct * vma)1139 int pfn_mkclean_range(unsigned long pfn, unsigned long nr_pages, pgoff_t pgoff,
1140 		      struct vm_area_struct *vma)
1141 {
1142 	struct page_vma_mapped_walk pvmw = {
1143 		.pfn		= pfn,
1144 		.nr_pages	= nr_pages,
1145 		.pgoff		= pgoff,
1146 		.vma		= vma,
1147 		.flags		= PVMW_SYNC,
1148 	};
1149 
1150 	if (invalid_mkclean_vma(vma, NULL))
1151 		return 0;
1152 
1153 	pvmw.address = vma_address(vma, pgoff, nr_pages);
1154 	VM_BUG_ON_VMA(pvmw.address == -EFAULT, vma);
1155 
1156 	return page_vma_mkclean_one(&pvmw);
1157 }
1158 
__folio_add_rmap(struct folio * folio,struct page * page,int nr_pages,enum rmap_level level,int * nr_pmdmapped)1159 static __always_inline unsigned int __folio_add_rmap(struct folio *folio,
1160 		struct page *page, int nr_pages, enum rmap_level level,
1161 		int *nr_pmdmapped)
1162 {
1163 	atomic_t *mapped = &folio->_nr_pages_mapped;
1164 	const int orig_nr_pages = nr_pages;
1165 	int first = 0, nr = 0;
1166 
1167 	__folio_rmap_sanity_checks(folio, page, nr_pages, level);
1168 
1169 	switch (level) {
1170 	case RMAP_LEVEL_PTE:
1171 		if (!folio_test_large(folio)) {
1172 			nr = atomic_inc_and_test(&folio->_mapcount);
1173 			break;
1174 		}
1175 
1176 		do {
1177 			first += atomic_inc_and_test(&page->_mapcount);
1178 		} while (page++, --nr_pages > 0);
1179 
1180 		if (first &&
1181 		    atomic_add_return_relaxed(first, mapped) < ENTIRELY_MAPPED)
1182 			nr = first;
1183 
1184 		atomic_add(orig_nr_pages, &folio->_large_mapcount);
1185 		break;
1186 	case RMAP_LEVEL_PMD:
1187 		first = atomic_inc_and_test(&folio->_entire_mapcount);
1188 		if (first) {
1189 			nr = atomic_add_return_relaxed(ENTIRELY_MAPPED, mapped);
1190 			if (likely(nr < ENTIRELY_MAPPED + ENTIRELY_MAPPED)) {
1191 				*nr_pmdmapped = folio_nr_pages(folio);
1192 				nr = *nr_pmdmapped - (nr & FOLIO_PAGES_MAPPED);
1193 				/* Raced ahead of a remove and another add? */
1194 				if (unlikely(nr < 0))
1195 					nr = 0;
1196 			} else {
1197 				/* Raced ahead of a remove of ENTIRELY_MAPPED */
1198 				nr = 0;
1199 			}
1200 		}
1201 		atomic_inc(&folio->_large_mapcount);
1202 		break;
1203 	}
1204 	return nr;
1205 }
1206 
1207 /**
1208  * folio_move_anon_rmap - move a folio to our anon_vma
1209  * @folio:	The folio to move to our anon_vma
1210  * @vma:	The vma the folio belongs to
1211  *
1212  * When a folio belongs exclusively to one process after a COW event,
1213  * that folio can be moved into the anon_vma that belongs to just that
1214  * process, so the rmap code will not search the parent or sibling processes.
1215  */
folio_move_anon_rmap(struct folio * folio,struct vm_area_struct * vma)1216 void folio_move_anon_rmap(struct folio *folio, struct vm_area_struct *vma)
1217 {
1218 	void *anon_vma = vma->anon_vma;
1219 
1220 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1221 	VM_BUG_ON_VMA(!anon_vma, vma);
1222 
1223 	anon_vma += PAGE_MAPPING_ANON;
1224 	/*
1225 	 * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
1226 	 * simultaneously, so a concurrent reader (eg folio_referenced()'s
1227 	 * folio_test_anon()) will not see one without the other.
1228 	 */
1229 	WRITE_ONCE(folio->mapping, anon_vma);
1230 }
1231 
1232 /**
1233  * __folio_set_anon - set up a new anonymous rmap for a folio
1234  * @folio:	The folio to set up the new anonymous rmap for.
1235  * @vma:	VM area to add the folio to.
1236  * @address:	User virtual address of the mapping
1237  * @exclusive:	Whether the folio is exclusive to the process.
1238  */
__folio_set_anon(struct folio * folio,struct vm_area_struct * vma,unsigned long address,bool exclusive)1239 static void __folio_set_anon(struct folio *folio, struct vm_area_struct *vma,
1240 			     unsigned long address, bool exclusive)
1241 {
1242 	struct anon_vma *anon_vma = vma->anon_vma;
1243 
1244 	BUG_ON(!anon_vma);
1245 
1246 	/*
1247 	 * If the folio isn't exclusive to this vma, we must use the _oldest_
1248 	 * possible anon_vma for the folio mapping!
1249 	 */
1250 	if (!exclusive)
1251 		anon_vma = anon_vma->root;
1252 
1253 	/*
1254 	 * page_idle does a lockless/optimistic rmap scan on folio->mapping.
1255 	 * Make sure the compiler doesn't split the stores of anon_vma and
1256 	 * the PAGE_MAPPING_ANON type identifier, otherwise the rmap code
1257 	 * could mistake the mapping for a struct address_space and crash.
1258 	 */
1259 	anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
1260 	WRITE_ONCE(folio->mapping, (struct address_space *) anon_vma);
1261 	folio->index = linear_page_index(vma, address);
1262 }
1263 
1264 /**
1265  * __page_check_anon_rmap - sanity check anonymous rmap addition
1266  * @folio:	The folio containing @page.
1267  * @page:	the page to check the mapping of
1268  * @vma:	the vm area in which the mapping is added
1269  * @address:	the user virtual address mapped
1270  */
__page_check_anon_rmap(struct folio * folio,struct page * page,struct vm_area_struct * vma,unsigned long address)1271 static void __page_check_anon_rmap(struct folio *folio, struct page *page,
1272 	struct vm_area_struct *vma, unsigned long address)
1273 {
1274 	/*
1275 	 * The page's anon-rmap details (mapping and index) are guaranteed to
1276 	 * be set up correctly at this point.
1277 	 *
1278 	 * We have exclusion against folio_add_anon_rmap_*() because the caller
1279 	 * always holds the page locked.
1280 	 *
1281 	 * We have exclusion against folio_add_new_anon_rmap because those pages
1282 	 * are initially only visible via the pagetables, and the pte is locked
1283 	 * over the call to folio_add_new_anon_rmap.
1284 	 */
1285 	VM_BUG_ON_FOLIO(folio_anon_vma(folio)->root != vma->anon_vma->root,
1286 			folio);
1287 	VM_BUG_ON_PAGE(page_to_pgoff(page) != linear_page_index(vma, address),
1288 		       page);
1289 }
1290 
__folio_mod_stat(struct folio * folio,int nr,int nr_pmdmapped)1291 static void __folio_mod_stat(struct folio *folio, int nr, int nr_pmdmapped)
1292 {
1293 	int idx;
1294 
1295 	if (nr) {
1296 		idx = folio_test_anon(folio) ? NR_ANON_MAPPED : NR_FILE_MAPPED;
1297 		__lruvec_stat_mod_folio(folio, idx, nr);
1298 	}
1299 	if (nr_pmdmapped) {
1300 		if (folio_test_anon(folio)) {
1301 			idx = NR_ANON_THPS;
1302 			__lruvec_stat_mod_folio(folio, idx, nr_pmdmapped);
1303 		} else {
1304 			/* NR_*_PMDMAPPED are not maintained per-memcg */
1305 			idx = folio_test_swapbacked(folio) ?
1306 				NR_SHMEM_PMDMAPPED : NR_FILE_PMDMAPPED;
1307 			__mod_node_page_state(folio_pgdat(folio), idx,
1308 					      nr_pmdmapped);
1309 		}
1310 	}
1311 }
1312 
__folio_add_anon_rmap(struct folio * folio,struct page * page,int nr_pages,struct vm_area_struct * vma,unsigned long address,rmap_t flags,enum rmap_level level)1313 static __always_inline void __folio_add_anon_rmap(struct folio *folio,
1314 		struct page *page, int nr_pages, struct vm_area_struct *vma,
1315 		unsigned long address, rmap_t flags, enum rmap_level level)
1316 {
1317 	int i, nr, nr_pmdmapped = 0;
1318 
1319 	VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
1320 
1321 	nr = __folio_add_rmap(folio, page, nr_pages, level, &nr_pmdmapped);
1322 
1323 	if (likely(!folio_test_ksm(folio)))
1324 		__page_check_anon_rmap(folio, page, vma, address);
1325 
1326 	__folio_mod_stat(folio, nr, nr_pmdmapped);
1327 
1328 	if (flags & RMAP_EXCLUSIVE) {
1329 		switch (level) {
1330 		case RMAP_LEVEL_PTE:
1331 			for (i = 0; i < nr_pages; i++)
1332 				SetPageAnonExclusive(page + i);
1333 			break;
1334 		case RMAP_LEVEL_PMD:
1335 			SetPageAnonExclusive(page);
1336 			break;
1337 		}
1338 	}
1339 	for (i = 0; i < nr_pages; i++) {
1340 		struct page *cur_page = page + i;
1341 
1342 		/* While PTE-mapping a THP we have a PMD and a PTE mapping. */
1343 		VM_WARN_ON_FOLIO((atomic_read(&cur_page->_mapcount) > 0 ||
1344 				  (folio_test_large(folio) &&
1345 				   folio_entire_mapcount(folio) > 1)) &&
1346 				 PageAnonExclusive(cur_page), folio);
1347 	}
1348 
1349 	/*
1350 	 * For large folio, only mlock it if it's fully mapped to VMA. It's
1351 	 * not easy to check whether the large folio is fully mapped to VMA
1352 	 * here. Only mlock normal 4K folio and leave page reclaim to handle
1353 	 * large folio.
1354 	 */
1355 	if (!folio_test_large(folio))
1356 		mlock_vma_folio(folio, vma);
1357 }
1358 
1359 /**
1360  * folio_add_anon_rmap_ptes - add PTE mappings to a page range of an anon folio
1361  * @folio:	The folio to add the mappings to
1362  * @page:	The first page to add
1363  * @nr_pages:	The number of pages which will be mapped
1364  * @vma:	The vm area in which the mappings are added
1365  * @address:	The user virtual address of the first page to map
1366  * @flags:	The rmap flags
1367  *
1368  * The page range of folio is defined by [first_page, first_page + nr_pages)
1369  *
1370  * The caller needs to hold the page table lock, and the page must be locked in
1371  * the anon_vma case: to serialize mapping,index checking after setting,
1372  * and to ensure that an anon folio is not being upgraded racily to a KSM folio
1373  * (but KSM folios are never downgraded).
1374  */
folio_add_anon_rmap_ptes(struct folio * folio,struct page * page,int nr_pages,struct vm_area_struct * vma,unsigned long address,rmap_t flags)1375 void folio_add_anon_rmap_ptes(struct folio *folio, struct page *page,
1376 		int nr_pages, struct vm_area_struct *vma, unsigned long address,
1377 		rmap_t flags)
1378 {
1379 	__folio_add_anon_rmap(folio, page, nr_pages, vma, address, flags,
1380 			      RMAP_LEVEL_PTE);
1381 }
1382 
1383 /**
1384  * folio_add_anon_rmap_pmd - add a PMD mapping to a page range of an anon folio
1385  * @folio:	The folio to add the mapping to
1386  * @page:	The first page to add
1387  * @vma:	The vm area in which the mapping is added
1388  * @address:	The user virtual address of the first page to map
1389  * @flags:	The rmap flags
1390  *
1391  * The page range of folio is defined by [first_page, first_page + HPAGE_PMD_NR)
1392  *
1393  * The caller needs to hold the page table lock, and the page must be locked in
1394  * the anon_vma case: to serialize mapping,index checking after setting.
1395  */
folio_add_anon_rmap_pmd(struct folio * folio,struct page * page,struct vm_area_struct * vma,unsigned long address,rmap_t flags)1396 void folio_add_anon_rmap_pmd(struct folio *folio, struct page *page,
1397 		struct vm_area_struct *vma, unsigned long address, rmap_t flags)
1398 {
1399 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1400 	__folio_add_anon_rmap(folio, page, HPAGE_PMD_NR, vma, address, flags,
1401 			      RMAP_LEVEL_PMD);
1402 #else
1403 	WARN_ON_ONCE(true);
1404 #endif
1405 }
1406 
1407 /**
1408  * folio_add_new_anon_rmap - Add mapping to a new anonymous folio.
1409  * @folio:	The folio to add the mapping to.
1410  * @vma:	the vm area in which the mapping is added
1411  * @address:	the user virtual address mapped
1412  * @flags:	The rmap flags
1413  *
1414  * Like folio_add_anon_rmap_*() but must only be called on *new* folios.
1415  * This means the inc-and-test can be bypassed.
1416  * The folio doesn't necessarily need to be locked while it's exclusive
1417  * unless two threads map it concurrently. However, the folio must be
1418  * locked if it's shared.
1419  *
1420  * If the folio is pmd-mappable, it is accounted as a THP.
1421  */
folio_add_new_anon_rmap(struct folio * folio,struct vm_area_struct * vma,unsigned long address,rmap_t flags)1422 void folio_add_new_anon_rmap(struct folio *folio, struct vm_area_struct *vma,
1423 		unsigned long address, rmap_t flags)
1424 {
1425 	const int nr = folio_nr_pages(folio);
1426 	const bool exclusive = flags & RMAP_EXCLUSIVE;
1427 	int nr_pmdmapped = 0;
1428 
1429 	VM_WARN_ON_FOLIO(folio_test_hugetlb(folio), folio);
1430 	VM_WARN_ON_FOLIO(!exclusive && !folio_test_locked(folio), folio);
1431 	VM_BUG_ON_VMA(address < vma->vm_start ||
1432 			address + (nr << PAGE_SHIFT) > vma->vm_end, vma);
1433 
1434 	/*
1435 	 * VM_DROPPABLE mappings don't swap; instead they're just dropped when
1436 	 * under memory pressure.
1437 	 */
1438 	if (!folio_test_swapbacked(folio) && !(vma->vm_flags & VM_DROPPABLE))
1439 		__folio_set_swapbacked(folio);
1440 	__folio_set_anon(folio, vma, address, exclusive);
1441 
1442 	if (likely(!folio_test_large(folio))) {
1443 		/* increment count (starts at -1) */
1444 		atomic_set(&folio->_mapcount, 0);
1445 		if (exclusive)
1446 			SetPageAnonExclusive(&folio->page);
1447 	} else if (!folio_test_pmd_mappable(folio)) {
1448 		int i;
1449 
1450 		for (i = 0; i < nr; i++) {
1451 			struct page *page = folio_page(folio, i);
1452 
1453 			/* increment count (starts at -1) */
1454 			atomic_set(&page->_mapcount, 0);
1455 			if (exclusive)
1456 				SetPageAnonExclusive(page);
1457 		}
1458 
1459 		/* increment count (starts at -1) */
1460 		atomic_set(&folio->_large_mapcount, nr - 1);
1461 		atomic_set(&folio->_nr_pages_mapped, nr);
1462 	} else {
1463 		/* increment count (starts at -1) */
1464 		atomic_set(&folio->_entire_mapcount, 0);
1465 		/* increment count (starts at -1) */
1466 		atomic_set(&folio->_large_mapcount, 0);
1467 		atomic_set(&folio->_nr_pages_mapped, ENTIRELY_MAPPED);
1468 		if (exclusive)
1469 			SetPageAnonExclusive(&folio->page);
1470 		nr_pmdmapped = nr;
1471 	}
1472 
1473 	__folio_mod_stat(folio, nr, nr_pmdmapped);
1474 	mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
1475 	trace_android_vh_page_add_new_anon_rmap(&folio->page, vma, address);
1476 }
1477 
__folio_add_file_rmap(struct folio * folio,struct page * page,int nr_pages,struct vm_area_struct * vma,enum rmap_level level)1478 static __always_inline void __folio_add_file_rmap(struct folio *folio,
1479 		struct page *page, int nr_pages, struct vm_area_struct *vma,
1480 		enum rmap_level level)
1481 {
1482 	int nr, nr_pmdmapped = 0;
1483 
1484 	VM_WARN_ON_FOLIO(folio_test_anon(folio), folio);
1485 
1486 	nr = __folio_add_rmap(folio, page, nr_pages, level, &nr_pmdmapped);
1487 	__folio_mod_stat(folio, nr, nr_pmdmapped);
1488 
1489 	/* See comments in folio_add_anon_rmap_*() */
1490 	if (!folio_test_large(folio))
1491 		mlock_vma_folio(folio, vma);
1492 }
1493 
1494 /**
1495  * folio_add_file_rmap_ptes - add PTE mappings to a page range of a folio
1496  * @folio:	The folio to add the mappings to
1497  * @page:	The first page to add
1498  * @nr_pages:	The number of pages that will be mapped using PTEs
1499  * @vma:	The vm area in which the mappings are added
1500  *
1501  * The page range of the folio is defined by [page, page + nr_pages)
1502  *
1503  * The caller needs to hold the page table lock.
1504  */
folio_add_file_rmap_ptes(struct folio * folio,struct page * page,int nr_pages,struct vm_area_struct * vma)1505 void folio_add_file_rmap_ptes(struct folio *folio, struct page *page,
1506 		int nr_pages, struct vm_area_struct *vma)
1507 {
1508 	__folio_add_file_rmap(folio, page, nr_pages, vma, RMAP_LEVEL_PTE);
1509 }
1510 
1511 /**
1512  * folio_add_file_rmap_pmd - add a PMD mapping to a page range of a folio
1513  * @folio:	The folio to add the mapping to
1514  * @page:	The first page to add
1515  * @vma:	The vm area in which the mapping is added
1516  *
1517  * The page range of the folio is defined by [page, page + HPAGE_PMD_NR)
1518  *
1519  * The caller needs to hold the page table lock.
1520  */
folio_add_file_rmap_pmd(struct folio * folio,struct page * page,struct vm_area_struct * vma)1521 void folio_add_file_rmap_pmd(struct folio *folio, struct page *page,
1522 		struct vm_area_struct *vma)
1523 {
1524 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1525 	__folio_add_file_rmap(folio, page, HPAGE_PMD_NR, vma, RMAP_LEVEL_PMD);
1526 #else
1527 	WARN_ON_ONCE(true);
1528 #endif
1529 }
1530 
__folio_remove_rmap(struct folio * folio,struct page * page,int nr_pages,struct vm_area_struct * vma,enum rmap_level level)1531 static __always_inline void __folio_remove_rmap(struct folio *folio,
1532 		struct page *page, int nr_pages, struct vm_area_struct *vma,
1533 		enum rmap_level level)
1534 {
1535 	atomic_t *mapped = &folio->_nr_pages_mapped;
1536 	int last = 0, nr = 0, nr_pmdmapped = 0;
1537 	bool partially_mapped = false;
1538 
1539 	__folio_rmap_sanity_checks(folio, page, nr_pages, level);
1540 
1541 	switch (level) {
1542 	case RMAP_LEVEL_PTE:
1543 		if (!folio_test_large(folio)) {
1544 			nr = atomic_add_negative(-1, &folio->_mapcount);
1545 			break;
1546 		}
1547 
1548 		atomic_sub(nr_pages, &folio->_large_mapcount);
1549 		do {
1550 			last += atomic_add_negative(-1, &page->_mapcount);
1551 		} while (page++, --nr_pages > 0);
1552 
1553 		if (last &&
1554 		    atomic_sub_return_relaxed(last, mapped) < ENTIRELY_MAPPED)
1555 			nr = last;
1556 
1557 		partially_mapped = nr && atomic_read(mapped);
1558 		break;
1559 	case RMAP_LEVEL_PMD:
1560 		atomic_dec(&folio->_large_mapcount);
1561 		last = atomic_add_negative(-1, &folio->_entire_mapcount);
1562 		if (last) {
1563 			nr = atomic_sub_return_relaxed(ENTIRELY_MAPPED, mapped);
1564 			if (likely(nr < ENTIRELY_MAPPED)) {
1565 				nr_pmdmapped = folio_nr_pages(folio);
1566 				nr = nr_pmdmapped - (nr & FOLIO_PAGES_MAPPED);
1567 				/* Raced ahead of another remove and an add? */
1568 				if (unlikely(nr < 0))
1569 					nr = 0;
1570 			} else {
1571 				/* An add of ENTIRELY_MAPPED raced ahead */
1572 				nr = 0;
1573 			}
1574 		}
1575 
1576 		partially_mapped = nr && nr < nr_pmdmapped;
1577 		break;
1578 	}
1579 
1580 	/*
1581 	 * Queue anon large folio for deferred split if at least one page of
1582 	 * the folio is unmapped and at least one page is still mapped.
1583 	 *
1584 	 * Check partially_mapped first to ensure it is a large folio.
1585 	 */
1586 	if (partially_mapped && folio_test_anon(folio) &&
1587 	    !folio_test_partially_mapped(folio))
1588 		deferred_split_folio(folio, true);
1589 
1590 	__folio_mod_stat(folio, -nr, -nr_pmdmapped);
1591 
1592 	/*
1593 	 * It would be tidy to reset folio_test_anon mapping when fully
1594 	 * unmapped, but that might overwrite a racing folio_add_anon_rmap_*()
1595 	 * which increments mapcount after us but sets mapping before us:
1596 	 * so leave the reset to free_pages_prepare, and remember that
1597 	 * it's only reliable while mapped.
1598 	 */
1599 
1600 	munlock_vma_folio(folio, vma);
1601 }
1602 
1603 /**
1604  * folio_remove_rmap_ptes - remove PTE mappings from a page range of a folio
1605  * @folio:	The folio to remove the mappings from
1606  * @page:	The first page to remove
1607  * @nr_pages:	The number of pages that will be removed from the mapping
1608  * @vma:	The vm area from which the mappings are removed
1609  *
1610  * The page range of the folio is defined by [page, page + nr_pages)
1611  *
1612  * The caller needs to hold the page table lock.
1613  */
folio_remove_rmap_ptes(struct folio * folio,struct page * page,int nr_pages,struct vm_area_struct * vma)1614 void folio_remove_rmap_ptes(struct folio *folio, struct page *page,
1615 		int nr_pages, struct vm_area_struct *vma)
1616 {
1617 	__folio_remove_rmap(folio, page, nr_pages, vma, RMAP_LEVEL_PTE);
1618 }
1619 
1620 /**
1621  * folio_remove_rmap_pmd - remove a PMD mapping from a page range of a folio
1622  * @folio:	The folio to remove the mapping from
1623  * @page:	The first page to remove
1624  * @vma:	The vm area from which the mapping is removed
1625  *
1626  * The page range of the folio is defined by [page, page + HPAGE_PMD_NR)
1627  *
1628  * The caller needs to hold the page table lock.
1629  */
folio_remove_rmap_pmd(struct folio * folio,struct page * page,struct vm_area_struct * vma)1630 void folio_remove_rmap_pmd(struct folio *folio, struct page *page,
1631 		struct vm_area_struct *vma)
1632 {
1633 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
1634 	__folio_remove_rmap(folio, page, HPAGE_PMD_NR, vma, RMAP_LEVEL_PMD);
1635 #else
1636 	WARN_ON_ONCE(true);
1637 #endif
1638 }
1639 
1640 /*
1641  * @arg: enum ttu_flags will be passed to this argument
1642  */
try_to_unmap_one(struct folio * folio,struct vm_area_struct * vma,unsigned long address,void * arg)1643 static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
1644 		     unsigned long address, void *arg)
1645 {
1646 	struct mm_struct *mm = vma->vm_mm;
1647 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
1648 	pte_t pteval;
1649 	struct page *subpage;
1650 	bool anon_exclusive, ret = true;
1651 	struct mmu_notifier_range range;
1652 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
1653 	unsigned long pfn;
1654 	unsigned long hsz = 0;
1655 
1656 	/*
1657 	 * When racing against e.g. zap_pte_range() on another cpu,
1658 	 * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(),
1659 	 * try_to_unmap() may return before page_mapped() has become false,
1660 	 * if page table locking is skipped: use TTU_SYNC to wait for that.
1661 	 */
1662 	if (flags & TTU_SYNC)
1663 		pvmw.flags = PVMW_SYNC;
1664 
1665 	/*
1666 	 * For THP, we have to assume the worse case ie pmd for invalidation.
1667 	 * For hugetlb, it could be much worse if we need to do pud
1668 	 * invalidation in the case of pmd sharing.
1669 	 *
1670 	 * Note that the folio can not be freed in this function as call of
1671 	 * try_to_unmap() must hold a reference on the folio.
1672 	 */
1673 	range.end = vma_address_end(&pvmw);
1674 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
1675 				address, range.end);
1676 	if (folio_test_hugetlb(folio)) {
1677 		/*
1678 		 * If sharing is possible, start and end will be adjusted
1679 		 * accordingly.
1680 		 */
1681 		adjust_range_if_pmd_sharing_possible(vma, &range.start,
1682 						     &range.end);
1683 
1684 		/* We need the huge page size for set_huge_pte_at() */
1685 		hsz = huge_page_size(hstate_vma(vma));
1686 	}
1687 	mmu_notifier_invalidate_range_start(&range);
1688 
1689 	while (page_vma_mapped_walk(&pvmw)) {
1690 		/*
1691 		 * If the folio is in an mlock()d vma, we must not swap it out.
1692 		 */
1693 		if (!(flags & TTU_IGNORE_MLOCK) &&
1694 		    (vma->vm_flags & VM_LOCKED)) {
1695 			/* Restore the mlock which got missed */
1696 			if (!folio_test_large(folio))
1697 				mlock_vma_folio(folio, vma);
1698 			goto walk_abort;
1699 		}
1700 
1701 		if (!pvmw.pte) {
1702 			if (unmap_huge_pmd_locked(vma, pvmw.address, pvmw.pmd,
1703 						  folio))
1704 				goto walk_done;
1705 
1706 			if (flags & TTU_SPLIT_HUGE_PMD) {
1707 				/*
1708 				 * We temporarily have to drop the PTL and
1709 				 * restart so we can process the PTE-mapped THP.
1710 				 */
1711 				split_huge_pmd_locked(vma, pvmw.address,
1712 						      pvmw.pmd, false, folio);
1713 				flags &= ~TTU_SPLIT_HUGE_PMD;
1714 				page_vma_mapped_walk_restart(&pvmw);
1715 				continue;
1716 			}
1717 		}
1718 
1719 		/* Unexpected PMD-mapped THP? */
1720 		VM_BUG_ON_FOLIO(!pvmw.pte, folio);
1721 
1722 		pfn = pte_pfn(ptep_get(pvmw.pte));
1723 		subpage = folio_page(folio, pfn - folio_pfn(folio));
1724 		address = pvmw.address;
1725 		anon_exclusive = folio_test_anon(folio) &&
1726 				 PageAnonExclusive(subpage);
1727 
1728 		if (folio_test_hugetlb(folio)) {
1729 			bool anon = folio_test_anon(folio);
1730 
1731 			/*
1732 			 * The try_to_unmap() is only passed a hugetlb page
1733 			 * in the case where the hugetlb page is poisoned.
1734 			 */
1735 			VM_BUG_ON_PAGE(!PageHWPoison(subpage), subpage);
1736 			/*
1737 			 * huge_pmd_unshare may unmap an entire PMD page.
1738 			 * There is no way of knowing exactly which PMDs may
1739 			 * be cached for this mm, so we must flush them all.
1740 			 * start/end were already adjusted above to cover this
1741 			 * range.
1742 			 */
1743 			flush_cache_range(vma, range.start, range.end);
1744 
1745 			/*
1746 			 * To call huge_pmd_unshare, i_mmap_rwsem must be
1747 			 * held in write mode.  Caller needs to explicitly
1748 			 * do this outside rmap routines.
1749 			 *
1750 			 * We also must hold hugetlb vma_lock in write mode.
1751 			 * Lock order dictates acquiring vma_lock BEFORE
1752 			 * i_mmap_rwsem.  We can only try lock here and fail
1753 			 * if unsuccessful.
1754 			 */
1755 			if (!anon) {
1756 				VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
1757 				if (!hugetlb_vma_trylock_write(vma))
1758 					goto walk_abort;
1759 				if (huge_pmd_unshare(mm, vma, address, pvmw.pte)) {
1760 					hugetlb_vma_unlock_write(vma);
1761 					flush_tlb_range(vma,
1762 						range.start, range.end);
1763 					/*
1764 					 * The ref count of the PMD page was
1765 					 * dropped which is part of the way map
1766 					 * counting is done for shared PMDs.
1767 					 * Return 'true' here.  When there is
1768 					 * no other sharing, huge_pmd_unshare
1769 					 * returns false and we will unmap the
1770 					 * actual page and drop map count
1771 					 * to zero.
1772 					 */
1773 					goto walk_done;
1774 				}
1775 				hugetlb_vma_unlock_write(vma);
1776 			}
1777 			pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
1778 		} else {
1779 			flush_cache_page(vma, address, pfn);
1780 			/* Nuke the page table entry. */
1781 			if (should_defer_flush(mm, flags)) {
1782 				/*
1783 				 * We clear the PTE but do not flush so potentially
1784 				 * a remote CPU could still be writing to the folio.
1785 				 * If the entry was previously clean then the
1786 				 * architecture must guarantee that a clear->dirty
1787 				 * transition on a cached TLB entry is written through
1788 				 * and traps if the PTE is unmapped.
1789 				 */
1790 				pteval = ptep_get_and_clear(mm, address, pvmw.pte);
1791 
1792 				set_tlb_ubc_flush_pending(mm, pteval, address);
1793 			} else {
1794 				pteval = ptep_clear_flush(vma, address, pvmw.pte);
1795 			}
1796 		}
1797 
1798 		/*
1799 		 * Now the pte is cleared. If this pte was uffd-wp armed,
1800 		 * we may want to replace a none pte with a marker pte if
1801 		 * it's file-backed, so we don't lose the tracking info.
1802 		 */
1803 		pte_install_uffd_wp_if_needed(vma, address, pvmw.pte, pteval);
1804 
1805 		/* Set the dirty flag on the folio now the pte is gone. */
1806 		if (pte_dirty(pteval))
1807 			folio_mark_dirty(folio);
1808 
1809 		/* Update high watermark before we lower rss */
1810 		update_hiwater_rss(mm);
1811 
1812 		if (PageHWPoison(subpage) && (flags & TTU_HWPOISON)) {
1813 			pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
1814 			if (folio_test_hugetlb(folio)) {
1815 				hugetlb_count_sub(folio_nr_pages(folio), mm);
1816 				set_huge_pte_at(mm, address, pvmw.pte, pteval,
1817 						hsz);
1818 			} else {
1819 				dec_mm_counter(mm, mm_counter(folio));
1820 				set_pte_at(mm, address, pvmw.pte, pteval);
1821 			}
1822 
1823 		} else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
1824 			/*
1825 			 * The guest indicated that the page content is of no
1826 			 * interest anymore. Simply discard the pte, vmscan
1827 			 * will take care of the rest.
1828 			 * A future reference will then fault in a new zero
1829 			 * page. When userfaultfd is active, we must not drop
1830 			 * this page though, as its main user (postcopy
1831 			 * migration) will not expect userfaults on already
1832 			 * copied pages.
1833 			 */
1834 			dec_mm_counter(mm, mm_counter(folio));
1835 		} else if (folio_test_anon(folio)) {
1836 			swp_entry_t entry = page_swap_entry(subpage);
1837 			pte_t swp_pte;
1838 			/*
1839 			 * Store the swap location in the pte.
1840 			 * See handle_pte_fault() ...
1841 			 */
1842 			if (unlikely(folio_test_swapbacked(folio) !=
1843 					folio_test_swapcache(folio))) {
1844 				WARN_ON_ONCE(1);
1845 				goto walk_abort;
1846 			}
1847 
1848 			/* MADV_FREE page check */
1849 			if (!folio_test_swapbacked(folio)) {
1850 				int ref_count, map_count;
1851 
1852 				/*
1853 				 * Synchronize with gup_pte_range():
1854 				 * - clear PTE; barrier; read refcount
1855 				 * - inc refcount; barrier; read PTE
1856 				 */
1857 				smp_mb();
1858 
1859 				ref_count = folio_ref_count(folio);
1860 				map_count = folio_mapcount(folio);
1861 
1862 				/*
1863 				 * Order reads for page refcount and dirty flag
1864 				 * (see comments in __remove_mapping()).
1865 				 */
1866 				smp_rmb();
1867 
1868 				/*
1869 				 * The only page refs must be one from isolation
1870 				 * plus the rmap(s) (dropped by discard:).
1871 				 */
1872 				if (ref_count == 1 + map_count &&
1873 				    (!folio_test_dirty(folio) ||
1874 				     /*
1875 				      * Unlike MADV_FREE mappings, VM_DROPPABLE
1876 				      * ones can be dropped even if they've
1877 				      * been dirtied.
1878 				      */
1879 				     (vma->vm_flags & VM_DROPPABLE))) {
1880 					dec_mm_counter(mm, MM_ANONPAGES);
1881 					goto discard;
1882 				}
1883 
1884 				/*
1885 				 * If the folio was redirtied, it cannot be
1886 				 * discarded. Remap the page to page table.
1887 				 */
1888 				set_pte_at(mm, address, pvmw.pte, pteval);
1889 				/*
1890 				 * Unlike MADV_FREE mappings, VM_DROPPABLE ones
1891 				 * never get swap backed on failure to drop.
1892 				 */
1893 				if (!(vma->vm_flags & VM_DROPPABLE))
1894 					folio_set_swapbacked(folio);
1895 				goto walk_abort;
1896 			}
1897 
1898 			if (swap_duplicate(entry) < 0) {
1899 				set_pte_at(mm, address, pvmw.pte, pteval);
1900 				goto walk_abort;
1901 			}
1902 			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1903 				swap_free(entry);
1904 				set_pte_at(mm, address, pvmw.pte, pteval);
1905 				goto walk_abort;
1906 			}
1907 
1908 			/* See folio_try_share_anon_rmap(): clear PTE first. */
1909 			if (anon_exclusive &&
1910 			    folio_try_share_anon_rmap_pte(folio, subpage)) {
1911 				swap_free(entry);
1912 				set_pte_at(mm, address, pvmw.pte, pteval);
1913 				goto walk_abort;
1914 			}
1915 			if (list_empty(&mm->mmlist)) {
1916 				spin_lock(&mmlist_lock);
1917 				if (list_empty(&mm->mmlist))
1918 					list_add(&mm->mmlist, &init_mm.mmlist);
1919 				spin_unlock(&mmlist_lock);
1920 			}
1921 			dec_mm_counter(mm, MM_ANONPAGES);
1922 			inc_mm_counter(mm, MM_SWAPENTS);
1923 			swp_pte = swp_entry_to_pte(entry);
1924 			if (anon_exclusive)
1925 				swp_pte = pte_swp_mkexclusive(swp_pte);
1926 			if (pte_soft_dirty(pteval))
1927 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
1928 			if (pte_uffd_wp(pteval))
1929 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
1930 			set_pte_at(mm, address, pvmw.pte, swp_pte);
1931 		} else {
1932 			/*
1933 			 * This is a locked file-backed folio,
1934 			 * so it cannot be removed from the page
1935 			 * cache and replaced by a new folio before
1936 			 * mmu_notifier_invalidate_range_end, so no
1937 			 * concurrent thread might update its page table
1938 			 * to point at a new folio while a device is
1939 			 * still using this folio.
1940 			 *
1941 			 * See Documentation/mm/mmu_notifier.rst
1942 			 */
1943 			dec_mm_counter(mm, mm_counter_file(folio));
1944 		}
1945 discard:
1946 		if (unlikely(folio_test_hugetlb(folio)))
1947 			hugetlb_remove_rmap(folio);
1948 		else
1949 			folio_remove_rmap_pte(folio, subpage, vma);
1950 		if (vma->vm_flags & VM_LOCKED)
1951 			mlock_drain_local();
1952 		folio_put(folio);
1953 		continue;
1954 walk_abort:
1955 		ret = false;
1956 walk_done:
1957 		page_vma_mapped_walk_done(&pvmw);
1958 		break;
1959 	}
1960 
1961 	mmu_notifier_invalidate_range_end(&range);
1962 	trace_android_vh_try_to_unmap_one(folio, vma, address, arg, ret);
1963 
1964 	return ret;
1965 }
1966 
invalid_migration_vma(struct vm_area_struct * vma,void * arg)1967 static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
1968 {
1969 	return vma_is_temporary_stack(vma);
1970 }
1971 
folio_not_mapped(struct folio * folio)1972 static int folio_not_mapped(struct folio *folio)
1973 {
1974 	return !folio_mapped(folio);
1975 }
1976 
1977 /**
1978  * try_to_unmap - Try to remove all page table mappings to a folio.
1979  * @folio: The folio to unmap.
1980  * @flags: action and flags
1981  *
1982  * Tries to remove all the page table entries which are mapping this
1983  * folio.  It is the caller's responsibility to check if the folio is
1984  * still mapped if needed (use TTU_SYNC to prevent accounting races).
1985  *
1986  * Context: Caller must hold the folio lock.
1987  */
try_to_unmap(struct folio * folio,enum ttu_flags flags)1988 void try_to_unmap(struct folio *folio, enum ttu_flags flags)
1989 {
1990 	struct rmap_walk_control rwc = {
1991 		.rmap_one = try_to_unmap_one,
1992 		.arg = (void *)flags,
1993 		.done = folio_not_mapped,
1994 		.anon_lock = folio_lock_anon_vma_read,
1995 	};
1996 
1997 	if (flags & TTU_RMAP_LOCKED)
1998 		rmap_walk_locked(folio, &rwc);
1999 	else
2000 		rmap_walk(folio, &rwc);
2001 }
2002 
2003 /*
2004  * @arg: enum ttu_flags will be passed to this argument.
2005  *
2006  * If TTU_SPLIT_HUGE_PMD is specified any PMD mappings will be split into PTEs
2007  * containing migration entries.
2008  */
try_to_migrate_one(struct folio * folio,struct vm_area_struct * vma,unsigned long address,void * arg)2009 static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,
2010 		     unsigned long address, void *arg)
2011 {
2012 	struct mm_struct *mm = vma->vm_mm;
2013 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
2014 	pte_t pteval;
2015 	struct page *subpage;
2016 	bool anon_exclusive, ret = true;
2017 	struct mmu_notifier_range range;
2018 	enum ttu_flags flags = (enum ttu_flags)(long)arg;
2019 	unsigned long pfn;
2020 	unsigned long hsz = 0;
2021 
2022 	/*
2023 	 * When racing against e.g. zap_pte_range() on another cpu,
2024 	 * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(),
2025 	 * try_to_migrate() may return before page_mapped() has become false,
2026 	 * if page table locking is skipped: use TTU_SYNC to wait for that.
2027 	 */
2028 	if (flags & TTU_SYNC)
2029 		pvmw.flags = PVMW_SYNC;
2030 
2031 	/*
2032 	 * unmap_page() in mm/huge_memory.c is the only user of migration with
2033 	 * TTU_SPLIT_HUGE_PMD and it wants to freeze.
2034 	 */
2035 	if (flags & TTU_SPLIT_HUGE_PMD)
2036 		split_huge_pmd_address(vma, address, true, folio);
2037 
2038 	/*
2039 	 * For THP, we have to assume the worse case ie pmd for invalidation.
2040 	 * For hugetlb, it could be much worse if we need to do pud
2041 	 * invalidation in the case of pmd sharing.
2042 	 *
2043 	 * Note that the page can not be free in this function as call of
2044 	 * try_to_unmap() must hold a reference on the page.
2045 	 */
2046 	range.end = vma_address_end(&pvmw);
2047 	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2048 				address, range.end);
2049 	if (folio_test_hugetlb(folio)) {
2050 		/*
2051 		 * If sharing is possible, start and end will be adjusted
2052 		 * accordingly.
2053 		 */
2054 		adjust_range_if_pmd_sharing_possible(vma, &range.start,
2055 						     &range.end);
2056 
2057 		/* We need the huge page size for set_huge_pte_at() */
2058 		hsz = huge_page_size(hstate_vma(vma));
2059 	}
2060 	mmu_notifier_invalidate_range_start(&range);
2061 
2062 	while (page_vma_mapped_walk(&pvmw)) {
2063 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
2064 		/* PMD-mapped THP migration entry */
2065 		if (!pvmw.pte) {
2066 			subpage = folio_page(folio,
2067 				pmd_pfn(*pvmw.pmd) - folio_pfn(folio));
2068 			VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
2069 					!folio_test_pmd_mappable(folio), folio);
2070 
2071 			if (set_pmd_migration_entry(&pvmw, subpage)) {
2072 				ret = false;
2073 				page_vma_mapped_walk_done(&pvmw);
2074 				break;
2075 			}
2076 			continue;
2077 		}
2078 #endif
2079 
2080 		/* Unexpected PMD-mapped THP? */
2081 		VM_BUG_ON_FOLIO(!pvmw.pte, folio);
2082 
2083 		pfn = pte_pfn(ptep_get(pvmw.pte));
2084 
2085 		if (folio_is_zone_device(folio)) {
2086 			/*
2087 			 * Our PTE is a non-present device exclusive entry and
2088 			 * calculating the subpage as for the common case would
2089 			 * result in an invalid pointer.
2090 			 *
2091 			 * Since only PAGE_SIZE pages can currently be
2092 			 * migrated, just set it to page. This will need to be
2093 			 * changed when hugepage migrations to device private
2094 			 * memory are supported.
2095 			 */
2096 			VM_BUG_ON_FOLIO(folio_nr_pages(folio) > 1, folio);
2097 			subpage = &folio->page;
2098 		} else {
2099 			subpage = folio_page(folio, pfn - folio_pfn(folio));
2100 		}
2101 		address = pvmw.address;
2102 		anon_exclusive = folio_test_anon(folio) &&
2103 				 PageAnonExclusive(subpage);
2104 
2105 		if (folio_test_hugetlb(folio)) {
2106 			bool anon = folio_test_anon(folio);
2107 
2108 			/*
2109 			 * huge_pmd_unshare may unmap an entire PMD page.
2110 			 * There is no way of knowing exactly which PMDs may
2111 			 * be cached for this mm, so we must flush them all.
2112 			 * start/end were already adjusted above to cover this
2113 			 * range.
2114 			 */
2115 			flush_cache_range(vma, range.start, range.end);
2116 
2117 			/*
2118 			 * To call huge_pmd_unshare, i_mmap_rwsem must be
2119 			 * held in write mode.  Caller needs to explicitly
2120 			 * do this outside rmap routines.
2121 			 *
2122 			 * We also must hold hugetlb vma_lock in write mode.
2123 			 * Lock order dictates acquiring vma_lock BEFORE
2124 			 * i_mmap_rwsem.  We can only try lock here and
2125 			 * fail if unsuccessful.
2126 			 */
2127 			if (!anon) {
2128 				VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
2129 				if (!hugetlb_vma_trylock_write(vma)) {
2130 					page_vma_mapped_walk_done(&pvmw);
2131 					ret = false;
2132 					break;
2133 				}
2134 				if (huge_pmd_unshare(mm, vma, address, pvmw.pte)) {
2135 					hugetlb_vma_unlock_write(vma);
2136 					flush_tlb_range(vma,
2137 						range.start, range.end);
2138 
2139 					/*
2140 					 * The ref count of the PMD page was
2141 					 * dropped which is part of the way map
2142 					 * counting is done for shared PMDs.
2143 					 * Return 'true' here.  When there is
2144 					 * no other sharing, huge_pmd_unshare
2145 					 * returns false and we will unmap the
2146 					 * actual page and drop map count
2147 					 * to zero.
2148 					 */
2149 					page_vma_mapped_walk_done(&pvmw);
2150 					break;
2151 				}
2152 				hugetlb_vma_unlock_write(vma);
2153 			}
2154 			/* Nuke the hugetlb page table entry */
2155 			pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
2156 		} else {
2157 			flush_cache_page(vma, address, pfn);
2158 			/* Nuke the page table entry. */
2159 			if (should_defer_flush(mm, flags)) {
2160 				/*
2161 				 * We clear the PTE but do not flush so potentially
2162 				 * a remote CPU could still be writing to the folio.
2163 				 * If the entry was previously clean then the
2164 				 * architecture must guarantee that a clear->dirty
2165 				 * transition on a cached TLB entry is written through
2166 				 * and traps if the PTE is unmapped.
2167 				 */
2168 				pteval = ptep_get_and_clear(mm, address, pvmw.pte);
2169 
2170 				set_tlb_ubc_flush_pending(mm, pteval, address);
2171 			} else {
2172 				pteval = ptep_clear_flush(vma, address, pvmw.pte);
2173 			}
2174 		}
2175 
2176 		/* Set the dirty flag on the folio now the pte is gone. */
2177 		if (pte_dirty(pteval))
2178 			folio_mark_dirty(folio);
2179 
2180 		/* Update high watermark before we lower rss */
2181 		update_hiwater_rss(mm);
2182 
2183 		if (folio_is_device_private(folio)) {
2184 			unsigned long pfn = folio_pfn(folio);
2185 			swp_entry_t entry;
2186 			pte_t swp_pte;
2187 
2188 			if (anon_exclusive)
2189 				WARN_ON_ONCE(folio_try_share_anon_rmap_pte(folio,
2190 									   subpage));
2191 
2192 			/*
2193 			 * Store the pfn of the page in a special migration
2194 			 * pte. do_swap_page() will wait until the migration
2195 			 * pte is removed and then restart fault handling.
2196 			 */
2197 			entry = pte_to_swp_entry(pteval);
2198 			if (is_writable_device_private_entry(entry))
2199 				entry = make_writable_migration_entry(pfn);
2200 			else if (anon_exclusive)
2201 				entry = make_readable_exclusive_migration_entry(pfn);
2202 			else
2203 				entry = make_readable_migration_entry(pfn);
2204 			swp_pte = swp_entry_to_pte(entry);
2205 
2206 			/*
2207 			 * pteval maps a zone device page and is therefore
2208 			 * a swap pte.
2209 			 */
2210 			if (pte_swp_soft_dirty(pteval))
2211 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
2212 			if (pte_swp_uffd_wp(pteval))
2213 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
2214 			set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
2215 			trace_set_migration_pte(pvmw.address, pte_val(swp_pte),
2216 						folio_order(folio));
2217 			/*
2218 			 * No need to invalidate here it will synchronize on
2219 			 * against the special swap migration pte.
2220 			 */
2221 		} else if (PageHWPoison(subpage)) {
2222 			pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
2223 			if (folio_test_hugetlb(folio)) {
2224 				hugetlb_count_sub(folio_nr_pages(folio), mm);
2225 				set_huge_pte_at(mm, address, pvmw.pte, pteval,
2226 						hsz);
2227 			} else {
2228 				dec_mm_counter(mm, mm_counter(folio));
2229 				set_pte_at(mm, address, pvmw.pte, pteval);
2230 			}
2231 
2232 		} else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
2233 			/*
2234 			 * The guest indicated that the page content is of no
2235 			 * interest anymore. Simply discard the pte, vmscan
2236 			 * will take care of the rest.
2237 			 * A future reference will then fault in a new zero
2238 			 * page. When userfaultfd is active, we must not drop
2239 			 * this page though, as its main user (postcopy
2240 			 * migration) will not expect userfaults on already
2241 			 * copied pages.
2242 			 */
2243 			dec_mm_counter(mm, mm_counter(folio));
2244 		} else {
2245 			swp_entry_t entry;
2246 			pte_t swp_pte;
2247 
2248 			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
2249 				if (folio_test_hugetlb(folio))
2250 					set_huge_pte_at(mm, address, pvmw.pte,
2251 							pteval, hsz);
2252 				else
2253 					set_pte_at(mm, address, pvmw.pte, pteval);
2254 				ret = false;
2255 				page_vma_mapped_walk_done(&pvmw);
2256 				break;
2257 			}
2258 			VM_BUG_ON_PAGE(pte_write(pteval) && folio_test_anon(folio) &&
2259 				       !anon_exclusive, subpage);
2260 
2261 			/* See folio_try_share_anon_rmap_pte(): clear PTE first. */
2262 			if (folio_test_hugetlb(folio)) {
2263 				if (anon_exclusive &&
2264 				    hugetlb_try_share_anon_rmap(folio)) {
2265 					set_huge_pte_at(mm, address, pvmw.pte,
2266 							pteval, hsz);
2267 					ret = false;
2268 					page_vma_mapped_walk_done(&pvmw);
2269 					break;
2270 				}
2271 			} else if (anon_exclusive &&
2272 				   folio_try_share_anon_rmap_pte(folio, subpage)) {
2273 				set_pte_at(mm, address, pvmw.pte, pteval);
2274 				ret = false;
2275 				page_vma_mapped_walk_done(&pvmw);
2276 				break;
2277 			}
2278 
2279 			/*
2280 			 * Store the pfn of the page in a special migration
2281 			 * pte. do_swap_page() will wait until the migration
2282 			 * pte is removed and then restart fault handling.
2283 			 */
2284 			if (pte_write(pteval))
2285 				entry = make_writable_migration_entry(
2286 							page_to_pfn(subpage));
2287 			else if (anon_exclusive)
2288 				entry = make_readable_exclusive_migration_entry(
2289 							page_to_pfn(subpage));
2290 			else
2291 				entry = make_readable_migration_entry(
2292 							page_to_pfn(subpage));
2293 			if (pte_young(pteval))
2294 				entry = make_migration_entry_young(entry);
2295 			if (pte_dirty(pteval))
2296 				entry = make_migration_entry_dirty(entry);
2297 			swp_pte = swp_entry_to_pte(entry);
2298 			if (pte_soft_dirty(pteval))
2299 				swp_pte = pte_swp_mksoft_dirty(swp_pte);
2300 			if (pte_uffd_wp(pteval))
2301 				swp_pte = pte_swp_mkuffd_wp(swp_pte);
2302 			if (folio_test_hugetlb(folio))
2303 				set_huge_pte_at(mm, address, pvmw.pte, swp_pte,
2304 						hsz);
2305 			else
2306 				set_pte_at(mm, address, pvmw.pte, swp_pte);
2307 			trace_set_migration_pte(address, pte_val(swp_pte),
2308 						folio_order(folio));
2309 			trace_android_vh_mm_migrate_one_page(subpage, vma->vm_flags);
2310 			/*
2311 			 * No need to invalidate here it will synchronize on
2312 			 * against the special swap migration pte.
2313 			 */
2314 		}
2315 
2316 		if (unlikely(folio_test_hugetlb(folio)))
2317 			hugetlb_remove_rmap(folio);
2318 		else
2319 			folio_remove_rmap_pte(folio, subpage, vma);
2320 		if (vma->vm_flags & VM_LOCKED)
2321 			mlock_drain_local();
2322 		folio_put(folio);
2323 	}
2324 
2325 	mmu_notifier_invalidate_range_end(&range);
2326 
2327 	return ret;
2328 }
2329 
2330 /**
2331  * try_to_migrate - try to replace all page table mappings with swap entries
2332  * @folio: the folio to replace page table entries for
2333  * @flags: action and flags
2334  *
2335  * Tries to remove all the page table entries which are mapping this folio and
2336  * replace them with special swap entries. Caller must hold the folio lock.
2337  */
try_to_migrate(struct folio * folio,enum ttu_flags flags)2338 void try_to_migrate(struct folio *folio, enum ttu_flags flags)
2339 {
2340 	struct rmap_walk_control rwc = {
2341 		.rmap_one = try_to_migrate_one,
2342 		.arg = (void *)flags,
2343 		.done = folio_not_mapped,
2344 		.anon_lock = folio_lock_anon_vma_read,
2345 	};
2346 
2347 	/*
2348 	 * Migration always ignores mlock and only supports TTU_RMAP_LOCKED and
2349 	 * TTU_SPLIT_HUGE_PMD, TTU_SYNC, and TTU_BATCH_FLUSH flags.
2350 	 */
2351 	if (WARN_ON_ONCE(flags & ~(TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
2352 					TTU_SYNC | TTU_BATCH_FLUSH)))
2353 		return;
2354 
2355 	if (folio_is_zone_device(folio) &&
2356 	    (!folio_is_device_private(folio) && !folio_is_device_coherent(folio)))
2357 		return;
2358 
2359 	/*
2360 	 * During exec, a temporary VMA is setup and later moved.
2361 	 * The VMA is moved under the anon_vma lock but not the
2362 	 * page tables leading to a race where migration cannot
2363 	 * find the migration ptes. Rather than increasing the
2364 	 * locking requirements of exec(), migration skips
2365 	 * temporary VMAs until after exec() completes.
2366 	 */
2367 	if (!folio_test_ksm(folio) && folio_test_anon(folio))
2368 		rwc.invalid_vma = invalid_migration_vma;
2369 
2370 	if (flags & TTU_RMAP_LOCKED)
2371 		rmap_walk_locked(folio, &rwc);
2372 	else
2373 		rmap_walk(folio, &rwc);
2374 }
2375 
2376 #ifdef CONFIG_DEVICE_PRIVATE
2377 struct make_exclusive_args {
2378 	struct mm_struct *mm;
2379 	unsigned long address;
2380 	void *owner;
2381 	bool valid;
2382 };
2383 
page_make_device_exclusive_one(struct folio * folio,struct vm_area_struct * vma,unsigned long address,void * priv)2384 static bool page_make_device_exclusive_one(struct folio *folio,
2385 		struct vm_area_struct *vma, unsigned long address, void *priv)
2386 {
2387 	struct mm_struct *mm = vma->vm_mm;
2388 	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
2389 	struct make_exclusive_args *args = priv;
2390 	pte_t pteval;
2391 	struct page *subpage;
2392 	bool ret = true;
2393 	struct mmu_notifier_range range;
2394 	swp_entry_t entry;
2395 	pte_t swp_pte;
2396 	pte_t ptent;
2397 
2398 	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0,
2399 				      vma->vm_mm, address, min(vma->vm_end,
2400 				      address + folio_size(folio)),
2401 				      args->owner);
2402 	mmu_notifier_invalidate_range_start(&range);
2403 
2404 	while (page_vma_mapped_walk(&pvmw)) {
2405 		/* Unexpected PMD-mapped THP? */
2406 		VM_BUG_ON_FOLIO(!pvmw.pte, folio);
2407 
2408 		ptent = ptep_get(pvmw.pte);
2409 		if (!pte_present(ptent)) {
2410 			ret = false;
2411 			page_vma_mapped_walk_done(&pvmw);
2412 			break;
2413 		}
2414 
2415 		subpage = folio_page(folio,
2416 				pte_pfn(ptent) - folio_pfn(folio));
2417 		address = pvmw.address;
2418 
2419 		/* Nuke the page table entry. */
2420 		flush_cache_page(vma, address, pte_pfn(ptent));
2421 		pteval = ptep_clear_flush(vma, address, pvmw.pte);
2422 
2423 		/* Set the dirty flag on the folio now the pte is gone. */
2424 		if (pte_dirty(pteval))
2425 			folio_mark_dirty(folio);
2426 
2427 		/*
2428 		 * Check that our target page is still mapped at the expected
2429 		 * address.
2430 		 */
2431 		if (args->mm == mm && args->address == address &&
2432 		    pte_write(pteval))
2433 			args->valid = true;
2434 
2435 		/*
2436 		 * Store the pfn of the page in a special migration
2437 		 * pte. do_swap_page() will wait until the migration
2438 		 * pte is removed and then restart fault handling.
2439 		 */
2440 		if (pte_write(pteval))
2441 			entry = make_writable_device_exclusive_entry(
2442 							page_to_pfn(subpage));
2443 		else
2444 			entry = make_readable_device_exclusive_entry(
2445 							page_to_pfn(subpage));
2446 		swp_pte = swp_entry_to_pte(entry);
2447 		if (pte_soft_dirty(pteval))
2448 			swp_pte = pte_swp_mksoft_dirty(swp_pte);
2449 		if (pte_uffd_wp(pteval))
2450 			swp_pte = pte_swp_mkuffd_wp(swp_pte);
2451 
2452 		set_pte_at(mm, address, pvmw.pte, swp_pte);
2453 
2454 		/*
2455 		 * There is a reference on the page for the swap entry which has
2456 		 * been removed, so shouldn't take another.
2457 		 */
2458 		folio_remove_rmap_pte(folio, subpage, vma);
2459 	}
2460 
2461 	mmu_notifier_invalidate_range_end(&range);
2462 
2463 	return ret;
2464 }
2465 
2466 /**
2467  * folio_make_device_exclusive - Mark the folio exclusively owned by a device.
2468  * @folio: The folio to replace page table entries for.
2469  * @mm: The mm_struct where the folio is expected to be mapped.
2470  * @address: Address where the folio is expected to be mapped.
2471  * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier callbacks
2472  *
2473  * Tries to remove all the page table entries which are mapping this
2474  * folio and replace them with special device exclusive swap entries to
2475  * grant a device exclusive access to the folio.
2476  *
2477  * Context: Caller must hold the folio lock.
2478  * Return: false if the page is still mapped, or if it could not be unmapped
2479  * from the expected address. Otherwise returns true (success).
2480  */
folio_make_device_exclusive(struct folio * folio,struct mm_struct * mm,unsigned long address,void * owner)2481 static bool folio_make_device_exclusive(struct folio *folio,
2482 		struct mm_struct *mm, unsigned long address, void *owner)
2483 {
2484 	struct make_exclusive_args args = {
2485 		.mm = mm,
2486 		.address = address,
2487 		.owner = owner,
2488 		.valid = false,
2489 	};
2490 	struct rmap_walk_control rwc = {
2491 		.rmap_one = page_make_device_exclusive_one,
2492 		.done = folio_not_mapped,
2493 		.anon_lock = folio_lock_anon_vma_read,
2494 		.arg = &args,
2495 	};
2496 
2497 	/*
2498 	 * Restrict to anonymous folios for now to avoid potential writeback
2499 	 * issues.
2500 	 */
2501 	if (!folio_test_anon(folio) || folio_test_hugetlb(folio))
2502 		return false;
2503 
2504 	rmap_walk(folio, &rwc);
2505 
2506 	return args.valid && !folio_mapcount(folio);
2507 }
2508 
2509 /**
2510  * make_device_exclusive_range() - Mark a range for exclusive use by a device
2511  * @mm: mm_struct of associated target process
2512  * @start: start of the region to mark for exclusive device access
2513  * @end: end address of region
2514  * @pages: returns the pages which were successfully marked for exclusive access
2515  * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
2516  *
2517  * Returns: number of pages found in the range by GUP. A page is marked for
2518  * exclusive access only if the page pointer is non-NULL.
2519  *
2520  * This function finds ptes mapping page(s) to the given address range, locks
2521  * them and replaces mappings with special swap entries preventing userspace CPU
2522  * access. On fault these entries are replaced with the original mapping after
2523  * calling MMU notifiers.
2524  *
2525  * A driver using this to program access from a device must use a mmu notifier
2526  * critical section to hold a device specific lock during programming. Once
2527  * programming is complete it should drop the page lock and reference after
2528  * which point CPU access to the page will revoke the exclusive access.
2529  */
make_device_exclusive_range(struct mm_struct * mm,unsigned long start,unsigned long end,struct page ** pages,void * owner)2530 int make_device_exclusive_range(struct mm_struct *mm, unsigned long start,
2531 				unsigned long end, struct page **pages,
2532 				void *owner)
2533 {
2534 	long npages = (end - start) >> PAGE_SHIFT;
2535 	long i;
2536 
2537 	npages = get_user_pages_remote(mm, start, npages,
2538 				       FOLL_GET | FOLL_WRITE | FOLL_SPLIT_PMD,
2539 				       pages, NULL);
2540 	if (npages < 0)
2541 		return npages;
2542 
2543 	for (i = 0; i < npages; i++, start += PAGE_SIZE) {
2544 		struct folio *folio = page_folio(pages[i]);
2545 		if (PageTail(pages[i]) || !folio_trylock(folio)) {
2546 			folio_put(folio);
2547 			pages[i] = NULL;
2548 			continue;
2549 		}
2550 
2551 		if (!folio_make_device_exclusive(folio, mm, start, owner)) {
2552 			folio_unlock(folio);
2553 			folio_put(folio);
2554 			pages[i] = NULL;
2555 		}
2556 	}
2557 
2558 	return npages;
2559 }
2560 EXPORT_SYMBOL_GPL(make_device_exclusive_range);
2561 #endif
2562 
__put_anon_vma(struct anon_vma * anon_vma)2563 void __put_anon_vma(struct anon_vma *anon_vma)
2564 {
2565 	struct anon_vma *root = anon_vma->root;
2566 
2567 	anon_vma_free(anon_vma);
2568 	if (root != anon_vma && atomic_dec_and_test(&root->refcount))
2569 		anon_vma_free(root);
2570 }
2571 
rmap_walk_anon_lock(struct folio * folio,struct rmap_walk_control * rwc)2572 static struct anon_vma *rmap_walk_anon_lock(struct folio *folio,
2573 					    struct rmap_walk_control *rwc)
2574 {
2575 	struct anon_vma *anon_vma;
2576 
2577 	if (rwc->anon_lock)
2578 		return rwc->anon_lock(folio, rwc);
2579 
2580 	/*
2581 	 * Note: remove_migration_ptes() cannot use folio_lock_anon_vma_read()
2582 	 * because that depends on page_mapped(); but not all its usages
2583 	 * are holding mmap_lock. Users without mmap_lock are required to
2584 	 * take a reference count to prevent the anon_vma disappearing
2585 	 */
2586 	anon_vma = folio_anon_vma(folio);
2587 	if (!anon_vma)
2588 		return NULL;
2589 
2590 	if (anon_vma_trylock_read(anon_vma))
2591 		goto out;
2592 
2593 	if (rwc->try_lock) {
2594 		anon_vma = NULL;
2595 		rwc->contended = true;
2596 		goto out;
2597 	}
2598 
2599 	anon_vma_lock_read(anon_vma);
2600 out:
2601 	return anon_vma;
2602 }
2603 
2604 /*
2605  * rmap_walk_anon - do something to anonymous page using the object-based
2606  * rmap method
2607  * @folio: the folio to be handled
2608  * @rwc: control variable according to each walk type
2609  * @locked: caller holds relevant rmap lock
2610  *
2611  * Find all the mappings of a folio using the mapping pointer and the vma
2612  * chains contained in the anon_vma struct it points to.
2613  */
rmap_walk_anon(struct folio * folio,struct rmap_walk_control * rwc,bool locked)2614 static void rmap_walk_anon(struct folio *folio,
2615 		struct rmap_walk_control *rwc, bool locked)
2616 {
2617 	struct anon_vma *anon_vma;
2618 	pgoff_t pgoff_start, pgoff_end;
2619 	struct anon_vma_chain *avc;
2620 
2621 	if (locked) {
2622 		anon_vma = folio_anon_vma(folio);
2623 		/* anon_vma disappear under us? */
2624 		VM_BUG_ON_FOLIO(!anon_vma, folio);
2625 	} else {
2626 		anon_vma = rmap_walk_anon_lock(folio, rwc);
2627 	}
2628 	if (!anon_vma)
2629 		return;
2630 
2631 	pgoff_start = folio_pgoff(folio);
2632 	pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
2633 	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
2634 			pgoff_start, pgoff_end) {
2635 		struct vm_area_struct *vma = avc->vma;
2636 		unsigned long address = vma_address(vma, pgoff_start,
2637 				folio_nr_pages(folio));
2638 
2639 		VM_BUG_ON_VMA(address == -EFAULT, vma);
2640 		cond_resched();
2641 
2642 		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2643 			continue;
2644 
2645 		if (!rwc->rmap_one(folio, vma, address, rwc->arg))
2646 			break;
2647 		if (rwc->done && rwc->done(folio))
2648 			break;
2649 	}
2650 
2651 	if (!locked)
2652 		anon_vma_unlock_read(anon_vma);
2653 }
2654 
2655 /*
2656  * rmap_walk_file - do something to file page using the object-based rmap method
2657  * @folio: the folio to be handled
2658  * @rwc: control variable according to each walk type
2659  * @locked: caller holds relevant rmap lock
2660  *
2661  * Find all the mappings of a folio using the mapping pointer and the vma chains
2662  * contained in the address_space struct it points to.
2663  */
rmap_walk_file(struct folio * folio,struct rmap_walk_control * rwc,bool locked)2664 static void rmap_walk_file(struct folio *folio,
2665 		struct rmap_walk_control *rwc, bool locked)
2666 {
2667 	struct address_space *mapping = folio_mapping(folio);
2668 	pgoff_t pgoff_start, pgoff_end;
2669 	struct vm_area_struct *vma;
2670 
2671 	/*
2672 	 * The page lock not only makes sure that page->mapping cannot
2673 	 * suddenly be NULLified by truncation, it makes sure that the
2674 	 * structure at mapping cannot be freed and reused yet,
2675 	 * so we can safely take mapping->i_mmap_rwsem.
2676 	 */
2677 	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
2678 
2679 	if (!mapping)
2680 		return;
2681 
2682 	pgoff_start = folio_pgoff(folio);
2683 	pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
2684 	if (!locked) {
2685 		if (i_mmap_trylock_read(mapping))
2686 			goto lookup;
2687 
2688 		if (rwc->try_lock) {
2689 			rwc->contended = true;
2690 			return;
2691 		}
2692 
2693 		i_mmap_lock_read(mapping);
2694 	}
2695 lookup:
2696 	vma_interval_tree_foreach(vma, &mapping->i_mmap,
2697 			pgoff_start, pgoff_end) {
2698 		unsigned long address = vma_address(vma, pgoff_start,
2699 			       folio_nr_pages(folio));
2700 
2701 		VM_BUG_ON_VMA(address == -EFAULT, vma);
2702 		cond_resched();
2703 
2704 		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2705 			continue;
2706 
2707 		if (!rwc->rmap_one(folio, vma, address, rwc->arg))
2708 			goto done;
2709 		if (rwc->done && rwc->done(folio))
2710 			goto done;
2711 	}
2712 
2713 done:
2714 	if (!locked)
2715 		i_mmap_unlock_read(mapping);
2716 }
2717 
rmap_walk(struct folio * folio,struct rmap_walk_control * rwc)2718 void rmap_walk(struct folio *folio, struct rmap_walk_control *rwc)
2719 {
2720 	if (unlikely(folio_test_ksm(folio)))
2721 		rmap_walk_ksm(folio, rwc);
2722 	else if (folio_test_anon(folio))
2723 		rmap_walk_anon(folio, rwc, false);
2724 	else
2725 		rmap_walk_file(folio, rwc, false);
2726 }
2727 
2728 /* Like rmap_walk, but caller holds relevant rmap lock */
rmap_walk_locked(struct folio * folio,struct rmap_walk_control * rwc)2729 void rmap_walk_locked(struct folio *folio, struct rmap_walk_control *rwc)
2730 {
2731 	/* no ksm support for now */
2732 	VM_BUG_ON_FOLIO(folio_test_ksm(folio), folio);
2733 	if (folio_test_anon(folio))
2734 		rmap_walk_anon(folio, rwc, true);
2735 	else
2736 		rmap_walk_file(folio, rwc, true);
2737 }
2738 
2739 #ifdef CONFIG_HUGETLB_PAGE
2740 /*
2741  * The following two functions are for anonymous (private mapped) hugepages.
2742  * Unlike common anonymous pages, anonymous hugepages have no accounting code
2743  * and no lru code, because we handle hugepages differently from common pages.
2744  */
hugetlb_add_anon_rmap(struct folio * folio,struct vm_area_struct * vma,unsigned long address,rmap_t flags)2745 void hugetlb_add_anon_rmap(struct folio *folio, struct vm_area_struct *vma,
2746 		unsigned long address, rmap_t flags)
2747 {
2748 	VM_WARN_ON_FOLIO(!folio_test_hugetlb(folio), folio);
2749 	VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
2750 
2751 	atomic_inc(&folio->_entire_mapcount);
2752 	atomic_inc(&folio->_large_mapcount);
2753 	if (flags & RMAP_EXCLUSIVE)
2754 		SetPageAnonExclusive(&folio->page);
2755 	VM_WARN_ON_FOLIO(folio_entire_mapcount(folio) > 1 &&
2756 			 PageAnonExclusive(&folio->page), folio);
2757 }
2758 
hugetlb_add_new_anon_rmap(struct folio * folio,struct vm_area_struct * vma,unsigned long address)2759 void hugetlb_add_new_anon_rmap(struct folio *folio,
2760 		struct vm_area_struct *vma, unsigned long address)
2761 {
2762 	VM_WARN_ON_FOLIO(!folio_test_hugetlb(folio), folio);
2763 
2764 	BUG_ON(address < vma->vm_start || address >= vma->vm_end);
2765 	/* increment count (starts at -1) */
2766 	atomic_set(&folio->_entire_mapcount, 0);
2767 	atomic_set(&folio->_large_mapcount, 0);
2768 	folio_clear_hugetlb_restore_reserve(folio);
2769 	__folio_set_anon(folio, vma, address, true);
2770 	SetPageAnonExclusive(&folio->page);
2771 }
2772 #endif /* CONFIG_HUGETLB_PAGE */
2773