2 * mm/rmap.c - physical to virtual reverse mappings
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.
17 * Contributions by Hugh Dickins 2003, 2004
21 * Lock ordering in mm:
23 * inode->i_rwsem (while writing or truncating, not reading or faulting)
25 * mapping->invalidate_lock (in filemap_fault)
26 * page->flags PG_locked (lock_page) * (see hugetlbfs below)
27 * hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share)
28 * mapping->i_mmap_rwsem
29 * hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
31 * mm->page_table_lock or pte_lock
32 * swap_lock (in swap_duplicate, swap_info_get)
33 * mmlist_lock (in mmput, drain_mmlist and others)
34 * mapping->private_lock (in __set_page_dirty_buffers)
35 * lock_page_memcg move_lock (in __set_page_dirty_buffers)
36 * i_pages lock (widely used)
37 * lruvec->lru_lock (in folio_lruvec_lock_irq)
38 * inode->i_lock (in set_page_dirty's __mark_inode_dirty)
39 * bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
40 * sb_lock (within inode_lock in fs/fs-writeback.c)
41 * i_pages lock (widely used, in set_page_dirty,
42 * in arch-dependent flush_dcache_mmap_lock,
43 * within bdi.wb->list_lock in __sync_single_inode)
45 * anon_vma->rwsem,mapping->i_mmap_rwsem (memory_failure, collect_procs_anon)
49 * * hugetlbfs PageHuge() pages take locks in this order:
50 * mapping->i_mmap_rwsem
51 * hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
52 * page->flags PG_locked (lock_page)
56 #include <linux/sched/mm.h>
57 #include <linux/sched/task.h>
58 #include <linux/pagemap.h>
59 #include <linux/swap.h>
60 #include <linux/swapops.h>
61 #include <linux/slab.h>
62 #include <linux/init.h>
63 #include <linux/ksm.h>
64 #include <linux/rmap.h>
65 #include <linux/rcupdate.h>
66 #include <linux/export.h>
67 #include <linux/memcontrol.h>
68 #include <linux/mmu_notifier.h>
69 #include <linux/migrate.h>
70 #include <linux/hugetlb.h>
71 #include <linux/huge_mm.h>
72 #include <linux/backing-dev.h>
73 #include <linux/page_idle.h>
74 #include <linux/memremap.h>
75 #include <linux/userfaultfd_k.h>
77 #include <asm/tlbflush.h>
79 #include <trace/events/tlb.h>
83 static struct kmem_cache *anon_vma_cachep;
84 static struct kmem_cache *anon_vma_chain_cachep;
86 static inline struct anon_vma *anon_vma_alloc(void)
88 struct anon_vma *anon_vma;
90 anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
92 atomic_set(&anon_vma->refcount, 1);
93 anon_vma->degree = 1; /* Reference for first vma */
94 anon_vma->parent = anon_vma;
96 * Initialise the anon_vma root to point to itself. If called
97 * from fork, the root will be reset to the parents anon_vma.
99 anon_vma->root = anon_vma;
105 static inline void anon_vma_free(struct anon_vma *anon_vma)
107 VM_BUG_ON(atomic_read(&anon_vma->refcount));
110 * Synchronize against folio_lock_anon_vma_read() such that
111 * we can safely hold the lock without the anon_vma getting
114 * Relies on the full mb implied by the atomic_dec_and_test() from
115 * put_anon_vma() against the acquire barrier implied by
116 * down_read_trylock() from folio_lock_anon_vma_read(). This orders:
118 * folio_lock_anon_vma_read() VS put_anon_vma()
119 * down_read_trylock() atomic_dec_and_test()
121 * atomic_read() rwsem_is_locked()
123 * LOCK should suffice since the actual taking of the lock must
124 * happen _before_ what follows.
127 if (rwsem_is_locked(&anon_vma->root->rwsem)) {
128 anon_vma_lock_write(anon_vma);
129 anon_vma_unlock_write(anon_vma);
132 kmem_cache_free(anon_vma_cachep, anon_vma);
135 static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
137 return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
140 static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
142 kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
145 static void anon_vma_chain_link(struct vm_area_struct *vma,
146 struct anon_vma_chain *avc,
147 struct anon_vma *anon_vma)
150 avc->anon_vma = anon_vma;
151 list_add(&avc->same_vma, &vma->anon_vma_chain);
152 anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
156 * __anon_vma_prepare - attach an anon_vma to a memory region
157 * @vma: the memory region in question
159 * This makes sure the memory mapping described by 'vma' has
160 * an 'anon_vma' attached to it, so that we can associate the
161 * anonymous pages mapped into it with that anon_vma.
163 * The common case will be that we already have one, which
164 * is handled inline by anon_vma_prepare(). But if
165 * not we either need to find an adjacent mapping that we
166 * can re-use the anon_vma from (very common when the only
167 * reason for splitting a vma has been mprotect()), or we
168 * allocate a new one.
170 * Anon-vma allocations are very subtle, because we may have
171 * optimistically looked up an anon_vma in folio_lock_anon_vma_read()
172 * and that may actually touch the rwsem even in the newly
173 * allocated vma (it depends on RCU to make sure that the
174 * anon_vma isn't actually destroyed).
176 * As a result, we need to do proper anon_vma locking even
177 * for the new allocation. At the same time, we do not want
178 * to do any locking for the common case of already having
181 * This must be called with the mmap_lock held for reading.
183 int __anon_vma_prepare(struct vm_area_struct *vma)
185 struct mm_struct *mm = vma->vm_mm;
186 struct anon_vma *anon_vma, *allocated;
187 struct anon_vma_chain *avc;
191 avc = anon_vma_chain_alloc(GFP_KERNEL);
195 anon_vma = find_mergeable_anon_vma(vma);
198 anon_vma = anon_vma_alloc();
199 if (unlikely(!anon_vma))
200 goto out_enomem_free_avc;
201 allocated = anon_vma;
204 anon_vma_lock_write(anon_vma);
205 /* page_table_lock to protect against threads */
206 spin_lock(&mm->page_table_lock);
207 if (likely(!vma->anon_vma)) {
208 vma->anon_vma = anon_vma;
209 anon_vma_chain_link(vma, avc, anon_vma);
210 /* vma reference or self-parent link for new root */
215 spin_unlock(&mm->page_table_lock);
216 anon_vma_unlock_write(anon_vma);
218 if (unlikely(allocated))
219 put_anon_vma(allocated);
221 anon_vma_chain_free(avc);
226 anon_vma_chain_free(avc);
232 * This is a useful helper function for locking the anon_vma root as
233 * we traverse the vma->anon_vma_chain, looping over anon_vma's that
236 * Such anon_vma's should have the same root, so you'd expect to see
237 * just a single mutex_lock for the whole traversal.
239 static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
241 struct anon_vma *new_root = anon_vma->root;
242 if (new_root != root) {
243 if (WARN_ON_ONCE(root))
244 up_write(&root->rwsem);
246 down_write(&root->rwsem);
251 static inline void unlock_anon_vma_root(struct anon_vma *root)
254 up_write(&root->rwsem);
258 * Attach the anon_vmas from src to dst.
259 * Returns 0 on success, -ENOMEM on failure.
261 * anon_vma_clone() is called by __vma_adjust(), __split_vma(), copy_vma() and
262 * anon_vma_fork(). The first three want an exact copy of src, while the last
263 * one, anon_vma_fork(), may try to reuse an existing anon_vma to prevent
264 * endless growth of anon_vma. Since dst->anon_vma is set to NULL before call,
265 * we can identify this case by checking (!dst->anon_vma && src->anon_vma).
267 * If (!dst->anon_vma && src->anon_vma) is true, this function tries to find
268 * and reuse existing anon_vma which has no vmas and only one child anon_vma.
269 * This prevents degradation of anon_vma hierarchy to endless linear chain in
270 * case of constantly forking task. On the other hand, an anon_vma with more
271 * than one child isn't reused even if there was no alive vma, thus rmap
272 * walker has a good chance of avoiding scanning the whole hierarchy when it
273 * searches where page is mapped.
275 int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
277 struct anon_vma_chain *avc, *pavc;
278 struct anon_vma *root = NULL;
280 list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
281 struct anon_vma *anon_vma;
283 avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
284 if (unlikely(!avc)) {
285 unlock_anon_vma_root(root);
287 avc = anon_vma_chain_alloc(GFP_KERNEL);
291 anon_vma = pavc->anon_vma;
292 root = lock_anon_vma_root(root, anon_vma);
293 anon_vma_chain_link(dst, avc, anon_vma);
296 * Reuse existing anon_vma if its degree lower than two,
297 * that means it has no vma and only one anon_vma child.
299 * Do not chose parent anon_vma, otherwise first child
300 * will always reuse it. Root anon_vma is never reused:
301 * it has self-parent reference and at least one child.
303 if (!dst->anon_vma && src->anon_vma &&
304 anon_vma != src->anon_vma && anon_vma->degree < 2)
305 dst->anon_vma = anon_vma;
308 dst->anon_vma->degree++;
309 unlock_anon_vma_root(root);
314 * dst->anon_vma is dropped here otherwise its degree can be incorrectly
315 * decremented in unlink_anon_vmas().
316 * We can safely do this because callers of anon_vma_clone() don't care
317 * about dst->anon_vma if anon_vma_clone() failed.
319 dst->anon_vma = NULL;
320 unlink_anon_vmas(dst);
325 * Attach vma to its own anon_vma, as well as to the anon_vmas that
326 * the corresponding VMA in the parent process is attached to.
327 * Returns 0 on success, non-zero on failure.
329 int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
331 struct anon_vma_chain *avc;
332 struct anon_vma *anon_vma;
335 /* Don't bother if the parent process has no anon_vma here. */
339 /* Drop inherited anon_vma, we'll reuse existing or allocate new. */
340 vma->anon_vma = NULL;
343 * First, attach the new VMA to the parent VMA's anon_vmas,
344 * so rmap can find non-COWed pages in child processes.
346 error = anon_vma_clone(vma, pvma);
350 /* An existing anon_vma has been reused, all done then. */
354 /* Then add our own anon_vma. */
355 anon_vma = anon_vma_alloc();
358 avc = anon_vma_chain_alloc(GFP_KERNEL);
360 goto out_error_free_anon_vma;
363 * The root anon_vma's rwsem is the lock actually used when we
364 * lock any of the anon_vmas in this anon_vma tree.
366 anon_vma->root = pvma->anon_vma->root;
367 anon_vma->parent = pvma->anon_vma;
369 * With refcounts, an anon_vma can stay around longer than the
370 * process it belongs to. The root anon_vma needs to be pinned until
371 * this anon_vma is freed, because the lock lives in the root.
373 get_anon_vma(anon_vma->root);
374 /* Mark this anon_vma as the one where our new (COWed) pages go. */
375 vma->anon_vma = anon_vma;
376 anon_vma_lock_write(anon_vma);
377 anon_vma_chain_link(vma, avc, anon_vma);
378 anon_vma->parent->degree++;
379 anon_vma_unlock_write(anon_vma);
383 out_error_free_anon_vma:
384 put_anon_vma(anon_vma);
386 unlink_anon_vmas(vma);
390 void unlink_anon_vmas(struct vm_area_struct *vma)
392 struct anon_vma_chain *avc, *next;
393 struct anon_vma *root = NULL;
396 * Unlink each anon_vma chained to the VMA. This list is ordered
397 * from newest to oldest, ensuring the root anon_vma gets freed last.
399 list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
400 struct anon_vma *anon_vma = avc->anon_vma;
402 root = lock_anon_vma_root(root, anon_vma);
403 anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
406 * Leave empty anon_vmas on the list - we'll need
407 * to free them outside the lock.
409 if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
410 anon_vma->parent->degree--;
414 list_del(&avc->same_vma);
415 anon_vma_chain_free(avc);
418 vma->anon_vma->degree--;
421 * vma would still be needed after unlink, and anon_vma will be prepared
424 vma->anon_vma = NULL;
426 unlock_anon_vma_root(root);
429 * Iterate the list once more, it now only contains empty and unlinked
430 * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
431 * needing to write-acquire the anon_vma->root->rwsem.
433 list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
434 struct anon_vma *anon_vma = avc->anon_vma;
436 VM_WARN_ON(anon_vma->degree);
437 put_anon_vma(anon_vma);
439 list_del(&avc->same_vma);
440 anon_vma_chain_free(avc);
444 static void anon_vma_ctor(void *data)
446 struct anon_vma *anon_vma = data;
448 init_rwsem(&anon_vma->rwsem);
449 atomic_set(&anon_vma->refcount, 0);
450 anon_vma->rb_root = RB_ROOT_CACHED;
453 void __init anon_vma_init(void)
455 anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
456 0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
458 anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
459 SLAB_PANIC|SLAB_ACCOUNT);
463 * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
465 * Since there is no serialization what so ever against page_remove_rmap()
466 * the best this function can do is return a refcount increased anon_vma
467 * that might have been relevant to this page.
469 * The page might have been remapped to a different anon_vma or the anon_vma
470 * returned may already be freed (and even reused).
472 * In case it was remapped to a different anon_vma, the new anon_vma will be a
473 * child of the old anon_vma, and the anon_vma lifetime rules will therefore
474 * ensure that any anon_vma obtained from the page will still be valid for as
475 * long as we observe page_mapped() [ hence all those page_mapped() tests ].
477 * All users of this function must be very careful when walking the anon_vma
478 * chain and verify that the page in question is indeed mapped in it
479 * [ something equivalent to page_mapped_in_vma() ].
481 * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
482 * page_remove_rmap() that the anon_vma pointer from page->mapping is valid
483 * if there is a mapcount, we can dereference the anon_vma after observing
486 struct anon_vma *page_get_anon_vma(struct page *page)
488 struct anon_vma *anon_vma = NULL;
489 unsigned long anon_mapping;
492 anon_mapping = (unsigned long)READ_ONCE(page->mapping);
493 if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
495 if (!page_mapped(page))
498 anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
499 if (!atomic_inc_not_zero(&anon_vma->refcount)) {
505 * If this page is still mapped, then its anon_vma cannot have been
506 * freed. But if it has been unmapped, we have no security against the
507 * anon_vma structure being freed and reused (for another anon_vma:
508 * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
509 * above cannot corrupt).
511 if (!page_mapped(page)) {
513 put_anon_vma(anon_vma);
523 * Similar to page_get_anon_vma() except it locks the anon_vma.
525 * Its a little more complex as it tries to keep the fast path to a single
526 * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
527 * reference like with page_get_anon_vma() and then block on the mutex.
529 struct anon_vma *folio_lock_anon_vma_read(struct folio *folio)
531 struct anon_vma *anon_vma = NULL;
532 struct anon_vma *root_anon_vma;
533 unsigned long anon_mapping;
536 anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
537 if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
539 if (!folio_mapped(folio))
542 anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
543 root_anon_vma = READ_ONCE(anon_vma->root);
544 if (down_read_trylock(&root_anon_vma->rwsem)) {
546 * If the folio is still mapped, then this anon_vma is still
547 * its anon_vma, and holding the mutex ensures that it will
548 * not go away, see anon_vma_free().
550 if (!folio_mapped(folio)) {
551 up_read(&root_anon_vma->rwsem);
557 /* trylock failed, we got to sleep */
558 if (!atomic_inc_not_zero(&anon_vma->refcount)) {
563 if (!folio_mapped(folio)) {
565 put_anon_vma(anon_vma);
569 /* we pinned the anon_vma, its safe to sleep */
571 anon_vma_lock_read(anon_vma);
573 if (atomic_dec_and_test(&anon_vma->refcount)) {
575 * Oops, we held the last refcount, release the lock
576 * and bail -- can't simply use put_anon_vma() because
577 * we'll deadlock on the anon_vma_lock_write() recursion.
579 anon_vma_unlock_read(anon_vma);
580 __put_anon_vma(anon_vma);
591 void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
593 anon_vma_unlock_read(anon_vma);
596 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
598 * Flush TLB entries for recently unmapped pages from remote CPUs. It is
599 * important if a PTE was dirty when it was unmapped that it's flushed
600 * before any IO is initiated on the page to prevent lost writes. Similarly,
601 * it must be flushed before freeing to prevent data leakage.
603 void try_to_unmap_flush(void)
605 struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
607 if (!tlb_ubc->flush_required)
610 arch_tlbbatch_flush(&tlb_ubc->arch);
611 tlb_ubc->flush_required = false;
612 tlb_ubc->writable = false;
615 /* Flush iff there are potentially writable TLB entries that can race with IO */
616 void try_to_unmap_flush_dirty(void)
618 struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
620 if (tlb_ubc->writable)
621 try_to_unmap_flush();
625 * Bits 0-14 of mm->tlb_flush_batched record pending generations.
626 * Bits 16-30 of mm->tlb_flush_batched bit record flushed generations.
628 #define TLB_FLUSH_BATCH_FLUSHED_SHIFT 16
629 #define TLB_FLUSH_BATCH_PENDING_MASK \
630 ((1 << (TLB_FLUSH_BATCH_FLUSHED_SHIFT - 1)) - 1)
631 #define TLB_FLUSH_BATCH_PENDING_LARGE \
632 (TLB_FLUSH_BATCH_PENDING_MASK / 2)
634 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
636 struct tlbflush_unmap_batch *tlb_ubc = ¤t->tlb_ubc;
639 arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
640 tlb_ubc->flush_required = true;
643 * Ensure compiler does not re-order the setting of tlb_flush_batched
644 * before the PTE is cleared.
647 batch = atomic_read(&mm->tlb_flush_batched);
649 if ((batch & TLB_FLUSH_BATCH_PENDING_MASK) > TLB_FLUSH_BATCH_PENDING_LARGE) {
651 * Prevent `pending' from catching up with `flushed' because of
652 * overflow. Reset `pending' and `flushed' to be 1 and 0 if
653 * `pending' becomes large.
655 nbatch = atomic_cmpxchg(&mm->tlb_flush_batched, batch, 1);
656 if (nbatch != batch) {
661 atomic_inc(&mm->tlb_flush_batched);
665 * If the PTE was dirty then it's best to assume it's writable. The
666 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
667 * before the page is queued for IO.
670 tlb_ubc->writable = true;
674 * Returns true if the TLB flush should be deferred to the end of a batch of
675 * unmap operations to reduce IPIs.
677 static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
679 bool should_defer = false;
681 if (!(flags & TTU_BATCH_FLUSH))
684 /* If remote CPUs need to be flushed then defer batch the flush */
685 if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
693 * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
694 * releasing the PTL if TLB flushes are batched. It's possible for a parallel
695 * operation such as mprotect or munmap to race between reclaim unmapping
696 * the page and flushing the page. If this race occurs, it potentially allows
697 * access to data via a stale TLB entry. Tracking all mm's that have TLB
698 * batching in flight would be expensive during reclaim so instead track
699 * whether TLB batching occurred in the past and if so then do a flush here
700 * if required. This will cost one additional flush per reclaim cycle paid
701 * by the first operation at risk such as mprotect and mumap.
703 * This must be called under the PTL so that an access to tlb_flush_batched
704 * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
707 void flush_tlb_batched_pending(struct mm_struct *mm)
709 int batch = atomic_read(&mm->tlb_flush_batched);
710 int pending = batch & TLB_FLUSH_BATCH_PENDING_MASK;
711 int flushed = batch >> TLB_FLUSH_BATCH_FLUSHED_SHIFT;
713 if (pending != flushed) {
716 * If the new TLB flushing is pending during flushing, leave
717 * mm->tlb_flush_batched as is, to avoid losing flushing.
719 atomic_cmpxchg(&mm->tlb_flush_batched, batch,
720 pending | (pending << TLB_FLUSH_BATCH_FLUSHED_SHIFT));
724 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
728 static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
732 #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
735 * At what user virtual address is page expected in vma?
736 * Caller should check the page is actually part of the vma.
738 unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
740 struct folio *folio = page_folio(page);
741 if (folio_test_anon(folio)) {
742 struct anon_vma *page__anon_vma = folio_anon_vma(folio);
744 * Note: swapoff's unuse_vma() is more efficient with this
745 * check, and needs it to match anon_vma when KSM is active.
747 if (!vma->anon_vma || !page__anon_vma ||
748 vma->anon_vma->root != page__anon_vma->root)
750 } else if (!vma->vm_file) {
752 } else if (vma->vm_file->f_mapping != folio->mapping) {
756 return vma_address(page, vma);
759 pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
767 pgd = pgd_offset(mm, address);
768 if (!pgd_present(*pgd))
771 p4d = p4d_offset(pgd, address);
772 if (!p4d_present(*p4d))
775 pud = pud_offset(p4d, address);
776 if (!pud_present(*pud))
779 pmd = pmd_offset(pud, address);
781 * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
782 * without holding anon_vma lock for write. So when looking for a
783 * genuine pmde (in which to find pte), test present and !THP together.
787 if (!pmd_present(pmde) || pmd_trans_huge(pmde))
793 struct folio_referenced_arg {
796 unsigned long vm_flags;
797 struct mem_cgroup *memcg;
800 * arg: folio_referenced_arg will be passed
802 static bool folio_referenced_one(struct folio *folio,
803 struct vm_area_struct *vma, unsigned long address, void *arg)
805 struct folio_referenced_arg *pra = arg;
806 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
809 while (page_vma_mapped_walk(&pvmw)) {
810 address = pvmw.address;
812 if ((vma->vm_flags & VM_LOCKED) &&
813 (!folio_test_large(folio) || !pvmw.pte)) {
814 /* Restore the mlock which got missed */
815 mlock_vma_folio(folio, vma, !pvmw.pte);
816 page_vma_mapped_walk_done(&pvmw);
817 pra->vm_flags |= VM_LOCKED;
818 return false; /* To break the loop */
822 if (ptep_clear_flush_young_notify(vma, address,
825 * Don't treat a reference through
826 * a sequentially read mapping as such.
827 * If the folio has been used in another mapping,
828 * we will catch it; if this other mapping is
829 * already gone, the unmap path will have set
830 * the referenced flag or activated the folio.
832 if (likely(!(vma->vm_flags & VM_SEQ_READ)))
835 } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
836 if (pmdp_clear_flush_young_notify(vma, address,
840 /* unexpected pmd-mapped folio? */
848 folio_clear_idle(folio);
849 if (folio_test_clear_young(folio))
854 pra->vm_flags |= vma->vm_flags & ~VM_LOCKED;
858 return false; /* To break the loop */
863 static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
865 struct folio_referenced_arg *pra = arg;
866 struct mem_cgroup *memcg = pra->memcg;
868 if (!mm_match_cgroup(vma->vm_mm, memcg))
875 * folio_referenced() - Test if the folio was referenced.
876 * @folio: The folio to test.
877 * @is_locked: Caller holds lock on the folio.
878 * @memcg: target memory cgroup
879 * @vm_flags: A combination of all the vma->vm_flags which referenced the folio.
881 * Quick test_and_clear_referenced for all mappings of a folio,
883 * Return: The number of mappings which referenced the folio.
885 int folio_referenced(struct folio *folio, int is_locked,
886 struct mem_cgroup *memcg, unsigned long *vm_flags)
889 struct folio_referenced_arg pra = {
890 .mapcount = folio_mapcount(folio),
893 struct rmap_walk_control rwc = {
894 .rmap_one = folio_referenced_one,
896 .anon_lock = folio_lock_anon_vma_read,
903 if (!folio_raw_mapping(folio))
906 if (!is_locked && (!folio_test_anon(folio) || folio_test_ksm(folio))) {
907 we_locked = folio_trylock(folio);
913 * If we are reclaiming on behalf of a cgroup, skip
914 * counting on behalf of references from different
918 rwc.invalid_vma = invalid_folio_referenced_vma;
921 rmap_walk(folio, &rwc);
922 *vm_flags = pra.vm_flags;
927 return pra.referenced;
930 static bool page_mkclean_one(struct folio *folio, struct vm_area_struct *vma,
931 unsigned long address, void *arg)
933 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, PVMW_SYNC);
934 struct mmu_notifier_range range;
938 * We have to assume the worse case ie pmd for invalidation. Note that
939 * the folio can not be freed from this function.
941 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
942 0, vma, vma->vm_mm, address,
943 vma_address_end(&pvmw));
944 mmu_notifier_invalidate_range_start(&range);
946 while (page_vma_mapped_walk(&pvmw)) {
949 address = pvmw.address;
952 pte_t *pte = pvmw.pte;
954 if (!pte_dirty(*pte) && !pte_write(*pte))
957 flush_cache_page(vma, address, pte_pfn(*pte));
958 entry = ptep_clear_flush(vma, address, pte);
959 entry = pte_wrprotect(entry);
960 entry = pte_mkclean(entry);
961 set_pte_at(vma->vm_mm, address, pte, entry);
964 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
965 pmd_t *pmd = pvmw.pmd;
968 if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
971 flush_cache_page(vma, address, folio_pfn(folio));
972 entry = pmdp_invalidate(vma, address, pmd);
973 entry = pmd_wrprotect(entry);
974 entry = pmd_mkclean(entry);
975 set_pmd_at(vma->vm_mm, address, pmd, entry);
978 /* unexpected pmd-mapped folio? */
984 * No need to call mmu_notifier_invalidate_range() as we are
985 * downgrading page table protection not changing it to point
988 * See Documentation/vm/mmu_notifier.rst
994 mmu_notifier_invalidate_range_end(&range);
999 static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
1001 if (vma->vm_flags & VM_SHARED)
1007 int folio_mkclean(struct folio *folio)
1010 struct address_space *mapping;
1011 struct rmap_walk_control rwc = {
1012 .arg = (void *)&cleaned,
1013 .rmap_one = page_mkclean_one,
1014 .invalid_vma = invalid_mkclean_vma,
1017 BUG_ON(!folio_test_locked(folio));
1019 if (!folio_mapped(folio))
1022 mapping = folio_mapping(folio);
1026 rmap_walk(folio, &rwc);
1030 EXPORT_SYMBOL_GPL(folio_mkclean);
1033 * page_move_anon_rmap - move a page to our anon_vma
1034 * @page: the page to move to our anon_vma
1035 * @vma: the vma the page belongs to
1037 * When a page belongs exclusively to one process after a COW event,
1038 * that page can be moved into the anon_vma that belongs to just that
1039 * process, so the rmap code will not search the parent or sibling
1042 void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
1044 struct anon_vma *anon_vma = vma->anon_vma;
1046 page = compound_head(page);
1048 VM_BUG_ON_PAGE(!PageLocked(page), page);
1049 VM_BUG_ON_VMA(!anon_vma, vma);
1051 anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
1053 * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
1054 * simultaneously, so a concurrent reader (eg folio_referenced()'s
1055 * folio_test_anon()) will not see one without the other.
1057 WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
1061 * __page_set_anon_rmap - set up new anonymous rmap
1062 * @page: Page or Hugepage to add to rmap
1063 * @vma: VM area to add page to.
1064 * @address: User virtual address of the mapping
1065 * @exclusive: the page is exclusively owned by the current process
1067 static void __page_set_anon_rmap(struct page *page,
1068 struct vm_area_struct *vma, unsigned long address, int exclusive)
1070 struct anon_vma *anon_vma = vma->anon_vma;
1078 * If the page isn't exclusively mapped into this vma,
1079 * we must use the _oldest_ possible anon_vma for the
1083 anon_vma = anon_vma->root;
1086 * page_idle does a lockless/optimistic rmap scan on page->mapping.
1087 * Make sure the compiler doesn't split the stores of anon_vma and
1088 * the PAGE_MAPPING_ANON type identifier, otherwise the rmap code
1089 * could mistake the mapping for a struct address_space and crash.
1091 anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
1092 WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
1093 page->index = linear_page_index(vma, address);
1097 * __page_check_anon_rmap - sanity check anonymous rmap addition
1098 * @page: the page to add the mapping to
1099 * @vma: the vm area in which the mapping is added
1100 * @address: the user virtual address mapped
1102 static void __page_check_anon_rmap(struct page *page,
1103 struct vm_area_struct *vma, unsigned long address)
1105 struct folio *folio = page_folio(page);
1107 * The page's anon-rmap details (mapping and index) are guaranteed to
1108 * be set up correctly at this point.
1110 * We have exclusion against page_add_anon_rmap because the caller
1111 * always holds the page locked.
1113 * We have exclusion against page_add_new_anon_rmap because those pages
1114 * are initially only visible via the pagetables, and the pte is locked
1115 * over the call to page_add_new_anon_rmap.
1117 VM_BUG_ON_FOLIO(folio_anon_vma(folio)->root != vma->anon_vma->root,
1119 VM_BUG_ON_PAGE(page_to_pgoff(page) != linear_page_index(vma, address),
1124 * page_add_anon_rmap - add pte mapping to an anonymous page
1125 * @page: the page to add the mapping to
1126 * @vma: the vm area in which the mapping is added
1127 * @address: the user virtual address mapped
1128 * @compound: charge the page as compound or small page
1130 * The caller needs to hold the pte lock, and the page must be locked in
1131 * the anon_vma case: to serialize mapping,index checking after setting,
1132 * and to ensure that PageAnon is not being upgraded racily to PageKsm
1133 * (but PageKsm is never downgraded to PageAnon).
1135 void page_add_anon_rmap(struct page *page,
1136 struct vm_area_struct *vma, unsigned long address, bool compound)
1138 do_page_add_anon_rmap(page, vma, address, compound ? RMAP_COMPOUND : 0);
1142 * Special version of the above for do_swap_page, which often runs
1143 * into pages that are exclusively owned by the current process.
1144 * Everybody else should continue to use page_add_anon_rmap above.
1146 void do_page_add_anon_rmap(struct page *page,
1147 struct vm_area_struct *vma, unsigned long address, int flags)
1149 bool compound = flags & RMAP_COMPOUND;
1152 if (unlikely(PageKsm(page)))
1153 lock_page_memcg(page);
1155 VM_BUG_ON_PAGE(!PageLocked(page), page);
1159 VM_BUG_ON_PAGE(!PageLocked(page), page);
1160 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
1161 mapcount = compound_mapcount_ptr(page);
1162 first = atomic_inc_and_test(mapcount);
1164 first = atomic_inc_and_test(&page->_mapcount);
1168 int nr = compound ? thp_nr_pages(page) : 1;
1170 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1171 * these counters are not modified in interrupt context, and
1172 * pte lock(a spinlock) is held, which implies preemption
1176 __mod_lruvec_page_state(page, NR_ANON_THPS, nr);
1177 __mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
1180 if (unlikely(PageKsm(page)))
1181 unlock_page_memcg(page);
1183 /* address might be in next vma when migration races vma_adjust */
1185 __page_set_anon_rmap(page, vma, address,
1186 flags & RMAP_EXCLUSIVE);
1188 __page_check_anon_rmap(page, vma, address);
1190 mlock_vma_page(page, vma, compound);
1194 * page_add_new_anon_rmap - add pte mapping to a new anonymous page
1195 * @page: the page to add the mapping to
1196 * @vma: the vm area in which the mapping is added
1197 * @address: the user virtual address mapped
1198 * @compound: charge the page as compound or small page
1200 * Same as page_add_anon_rmap but must only be called on *new* pages.
1201 * This means the inc-and-test can be bypassed.
1202 * Page does not have to be locked.
1204 void page_add_new_anon_rmap(struct page *page,
1205 struct vm_area_struct *vma, unsigned long address, bool compound)
1207 int nr = compound ? thp_nr_pages(page) : 1;
1209 VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
1210 __SetPageSwapBacked(page);
1212 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
1213 /* increment count (starts at -1) */
1214 atomic_set(compound_mapcount_ptr(page), 0);
1215 atomic_set(compound_pincount_ptr(page), 0);
1217 __mod_lruvec_page_state(page, NR_ANON_THPS, nr);
1219 /* Anon THP always mapped first with PMD */
1220 VM_BUG_ON_PAGE(PageTransCompound(page), page);
1221 /* increment count (starts at -1) */
1222 atomic_set(&page->_mapcount, 0);
1224 __mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
1225 __page_set_anon_rmap(page, vma, address, 1);
1229 * page_add_file_rmap - add pte mapping to a file page
1230 * @page: the page to add the mapping to
1231 * @vma: the vm area in which the mapping is added
1232 * @compound: charge the page as compound or small page
1234 * The caller needs to hold the pte lock.
1236 void page_add_file_rmap(struct page *page,
1237 struct vm_area_struct *vma, bool compound)
1241 VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
1242 lock_page_memcg(page);
1243 if (compound && PageTransHuge(page)) {
1244 int nr_pages = thp_nr_pages(page);
1246 for (i = 0, nr = 0; i < nr_pages; i++) {
1247 if (atomic_inc_and_test(&page[i]._mapcount))
1250 if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
1252 if (PageSwapBacked(page))
1253 __mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1256 __mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1259 if (PageTransCompound(page) && page_mapping(page)) {
1260 VM_WARN_ON_ONCE(!PageLocked(page));
1261 SetPageDoubleMap(compound_head(page));
1263 if (!atomic_inc_and_test(&page->_mapcount))
1266 __mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
1268 unlock_page_memcg(page);
1270 mlock_vma_page(page, vma, compound);
1273 static void page_remove_file_rmap(struct page *page, bool compound)
1277 VM_BUG_ON_PAGE(compound && !PageHead(page), page);
1279 /* Hugepages are not counted in NR_FILE_MAPPED for now. */
1280 if (unlikely(PageHuge(page))) {
1281 /* hugetlb pages are always mapped with pmds */
1282 atomic_dec(compound_mapcount_ptr(page));
1286 /* page still mapped by someone else? */
1287 if (compound && PageTransHuge(page)) {
1288 int nr_pages = thp_nr_pages(page);
1290 for (i = 0, nr = 0; i < nr_pages; i++) {
1291 if (atomic_add_negative(-1, &page[i]._mapcount))
1294 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1296 if (PageSwapBacked(page))
1297 __mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1300 __mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1303 if (!atomic_add_negative(-1, &page->_mapcount))
1308 * We use the irq-unsafe __{inc|mod}_lruvec_page_state because
1309 * these counters are not modified in interrupt context, and
1310 * pte lock(a spinlock) is held, which implies preemption disabled.
1312 __mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
1315 static void page_remove_anon_compound_rmap(struct page *page)
1319 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1322 /* Hugepages are not counted in NR_ANON_PAGES for now. */
1323 if (unlikely(PageHuge(page)))
1326 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1329 __mod_lruvec_page_state(page, NR_ANON_THPS, -thp_nr_pages(page));
1331 if (TestClearPageDoubleMap(page)) {
1333 * Subpages can be mapped with PTEs too. Check how many of
1334 * them are still mapped.
1336 for (i = 0, nr = 0; i < thp_nr_pages(page); i++) {
1337 if (atomic_add_negative(-1, &page[i]._mapcount))
1342 * Queue the page for deferred split if at least one small
1343 * page of the compound page is unmapped, but at least one
1344 * small page is still mapped.
1346 if (nr && nr < thp_nr_pages(page))
1347 deferred_split_huge_page(page);
1349 nr = thp_nr_pages(page);
1353 __mod_lruvec_page_state(page, NR_ANON_MAPPED, -nr);
1357 * page_remove_rmap - take down pte mapping from a page
1358 * @page: page to remove mapping from
1359 * @vma: the vm area from which the mapping is removed
1360 * @compound: uncharge the page as compound or small page
1362 * The caller needs to hold the pte lock.
1364 void page_remove_rmap(struct page *page,
1365 struct vm_area_struct *vma, bool compound)
1367 lock_page_memcg(page);
1369 if (!PageAnon(page)) {
1370 page_remove_file_rmap(page, compound);
1375 page_remove_anon_compound_rmap(page);
1379 /* page still mapped by someone else? */
1380 if (!atomic_add_negative(-1, &page->_mapcount))
1384 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1385 * these counters are not modified in interrupt context, and
1386 * pte lock(a spinlock) is held, which implies preemption disabled.
1388 __dec_lruvec_page_state(page, NR_ANON_MAPPED);
1390 if (PageTransCompound(page))
1391 deferred_split_huge_page(compound_head(page));
1394 * It would be tidy to reset the PageAnon mapping here,
1395 * but that might overwrite a racing page_add_anon_rmap
1396 * which increments mapcount after us but sets mapping
1397 * before us: so leave the reset to free_unref_page,
1398 * and remember that it's only reliable while mapped.
1399 * Leaving it set also helps swapoff to reinstate ptes
1400 * faster for those pages still in swapcache.
1403 unlock_page_memcg(page);
1405 munlock_vma_page(page, vma, compound);
1409 * @arg: enum ttu_flags will be passed to this argument
1411 static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
1412 unsigned long address, void *arg)
1414 struct mm_struct *mm = vma->vm_mm;
1415 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
1417 struct page *subpage;
1419 struct mmu_notifier_range range;
1420 enum ttu_flags flags = (enum ttu_flags)(long)arg;
1423 * When racing against e.g. zap_pte_range() on another cpu,
1424 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
1425 * try_to_unmap() may return before page_mapped() has become false,
1426 * if page table locking is skipped: use TTU_SYNC to wait for that.
1428 if (flags & TTU_SYNC)
1429 pvmw.flags = PVMW_SYNC;
1431 if (flags & TTU_SPLIT_HUGE_PMD)
1432 split_huge_pmd_address(vma, address, false, folio);
1435 * For THP, we have to assume the worse case ie pmd for invalidation.
1436 * For hugetlb, it could be much worse if we need to do pud
1437 * invalidation in the case of pmd sharing.
1439 * Note that the folio can not be freed in this function as call of
1440 * try_to_unmap() must hold a reference on the folio.
1442 range.end = vma_address_end(&pvmw);
1443 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1444 address, range.end);
1445 if (folio_test_hugetlb(folio)) {
1447 * If sharing is possible, start and end will be adjusted
1450 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1453 mmu_notifier_invalidate_range_start(&range);
1455 while (page_vma_mapped_walk(&pvmw)) {
1456 /* Unexpected PMD-mapped THP? */
1457 VM_BUG_ON_FOLIO(!pvmw.pte, folio);
1460 * If the folio is in an mlock()d vma, we must not swap it out.
1462 if (!(flags & TTU_IGNORE_MLOCK) &&
1463 (vma->vm_flags & VM_LOCKED)) {
1464 /* Restore the mlock which got missed */
1465 mlock_vma_folio(folio, vma, false);
1466 page_vma_mapped_walk_done(&pvmw);
1471 subpage = folio_page(folio,
1472 pte_pfn(*pvmw.pte) - folio_pfn(folio));
1473 address = pvmw.address;
1475 if (folio_test_hugetlb(folio) && !folio_test_anon(folio)) {
1477 * To call huge_pmd_unshare, i_mmap_rwsem must be
1478 * held in write mode. Caller needs to explicitly
1479 * do this outside rmap routines.
1481 VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
1482 if (huge_pmd_unshare(mm, vma, &address, pvmw.pte)) {
1484 * huge_pmd_unshare unmapped an entire PMD
1485 * page. There is no way of knowing exactly
1486 * which PMDs may be cached for this mm, so
1487 * we must flush them all. start/end were
1488 * already adjusted above to cover this range.
1490 flush_cache_range(vma, range.start, range.end);
1491 flush_tlb_range(vma, range.start, range.end);
1492 mmu_notifier_invalidate_range(mm, range.start,
1496 * The ref count of the PMD page was dropped
1497 * which is part of the way map counting
1498 * is done for shared PMDs. Return 'true'
1499 * here. When there is no other sharing,
1500 * huge_pmd_unshare returns false and we will
1501 * unmap the actual page and drop map count
1504 page_vma_mapped_walk_done(&pvmw);
1509 /* Nuke the page table entry. */
1510 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
1511 if (should_defer_flush(mm, flags)) {
1513 * We clear the PTE but do not flush so potentially
1514 * a remote CPU could still be writing to the folio.
1515 * If the entry was previously clean then the
1516 * architecture must guarantee that a clear->dirty
1517 * transition on a cached TLB entry is written through
1518 * and traps if the PTE is unmapped.
1520 pteval = ptep_get_and_clear(mm, address, pvmw.pte);
1522 set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
1524 pteval = ptep_clear_flush(vma, address, pvmw.pte);
1527 /* Set the dirty flag on the folio now the pte is gone. */
1528 if (pte_dirty(pteval))
1529 folio_mark_dirty(folio);
1531 /* Update high watermark before we lower rss */
1532 update_hiwater_rss(mm);
1534 if (PageHWPoison(subpage) && !(flags & TTU_IGNORE_HWPOISON)) {
1535 pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
1536 if (folio_test_hugetlb(folio)) {
1537 hugetlb_count_sub(folio_nr_pages(folio), mm);
1538 set_huge_swap_pte_at(mm, address,
1540 vma_mmu_pagesize(vma));
1542 dec_mm_counter(mm, mm_counter(&folio->page));
1543 set_pte_at(mm, address, pvmw.pte, pteval);
1546 } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
1548 * The guest indicated that the page content is of no
1549 * interest anymore. Simply discard the pte, vmscan
1550 * will take care of the rest.
1551 * A future reference will then fault in a new zero
1552 * page. When userfaultfd is active, we must not drop
1553 * this page though, as its main user (postcopy
1554 * migration) will not expect userfaults on already
1557 dec_mm_counter(mm, mm_counter(&folio->page));
1558 /* We have to invalidate as we cleared the pte */
1559 mmu_notifier_invalidate_range(mm, address,
1560 address + PAGE_SIZE);
1561 } else if (folio_test_anon(folio)) {
1562 swp_entry_t entry = { .val = page_private(subpage) };
1565 * Store the swap location in the pte.
1566 * See handle_pte_fault() ...
1568 if (unlikely(folio_test_swapbacked(folio) !=
1569 folio_test_swapcache(folio))) {
1572 /* We have to invalidate as we cleared the pte */
1573 mmu_notifier_invalidate_range(mm, address,
1574 address + PAGE_SIZE);
1575 page_vma_mapped_walk_done(&pvmw);
1579 /* MADV_FREE page check */
1580 if (!folio_test_swapbacked(folio)) {
1581 if (!folio_test_dirty(folio)) {
1582 /* Invalidate as we cleared the pte */
1583 mmu_notifier_invalidate_range(mm,
1584 address, address + PAGE_SIZE);
1585 dec_mm_counter(mm, MM_ANONPAGES);
1590 * If the folio was redirtied, it cannot be
1591 * discarded. Remap the page to page table.
1593 set_pte_at(mm, address, pvmw.pte, pteval);
1594 folio_set_swapbacked(folio);
1596 page_vma_mapped_walk_done(&pvmw);
1600 if (swap_duplicate(entry) < 0) {
1601 set_pte_at(mm, address, pvmw.pte, pteval);
1603 page_vma_mapped_walk_done(&pvmw);
1606 if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1607 set_pte_at(mm, address, pvmw.pte, pteval);
1609 page_vma_mapped_walk_done(&pvmw);
1612 if (list_empty(&mm->mmlist)) {
1613 spin_lock(&mmlist_lock);
1614 if (list_empty(&mm->mmlist))
1615 list_add(&mm->mmlist, &init_mm.mmlist);
1616 spin_unlock(&mmlist_lock);
1618 dec_mm_counter(mm, MM_ANONPAGES);
1619 inc_mm_counter(mm, MM_SWAPENTS);
1620 swp_pte = swp_entry_to_pte(entry);
1621 if (pte_soft_dirty(pteval))
1622 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1623 if (pte_uffd_wp(pteval))
1624 swp_pte = pte_swp_mkuffd_wp(swp_pte);
1625 set_pte_at(mm, address, pvmw.pte, swp_pte);
1626 /* Invalidate as we cleared the pte */
1627 mmu_notifier_invalidate_range(mm, address,
1628 address + PAGE_SIZE);
1631 * This is a locked file-backed folio,
1632 * so it cannot be removed from the page
1633 * cache and replaced by a new folio before
1634 * mmu_notifier_invalidate_range_end, so no
1635 * concurrent thread might update its page table
1636 * to point at a new folio while a device is
1637 * still using this folio.
1639 * See Documentation/vm/mmu_notifier.rst
1641 dec_mm_counter(mm, mm_counter_file(&folio->page));
1645 * No need to call mmu_notifier_invalidate_range() it has be
1646 * done above for all cases requiring it to happen under page
1647 * table lock before mmu_notifier_invalidate_range_end()
1649 * See Documentation/vm/mmu_notifier.rst
1651 page_remove_rmap(subpage, vma, folio_test_hugetlb(folio));
1652 if (vma->vm_flags & VM_LOCKED)
1653 mlock_page_drain(smp_processor_id());
1657 mmu_notifier_invalidate_range_end(&range);
1662 static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
1664 return vma_is_temporary_stack(vma);
1667 static int page_not_mapped(struct folio *folio)
1669 return !folio_mapped(folio);
1673 * try_to_unmap - Try to remove all page table mappings to a folio.
1674 * @folio: The folio to unmap.
1675 * @flags: action and flags
1677 * Tries to remove all the page table entries which are mapping this
1678 * folio. It is the caller's responsibility to check if the folio is
1679 * still mapped if needed (use TTU_SYNC to prevent accounting races).
1681 * Context: Caller must hold the folio lock.
1683 void try_to_unmap(struct folio *folio, enum ttu_flags flags)
1685 struct rmap_walk_control rwc = {
1686 .rmap_one = try_to_unmap_one,
1687 .arg = (void *)flags,
1688 .done = page_not_mapped,
1689 .anon_lock = folio_lock_anon_vma_read,
1692 if (flags & TTU_RMAP_LOCKED)
1693 rmap_walk_locked(folio, &rwc);
1695 rmap_walk(folio, &rwc);
1699 * @arg: enum ttu_flags will be passed to this argument.
1701 * If TTU_SPLIT_HUGE_PMD is specified any PMD mappings will be split into PTEs
1702 * containing migration entries.
1704 static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,
1705 unsigned long address, void *arg)
1707 struct mm_struct *mm = vma->vm_mm;
1708 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
1710 struct page *subpage;
1712 struct mmu_notifier_range range;
1713 enum ttu_flags flags = (enum ttu_flags)(long)arg;
1716 * When racing against e.g. zap_pte_range() on another cpu,
1717 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
1718 * try_to_migrate() may return before page_mapped() has become false,
1719 * if page table locking is skipped: use TTU_SYNC to wait for that.
1721 if (flags & TTU_SYNC)
1722 pvmw.flags = PVMW_SYNC;
1725 * unmap_page() in mm/huge_memory.c is the only user of migration with
1726 * TTU_SPLIT_HUGE_PMD and it wants to freeze.
1728 if (flags & TTU_SPLIT_HUGE_PMD)
1729 split_huge_pmd_address(vma, address, true, folio);
1732 * For THP, we have to assume the worse case ie pmd for invalidation.
1733 * For hugetlb, it could be much worse if we need to do pud
1734 * invalidation in the case of pmd sharing.
1736 * Note that the page can not be free in this function as call of
1737 * try_to_unmap() must hold a reference on the page.
1739 range.end = vma_address_end(&pvmw);
1740 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1741 address, range.end);
1742 if (folio_test_hugetlb(folio)) {
1744 * If sharing is possible, start and end will be adjusted
1747 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1750 mmu_notifier_invalidate_range_start(&range);
1752 while (page_vma_mapped_walk(&pvmw)) {
1753 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1754 /* PMD-mapped THP migration entry */
1756 subpage = folio_page(folio,
1757 pmd_pfn(*pvmw.pmd) - folio_pfn(folio));
1758 VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
1759 !folio_test_pmd_mappable(folio), folio);
1761 set_pmd_migration_entry(&pvmw, subpage);
1766 /* Unexpected PMD-mapped THP? */
1767 VM_BUG_ON_FOLIO(!pvmw.pte, folio);
1769 subpage = folio_page(folio,
1770 pte_pfn(*pvmw.pte) - folio_pfn(folio));
1771 address = pvmw.address;
1773 if (folio_test_hugetlb(folio) && !folio_test_anon(folio)) {
1775 * To call huge_pmd_unshare, i_mmap_rwsem must be
1776 * held in write mode. Caller needs to explicitly
1777 * do this outside rmap routines.
1779 VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
1780 if (huge_pmd_unshare(mm, vma, &address, pvmw.pte)) {
1782 * huge_pmd_unshare unmapped an entire PMD
1783 * page. There is no way of knowing exactly
1784 * which PMDs may be cached for this mm, so
1785 * we must flush them all. start/end were
1786 * already adjusted above to cover this range.
1788 flush_cache_range(vma, range.start, range.end);
1789 flush_tlb_range(vma, range.start, range.end);
1790 mmu_notifier_invalidate_range(mm, range.start,
1794 * The ref count of the PMD page was dropped
1795 * which is part of the way map counting
1796 * is done for shared PMDs. Return 'true'
1797 * here. When there is no other sharing,
1798 * huge_pmd_unshare returns false and we will
1799 * unmap the actual page and drop map count
1802 page_vma_mapped_walk_done(&pvmw);
1807 /* Nuke the page table entry. */
1808 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
1809 pteval = ptep_clear_flush(vma, address, pvmw.pte);
1811 /* Set the dirty flag on the folio now the pte is gone. */
1812 if (pte_dirty(pteval))
1813 folio_mark_dirty(folio);
1815 /* Update high watermark before we lower rss */
1816 update_hiwater_rss(mm);
1818 if (folio_is_zone_device(folio)) {
1819 unsigned long pfn = folio_pfn(folio);
1824 * Store the pfn of the page in a special migration
1825 * pte. do_swap_page() will wait until the migration
1826 * pte is removed and then restart fault handling.
1828 entry = pte_to_swp_entry(pteval);
1829 if (is_writable_device_private_entry(entry))
1830 entry = make_writable_migration_entry(pfn);
1832 entry = make_readable_migration_entry(pfn);
1833 swp_pte = swp_entry_to_pte(entry);
1836 * pteval maps a zone device page and is therefore
1839 if (pte_swp_soft_dirty(pteval))
1840 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1841 if (pte_swp_uffd_wp(pteval))
1842 swp_pte = pte_swp_mkuffd_wp(swp_pte);
1843 set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
1845 * No need to invalidate here it will synchronize on
1846 * against the special swap migration pte.
1848 * The assignment to subpage above was computed from a
1849 * swap PTE which results in an invalid pointer.
1850 * Since only PAGE_SIZE pages can currently be
1851 * migrated, just set it to page. This will need to be
1852 * changed when hugepage migrations to device private
1853 * memory are supported.
1855 subpage = &folio->page;
1856 } else if (PageHWPoison(subpage)) {
1857 pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
1858 if (folio_test_hugetlb(folio)) {
1859 hugetlb_count_sub(folio_nr_pages(folio), mm);
1860 set_huge_swap_pte_at(mm, address,
1862 vma_mmu_pagesize(vma));
1864 dec_mm_counter(mm, mm_counter(&folio->page));
1865 set_pte_at(mm, address, pvmw.pte, pteval);
1868 } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
1870 * The guest indicated that the page content is of no
1871 * interest anymore. Simply discard the pte, vmscan
1872 * will take care of the rest.
1873 * A future reference will then fault in a new zero
1874 * page. When userfaultfd is active, we must not drop
1875 * this page though, as its main user (postcopy
1876 * migration) will not expect userfaults on already
1879 dec_mm_counter(mm, mm_counter(&folio->page));
1880 /* We have to invalidate as we cleared the pte */
1881 mmu_notifier_invalidate_range(mm, address,
1882 address + PAGE_SIZE);
1887 if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1888 set_pte_at(mm, address, pvmw.pte, pteval);
1890 page_vma_mapped_walk_done(&pvmw);
1895 * Store the pfn of the page in a special migration
1896 * pte. do_swap_page() will wait until the migration
1897 * pte is removed and then restart fault handling.
1899 if (pte_write(pteval))
1900 entry = make_writable_migration_entry(
1901 page_to_pfn(subpage));
1903 entry = make_readable_migration_entry(
1904 page_to_pfn(subpage));
1906 swp_pte = swp_entry_to_pte(entry);
1907 if (pte_soft_dirty(pteval))
1908 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1909 if (pte_uffd_wp(pteval))
1910 swp_pte = pte_swp_mkuffd_wp(swp_pte);
1911 set_pte_at(mm, address, pvmw.pte, swp_pte);
1913 * No need to invalidate here it will synchronize on
1914 * against the special swap migration pte.
1919 * No need to call mmu_notifier_invalidate_range() it has be
1920 * done above for all cases requiring it to happen under page
1921 * table lock before mmu_notifier_invalidate_range_end()
1923 * See Documentation/vm/mmu_notifier.rst
1925 page_remove_rmap(subpage, vma, folio_test_hugetlb(folio));
1926 if (vma->vm_flags & VM_LOCKED)
1927 mlock_page_drain(smp_processor_id());
1931 mmu_notifier_invalidate_range_end(&range);
1937 * try_to_migrate - try to replace all page table mappings with swap entries
1938 * @folio: the folio to replace page table entries for
1939 * @flags: action and flags
1941 * Tries to remove all the page table entries which are mapping this folio and
1942 * replace them with special swap entries. Caller must hold the folio lock.
1944 void try_to_migrate(struct folio *folio, enum ttu_flags flags)
1946 struct rmap_walk_control rwc = {
1947 .rmap_one = try_to_migrate_one,
1948 .arg = (void *)flags,
1949 .done = page_not_mapped,
1950 .anon_lock = folio_lock_anon_vma_read,
1954 * Migration always ignores mlock and only supports TTU_RMAP_LOCKED and
1955 * TTU_SPLIT_HUGE_PMD and TTU_SYNC flags.
1957 if (WARN_ON_ONCE(flags & ~(TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
1961 if (folio_is_zone_device(folio) && !folio_is_device_private(folio))
1965 * During exec, a temporary VMA is setup and later moved.
1966 * The VMA is moved under the anon_vma lock but not the
1967 * page tables leading to a race where migration cannot
1968 * find the migration ptes. Rather than increasing the
1969 * locking requirements of exec(), migration skips
1970 * temporary VMAs until after exec() completes.
1972 if (!folio_test_ksm(folio) && folio_test_anon(folio))
1973 rwc.invalid_vma = invalid_migration_vma;
1975 if (flags & TTU_RMAP_LOCKED)
1976 rmap_walk_locked(folio, &rwc);
1978 rmap_walk(folio, &rwc);
1981 #ifdef CONFIG_DEVICE_PRIVATE
1982 struct make_exclusive_args {
1983 struct mm_struct *mm;
1984 unsigned long address;
1989 static bool page_make_device_exclusive_one(struct folio *folio,
1990 struct vm_area_struct *vma, unsigned long address, void *priv)
1992 struct mm_struct *mm = vma->vm_mm;
1993 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
1994 struct make_exclusive_args *args = priv;
1996 struct page *subpage;
1998 struct mmu_notifier_range range;
2002 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma,
2003 vma->vm_mm, address, min(vma->vm_end,
2004 address + folio_size(folio)),
2006 mmu_notifier_invalidate_range_start(&range);
2008 while (page_vma_mapped_walk(&pvmw)) {
2009 /* Unexpected PMD-mapped THP? */
2010 VM_BUG_ON_FOLIO(!pvmw.pte, folio);
2012 if (!pte_present(*pvmw.pte)) {
2014 page_vma_mapped_walk_done(&pvmw);
2018 subpage = folio_page(folio,
2019 pte_pfn(*pvmw.pte) - folio_pfn(folio));
2020 address = pvmw.address;
2022 /* Nuke the page table entry. */
2023 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
2024 pteval = ptep_clear_flush(vma, address, pvmw.pte);
2026 /* Set the dirty flag on the folio now the pte is gone. */
2027 if (pte_dirty(pteval))
2028 folio_mark_dirty(folio);
2031 * Check that our target page is still mapped at the expected
2034 if (args->mm == mm && args->address == address &&
2039 * Store the pfn of the page in a special migration
2040 * pte. do_swap_page() will wait until the migration
2041 * pte is removed and then restart fault handling.
2043 if (pte_write(pteval))
2044 entry = make_writable_device_exclusive_entry(
2045 page_to_pfn(subpage));
2047 entry = make_readable_device_exclusive_entry(
2048 page_to_pfn(subpage));
2049 swp_pte = swp_entry_to_pte(entry);
2050 if (pte_soft_dirty(pteval))
2051 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2052 if (pte_uffd_wp(pteval))
2053 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2055 set_pte_at(mm, address, pvmw.pte, swp_pte);
2058 * There is a reference on the page for the swap entry which has
2059 * been removed, so shouldn't take another.
2061 page_remove_rmap(subpage, vma, false);
2064 mmu_notifier_invalidate_range_end(&range);
2070 * folio_make_device_exclusive - Mark the folio exclusively owned by a device.
2071 * @folio: The folio to replace page table entries for.
2072 * @mm: The mm_struct where the folio is expected to be mapped.
2073 * @address: Address where the folio is expected to be mapped.
2074 * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier callbacks
2076 * Tries to remove all the page table entries which are mapping this
2077 * folio and replace them with special device exclusive swap entries to
2078 * grant a device exclusive access to the folio.
2080 * Context: Caller must hold the folio lock.
2081 * Return: false if the page is still mapped, or if it could not be unmapped
2082 * from the expected address. Otherwise returns true (success).
2084 static bool folio_make_device_exclusive(struct folio *folio,
2085 struct mm_struct *mm, unsigned long address, void *owner)
2087 struct make_exclusive_args args = {
2093 struct rmap_walk_control rwc = {
2094 .rmap_one = page_make_device_exclusive_one,
2095 .done = page_not_mapped,
2096 .anon_lock = folio_lock_anon_vma_read,
2101 * Restrict to anonymous folios for now to avoid potential writeback
2104 if (!folio_test_anon(folio))
2107 rmap_walk(folio, &rwc);
2109 return args.valid && !folio_mapcount(folio);
2113 * make_device_exclusive_range() - Mark a range for exclusive use by a device
2114 * @mm: mm_struct of assoicated target process
2115 * @start: start of the region to mark for exclusive device access
2116 * @end: end address of region
2117 * @pages: returns the pages which were successfully marked for exclusive access
2118 * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
2120 * Returns: number of pages found in the range by GUP. A page is marked for
2121 * exclusive access only if the page pointer is non-NULL.
2123 * This function finds ptes mapping page(s) to the given address range, locks
2124 * them and replaces mappings with special swap entries preventing userspace CPU
2125 * access. On fault these entries are replaced with the original mapping after
2126 * calling MMU notifiers.
2128 * A driver using this to program access from a device must use a mmu notifier
2129 * critical section to hold a device specific lock during programming. Once
2130 * programming is complete it should drop the page lock and reference after
2131 * which point CPU access to the page will revoke the exclusive access.
2133 int make_device_exclusive_range(struct mm_struct *mm, unsigned long start,
2134 unsigned long end, struct page **pages,
2137 long npages = (end - start) >> PAGE_SHIFT;
2140 npages = get_user_pages_remote(mm, start, npages,
2141 FOLL_GET | FOLL_WRITE | FOLL_SPLIT_PMD,
2146 for (i = 0; i < npages; i++, start += PAGE_SIZE) {
2147 struct folio *folio = page_folio(pages[i]);
2148 if (PageTail(pages[i]) || !folio_trylock(folio)) {
2154 if (!folio_make_device_exclusive(folio, mm, start, owner)) {
2155 folio_unlock(folio);
2163 EXPORT_SYMBOL_GPL(make_device_exclusive_range);
2166 void __put_anon_vma(struct anon_vma *anon_vma)
2168 struct anon_vma *root = anon_vma->root;
2170 anon_vma_free(anon_vma);
2171 if (root != anon_vma && atomic_dec_and_test(&root->refcount))
2172 anon_vma_free(root);
2175 static struct anon_vma *rmap_walk_anon_lock(struct folio *folio,
2176 const struct rmap_walk_control *rwc)
2178 struct anon_vma *anon_vma;
2181 return rwc->anon_lock(folio);
2184 * Note: remove_migration_ptes() cannot use folio_lock_anon_vma_read()
2185 * because that depends on page_mapped(); but not all its usages
2186 * are holding mmap_lock. Users without mmap_lock are required to
2187 * take a reference count to prevent the anon_vma disappearing
2189 anon_vma = folio_anon_vma(folio);
2193 anon_vma_lock_read(anon_vma);
2198 * rmap_walk_anon - do something to anonymous page using the object-based
2200 * @page: the page to be handled
2201 * @rwc: control variable according to each walk type
2203 * Find all the mappings of a page using the mapping pointer and the vma chains
2204 * contained in the anon_vma struct it points to.
2206 static void rmap_walk_anon(struct folio *folio,
2207 const struct rmap_walk_control *rwc, bool locked)
2209 struct anon_vma *anon_vma;
2210 pgoff_t pgoff_start, pgoff_end;
2211 struct anon_vma_chain *avc;
2214 anon_vma = folio_anon_vma(folio);
2215 /* anon_vma disappear under us? */
2216 VM_BUG_ON_FOLIO(!anon_vma, folio);
2218 anon_vma = rmap_walk_anon_lock(folio, rwc);
2223 pgoff_start = folio_pgoff(folio);
2224 pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
2225 anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
2226 pgoff_start, pgoff_end) {
2227 struct vm_area_struct *vma = avc->vma;
2228 unsigned long address = vma_address(&folio->page, vma);
2230 VM_BUG_ON_VMA(address == -EFAULT, vma);
2233 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2236 if (!rwc->rmap_one(folio, vma, address, rwc->arg))
2238 if (rwc->done && rwc->done(folio))
2243 anon_vma_unlock_read(anon_vma);
2247 * rmap_walk_file - do something to file page using the object-based rmap method
2248 * @page: the page to be handled
2249 * @rwc: control variable according to each walk type
2251 * Find all the mappings of a page using the mapping pointer and the vma chains
2252 * contained in the address_space struct it points to.
2254 static void rmap_walk_file(struct folio *folio,
2255 const struct rmap_walk_control *rwc, bool locked)
2257 struct address_space *mapping = folio_mapping(folio);
2258 pgoff_t pgoff_start, pgoff_end;
2259 struct vm_area_struct *vma;
2262 * The page lock not only makes sure that page->mapping cannot
2263 * suddenly be NULLified by truncation, it makes sure that the
2264 * structure at mapping cannot be freed and reused yet,
2265 * so we can safely take mapping->i_mmap_rwsem.
2267 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
2272 pgoff_start = folio_pgoff(folio);
2273 pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
2275 i_mmap_lock_read(mapping);
2276 vma_interval_tree_foreach(vma, &mapping->i_mmap,
2277 pgoff_start, pgoff_end) {
2278 unsigned long address = vma_address(&folio->page, vma);
2280 VM_BUG_ON_VMA(address == -EFAULT, vma);
2283 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2286 if (!rwc->rmap_one(folio, vma, address, rwc->arg))
2288 if (rwc->done && rwc->done(folio))
2294 i_mmap_unlock_read(mapping);
2297 void rmap_walk(struct folio *folio, const struct rmap_walk_control *rwc)
2299 if (unlikely(folio_test_ksm(folio)))
2300 rmap_walk_ksm(folio, rwc);
2301 else if (folio_test_anon(folio))
2302 rmap_walk_anon(folio, rwc, false);
2304 rmap_walk_file(folio, rwc, false);
2307 /* Like rmap_walk, but caller holds relevant rmap lock */
2308 void rmap_walk_locked(struct folio *folio, const struct rmap_walk_control *rwc)
2310 /* no ksm support for now */
2311 VM_BUG_ON_FOLIO(folio_test_ksm(folio), folio);
2312 if (folio_test_anon(folio))
2313 rmap_walk_anon(folio, rwc, true);
2315 rmap_walk_file(folio, rwc, true);
2318 #ifdef CONFIG_HUGETLB_PAGE
2320 * The following two functions are for anonymous (private mapped) hugepages.
2321 * Unlike common anonymous pages, anonymous hugepages have no accounting code
2322 * and no lru code, because we handle hugepages differently from common pages.
2324 void hugepage_add_anon_rmap(struct page *page,
2325 struct vm_area_struct *vma, unsigned long address)
2327 struct anon_vma *anon_vma = vma->anon_vma;
2330 BUG_ON(!PageLocked(page));
2332 /* address might be in next vma when migration races vma_adjust */
2333 first = atomic_inc_and_test(compound_mapcount_ptr(page));
2335 __page_set_anon_rmap(page, vma, address, 0);
2338 void hugepage_add_new_anon_rmap(struct page *page,
2339 struct vm_area_struct *vma, unsigned long address)
2341 BUG_ON(address < vma->vm_start || address >= vma->vm_end);
2342 atomic_set(compound_mapcount_ptr(page), 0);
2343 atomic_set(compound_pincount_ptr(page), 0);
2345 __page_set_anon_rmap(page, vma, address, 1);
2347 #endif /* CONFIG_HUGETLB_PAGE */