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