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