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