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