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