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