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