2 * mm/rmap.c - physical to virtual reverse mappings
4 * Copyright 2001, Rik van Riel <riel@conectiva.com.br>
5 * Released under the General Public License (GPL).
7 * Simple, low overhead reverse mapping scheme.
8 * Please try to keep this thing as modular as possible.
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.
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
21 * Lock ordering in mm:
23 * inode->i_mutex (while writing or truncating, not reading or faulting)
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)
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)
44 * anon_vma->rwsem,mapping->i_mutex (memory_failure, collect_procs_anon)
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)
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>
76 #include <asm/tlbflush.h>
78 #include <trace/events/tlb.h>
82 static struct kmem_cache *anon_vma_cachep;
83 static struct kmem_cache *anon_vma_chain_cachep;
85 static inline struct anon_vma *anon_vma_alloc(void)
87 struct anon_vma *anon_vma;
89 anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
91 atomic_set(&anon_vma->refcount, 1);
92 anon_vma->degree = 1; /* Reference for first vma */
93 anon_vma->parent = anon_vma;
95 * Initialise the anon_vma root to point to itself. If called
96 * from fork, the root will be reset to the parents anon_vma.
98 anon_vma->root = anon_vma;
104 static inline void anon_vma_free(struct anon_vma *anon_vma)
106 VM_BUG_ON(atomic_read(&anon_vma->refcount));
109 * Synchronize against page_lock_anon_vma_read() such that
110 * we can safely hold the lock without the anon_vma getting
113 * Relies on the full mb implied by the atomic_dec_and_test() from
114 * put_anon_vma() against the acquire barrier implied by
115 * down_read_trylock() from page_lock_anon_vma_read(). This orders:
117 * page_lock_anon_vma_read() VS put_anon_vma()
118 * down_read_trylock() atomic_dec_and_test()
120 * atomic_read() rwsem_is_locked()
122 * LOCK should suffice since the actual taking of the lock must
123 * happen _before_ what follows.
126 if (rwsem_is_locked(&anon_vma->root->rwsem)) {
127 anon_vma_lock_write(anon_vma);
128 anon_vma_unlock_write(anon_vma);
131 kmem_cache_free(anon_vma_cachep, anon_vma);
134 static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
136 return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
139 static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
141 kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
144 static void anon_vma_chain_link(struct vm_area_struct *vma,
145 struct anon_vma_chain *avc,
146 struct anon_vma *anon_vma)
149 avc->anon_vma = anon_vma;
150 list_add(&avc->same_vma, &vma->anon_vma_chain);
151 anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
155 * __anon_vma_prepare - attach an anon_vma to a memory region
156 * @vma: the memory region in question
158 * This makes sure the memory mapping described by 'vma' has
159 * an 'anon_vma' attached to it, so that we can associate the
160 * anonymous pages mapped into it with that anon_vma.
162 * The common case will be that we already have one, which
163 * is handled inline by anon_vma_prepare(). But if
164 * not we either need to find an adjacent mapping that we
165 * can re-use the anon_vma from (very common when the only
166 * reason for splitting a vma has been mprotect()), or we
167 * allocate a new one.
169 * Anon-vma allocations are very subtle, because we may have
170 * optimistically looked up an anon_vma in page_lock_anon_vma_read()
171 * and that may actually touch the spinlock even in the newly
172 * allocated vma (it depends on RCU to make sure that the
173 * anon_vma isn't actually destroyed).
175 * As a result, we need to do proper anon_vma locking even
176 * for the new allocation. At the same time, we do not want
177 * to do any locking for the common case of already having
180 * This must be called with the mmap_sem held for reading.
182 int __anon_vma_prepare(struct vm_area_struct *vma)
184 struct mm_struct *mm = vma->vm_mm;
185 struct anon_vma *anon_vma, *allocated;
186 struct anon_vma_chain *avc;
190 avc = anon_vma_chain_alloc(GFP_KERNEL);
194 anon_vma = find_mergeable_anon_vma(vma);
197 anon_vma = anon_vma_alloc();
198 if (unlikely(!anon_vma))
199 goto out_enomem_free_avc;
200 allocated = anon_vma;
203 anon_vma_lock_write(anon_vma);
204 /* page_table_lock to protect against threads */
205 spin_lock(&mm->page_table_lock);
206 if (likely(!vma->anon_vma)) {
207 vma->anon_vma = anon_vma;
208 anon_vma_chain_link(vma, avc, anon_vma);
209 /* vma reference or self-parent link for new root */
214 spin_unlock(&mm->page_table_lock);
215 anon_vma_unlock_write(anon_vma);
217 if (unlikely(allocated))
218 put_anon_vma(allocated);
220 anon_vma_chain_free(avc);
225 anon_vma_chain_free(avc);
231 * This is a useful helper function for locking the anon_vma root as
232 * we traverse the vma->anon_vma_chain, looping over anon_vma's that
235 * Such anon_vma's should have the same root, so you'd expect to see
236 * just a single mutex_lock for the whole traversal.
238 static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
240 struct anon_vma *new_root = anon_vma->root;
241 if (new_root != root) {
242 if (WARN_ON_ONCE(root))
243 up_write(&root->rwsem);
245 down_write(&root->rwsem);
250 static inline void unlock_anon_vma_root(struct anon_vma *root)
253 up_write(&root->rwsem);
257 * Attach the anon_vmas from src to dst.
258 * Returns 0 on success, -ENOMEM on failure.
260 * anon_vma_clone() is called by __vma_split(), __split_vma(), copy_vma() and
261 * anon_vma_fork(). The first three want an exact copy of src, while the last
262 * one, anon_vma_fork(), may try to reuse an existing anon_vma to prevent
263 * endless growth of anon_vma. Since dst->anon_vma is set to NULL before call,
264 * we can identify this case by checking (!dst->anon_vma && src->anon_vma).
266 * If (!dst->anon_vma && src->anon_vma) is true, this function tries to find
267 * and reuse existing anon_vma which has no vmas and only one child anon_vma.
268 * This prevents degradation of anon_vma hierarchy to endless linear chain in
269 * case of constantly forking task. On the other hand, an anon_vma with more
270 * than one child isn't reused even if there was no alive vma, thus rmap
271 * walker has a good chance of avoiding scanning the whole hierarchy when it
272 * searches where page is mapped.
274 int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
276 struct anon_vma_chain *avc, *pavc;
277 struct anon_vma *root = NULL;
278 struct vm_area_struct *prev = dst->vm_prev, *pprev = src->vm_prev;
281 * If parent share anon_vma with its vm_prev, keep this sharing in in
284 * 1. Parent has vm_prev, which implies we have vm_prev.
285 * 2. Parent and its vm_prev have the same anon_vma.
287 if (!dst->anon_vma && src->anon_vma &&
288 pprev && pprev->anon_vma == src->anon_vma)
289 dst->anon_vma = prev->anon_vma;
292 list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
293 struct anon_vma *anon_vma;
295 avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
296 if (unlikely(!avc)) {
297 unlock_anon_vma_root(root);
299 avc = anon_vma_chain_alloc(GFP_KERNEL);
303 anon_vma = pavc->anon_vma;
304 root = lock_anon_vma_root(root, anon_vma);
305 anon_vma_chain_link(dst, avc, anon_vma);
308 * Reuse existing anon_vma if its degree lower than two,
309 * that means it has no vma and only one anon_vma child.
311 * Do not chose parent anon_vma, otherwise first child
312 * will always reuse it. Root anon_vma is never reused:
313 * it has self-parent reference and at least one child.
315 if (!dst->anon_vma && src->anon_vma &&
316 anon_vma != src->anon_vma && anon_vma->degree < 2)
317 dst->anon_vma = anon_vma;
320 dst->anon_vma->degree++;
321 unlock_anon_vma_root(root);
326 * dst->anon_vma is dropped here otherwise its degree can be incorrectly
327 * decremented in unlink_anon_vmas().
328 * We can safely do this because callers of anon_vma_clone() don't care
329 * about dst->anon_vma if anon_vma_clone() failed.
331 dst->anon_vma = NULL;
332 unlink_anon_vmas(dst);
337 * Attach vma to its own anon_vma, as well as to the anon_vmas that
338 * the corresponding VMA in the parent process is attached to.
339 * Returns 0 on success, non-zero on failure.
341 int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
343 struct anon_vma_chain *avc;
344 struct anon_vma *anon_vma;
347 /* Don't bother if the parent process has no anon_vma here. */
351 /* Drop inherited anon_vma, we'll reuse existing or allocate new. */
352 vma->anon_vma = NULL;
355 * First, attach the new VMA to the parent VMA's anon_vmas,
356 * so rmap can find non-COWed pages in child processes.
358 error = anon_vma_clone(vma, pvma);
362 /* An existing anon_vma has been reused, all done then. */
366 /* Then add our own anon_vma. */
367 anon_vma = anon_vma_alloc();
370 avc = anon_vma_chain_alloc(GFP_KERNEL);
372 goto out_error_free_anon_vma;
375 * The root anon_vma's spinlock is the lock actually used when we
376 * lock any of the anon_vmas in this anon_vma tree.
378 anon_vma->root = pvma->anon_vma->root;
379 anon_vma->parent = pvma->anon_vma;
381 * With refcounts, an anon_vma can stay around longer than the
382 * process it belongs to. The root anon_vma needs to be pinned until
383 * this anon_vma is freed, because the lock lives in the root.
385 get_anon_vma(anon_vma->root);
386 /* Mark this anon_vma as the one where our new (COWed) pages go. */
387 vma->anon_vma = anon_vma;
388 anon_vma_lock_write(anon_vma);
389 anon_vma_chain_link(vma, avc, anon_vma);
390 anon_vma->parent->degree++;
391 anon_vma_unlock_write(anon_vma);
395 out_error_free_anon_vma:
396 put_anon_vma(anon_vma);
398 unlink_anon_vmas(vma);
402 void unlink_anon_vmas(struct vm_area_struct *vma)
404 struct anon_vma_chain *avc, *next;
405 struct anon_vma *root = NULL;
408 * Unlink each anon_vma chained to the VMA. This list is ordered
409 * from newest to oldest, ensuring the root anon_vma gets freed last.
411 list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
412 struct anon_vma *anon_vma = avc->anon_vma;
414 root = lock_anon_vma_root(root, anon_vma);
415 anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
418 * Leave empty anon_vmas on the list - we'll need
419 * to free them outside the lock.
421 if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
422 anon_vma->parent->degree--;
426 list_del(&avc->same_vma);
427 anon_vma_chain_free(avc);
430 vma->anon_vma->degree--;
431 unlock_anon_vma_root(root);
434 * Iterate the list once more, it now only contains empty and unlinked
435 * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
436 * needing to write-acquire the anon_vma->root->rwsem.
438 list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
439 struct anon_vma *anon_vma = avc->anon_vma;
441 VM_WARN_ON(anon_vma->degree);
442 put_anon_vma(anon_vma);
444 list_del(&avc->same_vma);
445 anon_vma_chain_free(avc);
449 static void anon_vma_ctor(void *data)
451 struct anon_vma *anon_vma = data;
453 init_rwsem(&anon_vma->rwsem);
454 atomic_set(&anon_vma->refcount, 0);
455 anon_vma->rb_root = RB_ROOT_CACHED;
458 void __init anon_vma_init(void)
460 anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
461 0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
463 anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
464 SLAB_PANIC|SLAB_ACCOUNT);
468 * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
470 * Since there is no serialization what so ever against page_remove_rmap()
471 * the best this function can do is return a locked anon_vma that might
472 * have been relevant to this page.
474 * The page might have been remapped to a different anon_vma or the anon_vma
475 * returned may already be freed (and even reused).
477 * In case it was remapped to a different anon_vma, the new anon_vma will be a
478 * child of the old anon_vma, and the anon_vma lifetime rules will therefore
479 * ensure that any anon_vma obtained from the page will still be valid for as
480 * long as we observe page_mapped() [ hence all those page_mapped() tests ].
482 * All users of this function must be very careful when walking the anon_vma
483 * chain and verify that the page in question is indeed mapped in it
484 * [ something equivalent to page_mapped_in_vma() ].
486 * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
487 * page_remove_rmap() that the anon_vma pointer from page->mapping is valid
488 * if there is a mapcount, we can dereference the anon_vma after observing
491 struct anon_vma *page_get_anon_vma(struct page *page)
493 struct anon_vma *anon_vma = NULL;
494 unsigned long anon_mapping;
497 anon_mapping = (unsigned long)READ_ONCE(page->mapping);
498 if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
500 if (!page_mapped(page))
503 anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
504 if (!atomic_inc_not_zero(&anon_vma->refcount)) {
510 * If this page is still mapped, then its anon_vma cannot have been
511 * freed. But if it has been unmapped, we have no security against the
512 * anon_vma structure being freed and reused (for another anon_vma:
513 * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
514 * above cannot corrupt).
516 if (!page_mapped(page)) {
518 put_anon_vma(anon_vma);
528 * Similar to page_get_anon_vma() except it locks the anon_vma.
530 * Its a little more complex as it tries to keep the fast path to a single
531 * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
532 * reference like with page_get_anon_vma() and then block on the mutex.
534 struct anon_vma *page_lock_anon_vma_read(struct page *page)
536 struct anon_vma *anon_vma = NULL;
537 struct anon_vma *root_anon_vma;
538 unsigned long anon_mapping;
541 anon_mapping = (unsigned long)READ_ONCE(page->mapping);
542 if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
544 if (!page_mapped(page))
547 anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
548 root_anon_vma = READ_ONCE(anon_vma->root);
549 if (down_read_trylock(&root_anon_vma->rwsem)) {
551 * If the page is still mapped, then this anon_vma is still
552 * its anon_vma, and holding the mutex ensures that it will
553 * not go away, see anon_vma_free().
555 if (!page_mapped(page)) {
556 up_read(&root_anon_vma->rwsem);
562 /* trylock failed, we got to sleep */
563 if (!atomic_inc_not_zero(&anon_vma->refcount)) {
568 if (!page_mapped(page)) {
570 put_anon_vma(anon_vma);
574 /* we pinned the anon_vma, its safe to sleep */
576 anon_vma_lock_read(anon_vma);
578 if (atomic_dec_and_test(&anon_vma->refcount)) {
580 * Oops, we held the last refcount, release the lock
581 * and bail -- can't simply use put_anon_vma() because
582 * we'll deadlock on the anon_vma_lock_write() recursion.
584 anon_vma_unlock_read(anon_vma);
585 __put_anon_vma(anon_vma);
596 void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
598 anon_vma_unlock_read(anon_vma);
601 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
603 * Flush TLB entries for recently unmapped pages from remote CPUs. It is
604 * important if a PTE was dirty when it was unmapped that it's flushed
605 * before any IO is initiated on the page to prevent lost writes. Similarly,
606 * it must be flushed before freeing to prevent data leakage.
608 void try_to_unmap_flush(void)
610 struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
612 if (!tlb_ubc->flush_required)
615 arch_tlbbatch_flush(&tlb_ubc->arch);
616 tlb_ubc->flush_required = false;
617 tlb_ubc->writable = false;
620 /* Flush iff there are potentially writable TLB entries that can race with IO */
621 void try_to_unmap_flush_dirty(void)
623 struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
625 if (tlb_ubc->writable)
626 try_to_unmap_flush();
629 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
631 struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
633 arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
634 tlb_ubc->flush_required = true;
637 * Ensure compiler does not re-order the setting of tlb_flush_batched
638 * before the PTE is cleared.
641 mm->tlb_flush_batched = true;
644 * If the PTE was dirty then it's best to assume it's writable. The
645 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
646 * before the page is queued for IO.
649 tlb_ubc->writable = true;
653 * Returns true if the TLB flush should be deferred to the end of a batch of
654 * unmap operations to reduce IPIs.
656 static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
658 bool should_defer = false;
660 if (!(flags & TTU_BATCH_FLUSH))
663 /* If remote CPUs need to be flushed then defer batch the flush */
664 if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
672 * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
673 * releasing the PTL if TLB flushes are batched. It's possible for a parallel
674 * operation such as mprotect or munmap to race between reclaim unmapping
675 * the page and flushing the page. If this race occurs, it potentially allows
676 * access to data via a stale TLB entry. Tracking all mm's that have TLB
677 * batching in flight would be expensive during reclaim so instead track
678 * whether TLB batching occurred in the past and if so then do a flush here
679 * if required. This will cost one additional flush per reclaim cycle paid
680 * by the first operation at risk such as mprotect and mumap.
682 * This must be called under the PTL so that an access to tlb_flush_batched
683 * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
686 void flush_tlb_batched_pending(struct mm_struct *mm)
688 if (mm->tlb_flush_batched) {
692 * Do not allow the compiler to re-order the clearing of
693 * tlb_flush_batched before the tlb is flushed.
696 mm->tlb_flush_batched = false;
700 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
704 static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
708 #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
711 * At what user virtual address is page expected in vma?
712 * Caller should check the page is actually part of the vma.
714 unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
716 unsigned long address;
717 if (PageAnon(page)) {
718 struct anon_vma *page__anon_vma = page_anon_vma(page);
720 * Note: swapoff's unuse_vma() is more efficient with this
721 * check, and needs it to match anon_vma when KSM is active.
723 if (!vma->anon_vma || !page__anon_vma ||
724 vma->anon_vma->root != page__anon_vma->root)
726 } else if (page->mapping) {
727 if (!vma->vm_file || vma->vm_file->f_mapping != page->mapping)
731 address = __vma_address(page, vma);
732 if (unlikely(address < vma->vm_start || address >= vma->vm_end))
737 pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
745 pgd = pgd_offset(mm, address);
746 if (!pgd_present(*pgd))
749 p4d = p4d_offset(pgd, address);
750 if (!p4d_present(*p4d))
753 pud = pud_offset(p4d, address);
754 if (!pud_present(*pud))
757 pmd = pmd_offset(pud, address);
759 * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
760 * without holding anon_vma lock for write. So when looking for a
761 * genuine pmde (in which to find pte), test present and !THP together.
765 if (!pmd_present(pmde) || pmd_trans_huge(pmde))
771 struct page_referenced_arg {
774 unsigned long vm_flags;
775 struct mem_cgroup *memcg;
778 * arg: page_referenced_arg will be passed
780 static bool page_referenced_one(struct page *page, struct vm_area_struct *vma,
781 unsigned long address, void *arg)
783 struct page_referenced_arg *pra = arg;
784 struct page_vma_mapped_walk pvmw = {
791 while (page_vma_mapped_walk(&pvmw)) {
792 address = pvmw.address;
794 if (vma->vm_flags & VM_LOCKED) {
795 page_vma_mapped_walk_done(&pvmw);
796 pra->vm_flags |= VM_LOCKED;
797 return false; /* To break the loop */
801 if (ptep_clear_flush_young_notify(vma, address,
804 * Don't treat a reference through
805 * a sequentially read mapping as such.
806 * If the page has been used in another mapping,
807 * we will catch it; if this other mapping is
808 * already gone, the unmap path will have set
809 * PG_referenced or activated the page.
811 if (likely(!(vma->vm_flags & VM_SEQ_READ)))
814 } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
815 if (pmdp_clear_flush_young_notify(vma, address,
819 /* unexpected pmd-mapped page? */
827 clear_page_idle(page);
828 if (test_and_clear_page_young(page))
833 pra->vm_flags |= vma->vm_flags;
837 return false; /* To break the loop */
842 static bool invalid_page_referenced_vma(struct vm_area_struct *vma, void *arg)
844 struct page_referenced_arg *pra = arg;
845 struct mem_cgroup *memcg = pra->memcg;
847 if (!mm_match_cgroup(vma->vm_mm, memcg))
854 * page_referenced - test if the page was referenced
855 * @page: the page to test
856 * @is_locked: caller holds lock on the page
857 * @memcg: target memory cgroup
858 * @vm_flags: collect encountered vma->vm_flags who actually referenced the page
860 * Quick test_and_clear_referenced for all mappings to a page,
861 * returns the number of ptes which referenced the page.
863 int page_referenced(struct page *page,
865 struct mem_cgroup *memcg,
866 unsigned long *vm_flags)
869 struct page_referenced_arg pra = {
870 .mapcount = total_mapcount(page),
873 struct rmap_walk_control rwc = {
874 .rmap_one = page_referenced_one,
876 .anon_lock = page_lock_anon_vma_read,
883 if (!page_rmapping(page))
886 if (!is_locked && (!PageAnon(page) || PageKsm(page))) {
887 we_locked = trylock_page(page);
893 * If we are reclaiming on behalf of a cgroup, skip
894 * counting on behalf of references from different
898 rwc.invalid_vma = invalid_page_referenced_vma;
901 rmap_walk(page, &rwc);
902 *vm_flags = pra.vm_flags;
907 return pra.referenced;
910 static bool page_mkclean_one(struct page *page, struct vm_area_struct *vma,
911 unsigned long address, void *arg)
913 struct page_vma_mapped_walk pvmw = {
919 struct mmu_notifier_range range;
923 * We have to assume the worse case ie pmd for invalidation. Note that
924 * the page can not be free from this function.
926 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
927 0, vma, vma->vm_mm, address,
928 min(vma->vm_end, address + page_size(page)));
929 mmu_notifier_invalidate_range_start(&range);
931 while (page_vma_mapped_walk(&pvmw)) {
934 address = pvmw.address;
937 pte_t *pte = pvmw.pte;
939 if (!pte_dirty(*pte) && !pte_write(*pte))
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);
949 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
950 pmd_t *pmd = pvmw.pmd;
953 if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
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);
963 /* unexpected pmd-mapped page? */
969 * No need to call mmu_notifier_invalidate_range() as we are
970 * downgrading page table protection not changing it to point
973 * See Documentation/vm/mmu_notifier.rst
979 mmu_notifier_invalidate_range_end(&range);
984 static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
986 if (vma->vm_flags & VM_SHARED)
992 int page_mkclean(struct page *page)
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,
1002 BUG_ON(!PageLocked(page));
1004 if (!page_mapped(page))
1007 mapping = page_mapping(page);
1011 rmap_walk(page, &rwc);
1015 EXPORT_SYMBOL_GPL(page_mkclean);
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
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
1027 void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
1029 struct anon_vma *anon_vma = vma->anon_vma;
1031 page = compound_head(page);
1033 VM_BUG_ON_PAGE(!PageLocked(page), page);
1034 VM_BUG_ON_VMA(!anon_vma, vma);
1036 anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
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.
1042 WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
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
1052 static void __page_set_anon_rmap(struct page *page,
1053 struct vm_area_struct *vma, unsigned long address, int exclusive)
1055 struct anon_vma *anon_vma = vma->anon_vma;
1063 * If the page isn't exclusively mapped into this vma,
1064 * we must use the _oldest_ possible anon_vma for the
1068 anon_vma = anon_vma->root;
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);
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
1081 static void __page_check_anon_rmap(struct page *page,
1082 struct vm_area_struct *vma, unsigned long address)
1085 * The page's anon-rmap details (mapping and index) are guaranteed to
1086 * be set up correctly at this point.
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.
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.
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),
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
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).
1113 void page_add_anon_rmap(struct page *page,
1114 struct vm_area_struct *vma, unsigned long address, bool compound)
1116 do_page_add_anon_rmap(page, vma, address, compound ? RMAP_COMPOUND : 0);
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.
1124 void do_page_add_anon_rmap(struct page *page,
1125 struct vm_area_struct *vma, unsigned long address, int flags)
1127 bool compound = flags & RMAP_COMPOUND;
1132 VM_BUG_ON_PAGE(!PageLocked(page), page);
1133 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
1134 mapcount = compound_mapcount_ptr(page);
1135 first = atomic_inc_and_test(mapcount);
1137 first = atomic_inc_and_test(&page->_mapcount);
1141 int nr = compound ? hpage_nr_pages(page) : 1;
1143 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1144 * these counters are not modified in interrupt context, and
1145 * pte lock(a spinlock) is held, which implies preemption
1149 __inc_node_page_state(page, NR_ANON_THPS);
1150 __mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, nr);
1152 if (unlikely(PageKsm(page)))
1155 VM_BUG_ON_PAGE(!PageLocked(page), page);
1157 /* address might be in next vma when migration races vma_adjust */
1159 __page_set_anon_rmap(page, vma, address,
1160 flags & RMAP_EXCLUSIVE);
1162 __page_check_anon_rmap(page, vma, address);
1166 * page_add_new_anon_rmap - add pte mapping to a new anonymous page
1167 * @page: the page to add the mapping to
1168 * @vma: the vm area in which the mapping is added
1169 * @address: the user virtual address mapped
1170 * @compound: charge the page as compound or small page
1172 * Same as page_add_anon_rmap but must only be called on *new* pages.
1173 * This means the inc-and-test can be bypassed.
1174 * Page does not have to be locked.
1176 void page_add_new_anon_rmap(struct page *page,
1177 struct vm_area_struct *vma, unsigned long address, bool compound)
1179 int nr = compound ? hpage_nr_pages(page) : 1;
1181 VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
1182 __SetPageSwapBacked(page);
1184 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
1185 /* increment count (starts at -1) */
1186 atomic_set(compound_mapcount_ptr(page), 0);
1187 if (hpage_pincount_available(page))
1188 atomic_set(compound_pincount_ptr(page), 0);
1190 __inc_node_page_state(page, NR_ANON_THPS);
1192 /* Anon THP always mapped first with PMD */
1193 VM_BUG_ON_PAGE(PageTransCompound(page), page);
1194 /* increment count (starts at -1) */
1195 atomic_set(&page->_mapcount, 0);
1197 __mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, nr);
1198 __page_set_anon_rmap(page, vma, address, 1);
1202 * page_add_file_rmap - add pte mapping to a file page
1203 * @page: the page to add the mapping to
1204 * @compound: charge the page as compound or small page
1206 * The caller needs to hold the pte lock.
1208 void page_add_file_rmap(struct page *page, bool compound)
1212 VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
1213 lock_page_memcg(page);
1214 if (compound && PageTransHuge(page)) {
1215 for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
1216 if (atomic_inc_and_test(&page[i]._mapcount))
1219 if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
1221 if (PageSwapBacked(page))
1222 __inc_node_page_state(page, NR_SHMEM_PMDMAPPED);
1224 __inc_node_page_state(page, NR_FILE_PMDMAPPED);
1226 if (PageTransCompound(page) && page_mapping(page)) {
1227 VM_WARN_ON_ONCE(!PageLocked(page));
1229 SetPageDoubleMap(compound_head(page));
1230 if (PageMlocked(page))
1231 clear_page_mlock(compound_head(page));
1233 if (!atomic_inc_and_test(&page->_mapcount))
1236 __mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
1238 unlock_page_memcg(page);
1241 static void page_remove_file_rmap(struct page *page, bool compound)
1245 VM_BUG_ON_PAGE(compound && !PageHead(page), page);
1246 lock_page_memcg(page);
1248 /* Hugepages are not counted in NR_FILE_MAPPED for now. */
1249 if (unlikely(PageHuge(page))) {
1250 /* hugetlb pages are always mapped with pmds */
1251 atomic_dec(compound_mapcount_ptr(page));
1255 /* page still mapped by someone else? */
1256 if (compound && PageTransHuge(page)) {
1257 for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
1258 if (atomic_add_negative(-1, &page[i]._mapcount))
1261 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1263 if (PageSwapBacked(page))
1264 __dec_node_page_state(page, NR_SHMEM_PMDMAPPED);
1266 __dec_node_page_state(page, NR_FILE_PMDMAPPED);
1268 if (!atomic_add_negative(-1, &page->_mapcount))
1273 * We use the irq-unsafe __{inc|mod}_lruvec_page_state because
1274 * these counters are not modified in interrupt context, and
1275 * pte lock(a spinlock) is held, which implies preemption disabled.
1277 __mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
1279 if (unlikely(PageMlocked(page)))
1280 clear_page_mlock(page);
1282 unlock_page_memcg(page);
1285 static void page_remove_anon_compound_rmap(struct page *page)
1289 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1292 /* Hugepages are not counted in NR_ANON_PAGES for now. */
1293 if (unlikely(PageHuge(page)))
1296 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1299 __dec_node_page_state(page, NR_ANON_THPS);
1301 if (TestClearPageDoubleMap(page)) {
1303 * Subpages can be mapped with PTEs too. Check how many of
1304 * them are still mapped.
1306 for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
1307 if (atomic_add_negative(-1, &page[i]._mapcount))
1312 * Queue the page for deferred split if at least one small
1313 * page of the compound page is unmapped, but at least one
1314 * small page is still mapped.
1316 if (nr && nr < HPAGE_PMD_NR)
1317 deferred_split_huge_page(page);
1322 if (unlikely(PageMlocked(page)))
1323 clear_page_mlock(page);
1326 __mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, -nr);
1330 * page_remove_rmap - take down pte mapping from a page
1331 * @page: page to remove mapping from
1332 * @compound: uncharge the page as compound or small page
1334 * The caller needs to hold the pte lock.
1336 void page_remove_rmap(struct page *page, bool compound)
1338 if (!PageAnon(page))
1339 return page_remove_file_rmap(page, compound);
1342 return page_remove_anon_compound_rmap(page);
1344 /* page still mapped by someone else? */
1345 if (!atomic_add_negative(-1, &page->_mapcount))
1349 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1350 * these counters are not modified in interrupt context, and
1351 * pte lock(a spinlock) is held, which implies preemption disabled.
1353 __dec_node_page_state(page, NR_ANON_MAPPED);
1355 if (unlikely(PageMlocked(page)))
1356 clear_page_mlock(page);
1358 if (PageTransCompound(page))
1359 deferred_split_huge_page(compound_head(page));
1362 * It would be tidy to reset the PageAnon mapping here,
1363 * but that might overwrite a racing page_add_anon_rmap
1364 * which increments mapcount after us but sets mapping
1365 * before us: so leave the reset to free_unref_page,
1366 * and remember that it's only reliable while mapped.
1367 * Leaving it set also helps swapoff to reinstate ptes
1368 * faster for those pages still in swapcache.
1373 * @arg: enum ttu_flags will be passed to this argument
1375 static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,
1376 unsigned long address, void *arg)
1378 struct mm_struct *mm = vma->vm_mm;
1379 struct page_vma_mapped_walk pvmw = {
1385 struct page *subpage;
1387 struct mmu_notifier_range range;
1388 enum ttu_flags flags = (enum ttu_flags)arg;
1390 /* munlock has nothing to gain from examining un-locked vmas */
1391 if ((flags & TTU_MUNLOCK) && !(vma->vm_flags & VM_LOCKED))
1394 if (IS_ENABLED(CONFIG_MIGRATION) && (flags & TTU_MIGRATION) &&
1395 is_zone_device_page(page) && !is_device_private_page(page))
1398 if (flags & TTU_SPLIT_HUGE_PMD) {
1399 split_huge_pmd_address(vma, address,
1400 flags & TTU_SPLIT_FREEZE, page);
1404 * For THP, we have to assume the worse case ie pmd for invalidation.
1405 * For hugetlb, it could be much worse if we need to do pud
1406 * invalidation in the case of pmd sharing.
1408 * Note that the page can not be free in this function as call of
1409 * try_to_unmap() must hold a reference on the page.
1411 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1413 min(vma->vm_end, address + page_size(page)));
1414 if (PageHuge(page)) {
1416 * If sharing is possible, start and end will be adjusted
1419 * If called for a huge page, caller must hold i_mmap_rwsem
1420 * in write mode as it is possible to call huge_pmd_unshare.
1422 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1425 mmu_notifier_invalidate_range_start(&range);
1427 while (page_vma_mapped_walk(&pvmw)) {
1428 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1429 /* PMD-mapped THP migration entry */
1430 if (!pvmw.pte && (flags & TTU_MIGRATION)) {
1431 VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
1433 set_pmd_migration_entry(&pvmw, page);
1439 * If the page is mlock()d, we cannot swap it out.
1440 * If it's recently referenced (perhaps page_referenced
1441 * skipped over this mm) then we should reactivate it.
1443 if (!(flags & TTU_IGNORE_MLOCK)) {
1444 if (vma->vm_flags & VM_LOCKED) {
1445 /* PTE-mapped THP are never mlocked */
1446 if (!PageTransCompound(page)) {
1448 * Holding pte lock, we do *not* need
1451 mlock_vma_page(page);
1454 page_vma_mapped_walk_done(&pvmw);
1457 if (flags & TTU_MUNLOCK)
1461 /* Unexpected PMD-mapped THP? */
1462 VM_BUG_ON_PAGE(!pvmw.pte, page);
1464 subpage = page - page_to_pfn(page) + pte_pfn(*pvmw.pte);
1465 address = pvmw.address;
1467 if (PageHuge(page)) {
1469 * To call huge_pmd_unshare, i_mmap_rwsem must be
1470 * held in write mode. Caller needs to explicitly
1471 * do this outside rmap routines.
1473 VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
1474 if (huge_pmd_unshare(mm, &address, pvmw.pte)) {
1476 * huge_pmd_unshare unmapped an entire PMD
1477 * page. There is no way of knowing exactly
1478 * which PMDs may be cached for this mm, so
1479 * we must flush them all. start/end were
1480 * already adjusted above to cover this range.
1482 flush_cache_range(vma, range.start, range.end);
1483 flush_tlb_range(vma, range.start, range.end);
1484 mmu_notifier_invalidate_range(mm, range.start,
1488 * The ref count of the PMD page was dropped
1489 * which is part of the way map counting
1490 * is done for shared PMDs. Return 'true'
1491 * here. When there is no other sharing,
1492 * huge_pmd_unshare returns false and we will
1493 * unmap the actual page and drop map count
1496 page_vma_mapped_walk_done(&pvmw);
1501 if (IS_ENABLED(CONFIG_MIGRATION) &&
1502 (flags & TTU_MIGRATION) &&
1503 is_zone_device_page(page)) {
1507 pteval = ptep_get_and_clear(mm, pvmw.address, pvmw.pte);
1510 * Store the pfn of the page in a special migration
1511 * pte. do_swap_page() will wait until the migration
1512 * pte is removed and then restart fault handling.
1514 entry = make_migration_entry(page, 0);
1515 swp_pte = swp_entry_to_pte(entry);
1516 if (pte_soft_dirty(pteval))
1517 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1518 set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
1520 * No need to invalidate here it will synchronize on
1521 * against the special swap migration pte.
1523 * The assignment to subpage above was computed from a
1524 * swap PTE which results in an invalid pointer.
1525 * Since only PAGE_SIZE pages can currently be
1526 * migrated, just set it to page. This will need to be
1527 * changed when hugepage migrations to device private
1528 * memory are supported.
1534 if (!(flags & TTU_IGNORE_ACCESS)) {
1535 if (ptep_clear_flush_young_notify(vma, address,
1538 page_vma_mapped_walk_done(&pvmw);
1543 /* Nuke the page table entry. */
1544 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
1545 if (should_defer_flush(mm, flags)) {
1547 * We clear the PTE but do not flush so potentially
1548 * a remote CPU could still be writing to the page.
1549 * If the entry was previously clean then the
1550 * architecture must guarantee that a clear->dirty
1551 * transition on a cached TLB entry is written through
1552 * and traps if the PTE is unmapped.
1554 pteval = ptep_get_and_clear(mm, address, pvmw.pte);
1556 set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
1558 pteval = ptep_clear_flush(vma, address, pvmw.pte);
1561 /* Move the dirty bit to the page. Now the pte is gone. */
1562 if (pte_dirty(pteval))
1563 set_page_dirty(page);
1565 /* Update high watermark before we lower rss */
1566 update_hiwater_rss(mm);
1568 if (PageHWPoison(page) && !(flags & TTU_IGNORE_HWPOISON)) {
1569 pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
1570 if (PageHuge(page)) {
1571 hugetlb_count_sub(compound_nr(page), mm);
1572 set_huge_swap_pte_at(mm, address,
1574 vma_mmu_pagesize(vma));
1576 dec_mm_counter(mm, mm_counter(page));
1577 set_pte_at(mm, address, pvmw.pte, pteval);
1580 } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
1582 * The guest indicated that the page content is of no
1583 * interest anymore. Simply discard the pte, vmscan
1584 * will take care of the rest.
1585 * A future reference will then fault in a new zero
1586 * page. When userfaultfd is active, we must not drop
1587 * this page though, as its main user (postcopy
1588 * migration) will not expect userfaults on already
1591 dec_mm_counter(mm, mm_counter(page));
1592 /* We have to invalidate as we cleared the pte */
1593 mmu_notifier_invalidate_range(mm, address,
1594 address + PAGE_SIZE);
1595 } else if (IS_ENABLED(CONFIG_MIGRATION) &&
1596 (flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))) {
1600 if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1601 set_pte_at(mm, address, pvmw.pte, pteval);
1603 page_vma_mapped_walk_done(&pvmw);
1608 * Store the pfn of the page in a special migration
1609 * pte. do_swap_page() will wait until the migration
1610 * pte is removed and then restart fault handling.
1612 entry = make_migration_entry(subpage,
1614 swp_pte = swp_entry_to_pte(entry);
1615 if (pte_soft_dirty(pteval))
1616 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1617 set_pte_at(mm, address, pvmw.pte, swp_pte);
1619 * No need to invalidate here it will synchronize on
1620 * against the special swap migration pte.
1622 } else if (PageAnon(page)) {
1623 swp_entry_t entry = { .val = page_private(subpage) };
1626 * Store the swap location in the pte.
1627 * See handle_pte_fault() ...
1629 if (unlikely(PageSwapBacked(page) != PageSwapCache(page))) {
1632 /* We have to invalidate as we cleared the pte */
1633 mmu_notifier_invalidate_range(mm, address,
1634 address + PAGE_SIZE);
1635 page_vma_mapped_walk_done(&pvmw);
1639 /* MADV_FREE page check */
1640 if (!PageSwapBacked(page)) {
1641 if (!PageDirty(page)) {
1642 /* Invalidate as we cleared the pte */
1643 mmu_notifier_invalidate_range(mm,
1644 address, address + PAGE_SIZE);
1645 dec_mm_counter(mm, MM_ANONPAGES);
1650 * If the page was redirtied, it cannot be
1651 * discarded. Remap the page to page table.
1653 set_pte_at(mm, address, pvmw.pte, pteval);
1654 SetPageSwapBacked(page);
1656 page_vma_mapped_walk_done(&pvmw);
1660 if (swap_duplicate(entry) < 0) {
1661 set_pte_at(mm, address, pvmw.pte, pteval);
1663 page_vma_mapped_walk_done(&pvmw);
1666 if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1667 set_pte_at(mm, address, pvmw.pte, pteval);
1669 page_vma_mapped_walk_done(&pvmw);
1672 if (list_empty(&mm->mmlist)) {
1673 spin_lock(&mmlist_lock);
1674 if (list_empty(&mm->mmlist))
1675 list_add(&mm->mmlist, &init_mm.mmlist);
1676 spin_unlock(&mmlist_lock);
1678 dec_mm_counter(mm, MM_ANONPAGES);
1679 inc_mm_counter(mm, MM_SWAPENTS);
1680 swp_pte = swp_entry_to_pte(entry);
1681 if (pte_soft_dirty(pteval))
1682 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1683 set_pte_at(mm, address, pvmw.pte, swp_pte);
1684 /* Invalidate as we cleared the pte */
1685 mmu_notifier_invalidate_range(mm, address,
1686 address + PAGE_SIZE);
1689 * This is a locked file-backed page, thus it cannot
1690 * be removed from the page cache and replaced by a new
1691 * page before mmu_notifier_invalidate_range_end, so no
1692 * concurrent thread might update its page table to
1693 * point at new page while a device still is using this
1696 * See Documentation/vm/mmu_notifier.rst
1698 dec_mm_counter(mm, mm_counter_file(page));
1702 * No need to call mmu_notifier_invalidate_range() it has be
1703 * done above for all cases requiring it to happen under page
1704 * table lock before mmu_notifier_invalidate_range_end()
1706 * See Documentation/vm/mmu_notifier.rst
1708 page_remove_rmap(subpage, PageHuge(page));
1712 mmu_notifier_invalidate_range_end(&range);
1717 static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
1719 return vma_is_temporary_stack(vma);
1722 static int page_mapcount_is_zero(struct page *page)
1724 return !total_mapcount(page);
1728 * try_to_unmap - try to remove all page table mappings to a page
1729 * @page: the page to get unmapped
1730 * @flags: action and flags
1732 * Tries to remove all the page table entries which are mapping this
1733 * page, used in the pageout path. Caller must hold the page lock.
1735 * If unmap is successful, return true. Otherwise, false.
1737 bool try_to_unmap(struct page *page, enum ttu_flags flags)
1739 struct rmap_walk_control rwc = {
1740 .rmap_one = try_to_unmap_one,
1741 .arg = (void *)flags,
1742 .done = page_mapcount_is_zero,
1743 .anon_lock = page_lock_anon_vma_read,
1747 * During exec, a temporary VMA is setup and later moved.
1748 * The VMA is moved under the anon_vma lock but not the
1749 * page tables leading to a race where migration cannot
1750 * find the migration ptes. Rather than increasing the
1751 * locking requirements of exec(), migration skips
1752 * temporary VMAs until after exec() completes.
1754 if ((flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))
1755 && !PageKsm(page) && PageAnon(page))
1756 rwc.invalid_vma = invalid_migration_vma;
1758 if (flags & TTU_RMAP_LOCKED)
1759 rmap_walk_locked(page, &rwc);
1761 rmap_walk(page, &rwc);
1763 return !page_mapcount(page) ? true : false;
1766 static int page_not_mapped(struct page *page)
1768 return !page_mapped(page);
1772 * try_to_munlock - try to munlock a page
1773 * @page: the page to be munlocked
1775 * Called from munlock code. Checks all of the VMAs mapping the page
1776 * to make sure nobody else has this page mlocked. The page will be
1777 * returned with PG_mlocked cleared if no other vmas have it mlocked.
1780 void try_to_munlock(struct page *page)
1782 struct rmap_walk_control rwc = {
1783 .rmap_one = try_to_unmap_one,
1784 .arg = (void *)TTU_MUNLOCK,
1785 .done = page_not_mapped,
1786 .anon_lock = page_lock_anon_vma_read,
1790 VM_BUG_ON_PAGE(!PageLocked(page) || PageLRU(page), page);
1791 VM_BUG_ON_PAGE(PageCompound(page) && PageDoubleMap(page), page);
1793 rmap_walk(page, &rwc);
1796 void __put_anon_vma(struct anon_vma *anon_vma)
1798 struct anon_vma *root = anon_vma->root;
1800 anon_vma_free(anon_vma);
1801 if (root != anon_vma && atomic_dec_and_test(&root->refcount))
1802 anon_vma_free(root);
1805 static struct anon_vma *rmap_walk_anon_lock(struct page *page,
1806 struct rmap_walk_control *rwc)
1808 struct anon_vma *anon_vma;
1811 return rwc->anon_lock(page);
1814 * Note: remove_migration_ptes() cannot use page_lock_anon_vma_read()
1815 * because that depends on page_mapped(); but not all its usages
1816 * are holding mmap_sem. Users without mmap_sem are required to
1817 * take a reference count to prevent the anon_vma disappearing
1819 anon_vma = page_anon_vma(page);
1823 anon_vma_lock_read(anon_vma);
1828 * rmap_walk_anon - do something to anonymous page using the object-based
1830 * @page: the page to be handled
1831 * @rwc: control variable according to each walk type
1833 * Find all the mappings of a page using the mapping pointer and the vma chains
1834 * contained in the anon_vma struct it points to.
1836 * When called from try_to_munlock(), the mmap_sem of the mm containing the vma
1837 * where the page was found will be held for write. So, we won't recheck
1838 * vm_flags for that VMA. That should be OK, because that vma shouldn't be
1841 static void rmap_walk_anon(struct page *page, struct rmap_walk_control *rwc,
1844 struct anon_vma *anon_vma;
1845 pgoff_t pgoff_start, pgoff_end;
1846 struct anon_vma_chain *avc;
1849 anon_vma = page_anon_vma(page);
1850 /* anon_vma disappear under us? */
1851 VM_BUG_ON_PAGE(!anon_vma, page);
1853 anon_vma = rmap_walk_anon_lock(page, rwc);
1858 pgoff_start = page_to_pgoff(page);
1859 pgoff_end = pgoff_start + hpage_nr_pages(page) - 1;
1860 anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
1861 pgoff_start, pgoff_end) {
1862 struct vm_area_struct *vma = avc->vma;
1863 unsigned long address = vma_address(page, vma);
1867 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
1870 if (!rwc->rmap_one(page, vma, address, rwc->arg))
1872 if (rwc->done && rwc->done(page))
1877 anon_vma_unlock_read(anon_vma);
1881 * rmap_walk_file - do something to file page using the object-based rmap method
1882 * @page: the page to be handled
1883 * @rwc: control variable according to each walk type
1885 * Find all the mappings of a page using the mapping pointer and the vma chains
1886 * contained in the address_space struct it points to.
1888 * When called from try_to_munlock(), the mmap_sem of the mm containing the vma
1889 * where the page was found will be held for write. So, we won't recheck
1890 * vm_flags for that VMA. That should be OK, because that vma shouldn't be
1893 static void rmap_walk_file(struct page *page, struct rmap_walk_control *rwc,
1896 struct address_space *mapping = page_mapping(page);
1897 pgoff_t pgoff_start, pgoff_end;
1898 struct vm_area_struct *vma;
1901 * The page lock not only makes sure that page->mapping cannot
1902 * suddenly be NULLified by truncation, it makes sure that the
1903 * structure at mapping cannot be freed and reused yet,
1904 * so we can safely take mapping->i_mmap_rwsem.
1906 VM_BUG_ON_PAGE(!PageLocked(page), page);
1911 pgoff_start = page_to_pgoff(page);
1912 pgoff_end = pgoff_start + hpage_nr_pages(page) - 1;
1914 i_mmap_lock_read(mapping);
1915 vma_interval_tree_foreach(vma, &mapping->i_mmap,
1916 pgoff_start, pgoff_end) {
1917 unsigned long address = vma_address(page, vma);
1921 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
1924 if (!rwc->rmap_one(page, vma, address, rwc->arg))
1926 if (rwc->done && rwc->done(page))
1932 i_mmap_unlock_read(mapping);
1935 void rmap_walk(struct page *page, struct rmap_walk_control *rwc)
1937 if (unlikely(PageKsm(page)))
1938 rmap_walk_ksm(page, rwc);
1939 else if (PageAnon(page))
1940 rmap_walk_anon(page, rwc, false);
1942 rmap_walk_file(page, rwc, false);
1945 /* Like rmap_walk, but caller holds relevant rmap lock */
1946 void rmap_walk_locked(struct page *page, struct rmap_walk_control *rwc)
1948 /* no ksm support for now */
1949 VM_BUG_ON_PAGE(PageKsm(page), page);
1951 rmap_walk_anon(page, rwc, true);
1953 rmap_walk_file(page, rwc, true);
1956 #ifdef CONFIG_HUGETLB_PAGE
1958 * The following two functions are for anonymous (private mapped) hugepages.
1959 * Unlike common anonymous pages, anonymous hugepages have no accounting code
1960 * and no lru code, because we handle hugepages differently from common pages.
1962 void hugepage_add_anon_rmap(struct page *page,
1963 struct vm_area_struct *vma, unsigned long address)
1965 struct anon_vma *anon_vma = vma->anon_vma;
1968 BUG_ON(!PageLocked(page));
1970 /* address might be in next vma when migration races vma_adjust */
1971 first = atomic_inc_and_test(compound_mapcount_ptr(page));
1973 __page_set_anon_rmap(page, vma, address, 0);
1976 void hugepage_add_new_anon_rmap(struct page *page,
1977 struct vm_area_struct *vma, unsigned long address)
1979 BUG_ON(address < vma->vm_start || address >= vma->vm_end);
1980 atomic_set(compound_mapcount_ptr(page), 0);
1981 if (hpage_pincount_available(page))
1982 atomic_set(compound_pincount_ptr(page), 0);
1984 __page_set_anon_rmap(page, vma, address, 1);
1986 #endif /* CONFIG_HUGETLB_PAGE */