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