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