File Index
Files and directories
Sign in
FILE

rmap.c

File preview with syntax highlighting.

linux-6.19.14/mm/rmap.c C
   1/*
   2 * mm/rmap.c - physical to virtual reverse mappings
   3 *
   4 * Copyright 2001, Rik van Riel <riel@conectiva.com.br>
   5 * Released under the General Public License (GPL).
   6 *
   7 * Simple, low overhead reverse mapping scheme.
   8 * Please try to keep this thing as modular as possible.
   9 *
  10 * Provides methods for unmapping each kind of mapped page:
  11 * the anon methods track anonymous pages, and
  12 * the file methods track pages belonging to an inode.
  13 *
  14 * Original design by Rik van Riel <riel@conectiva.com.br> 2001
  15 * File methods by Dave McCracken <dmccr@us.ibm.com> 2003, 2004
  16 * Anonymous methods by Andrea Arcangeli <andrea@suse.de> 2004
  17 * Contributions by Hugh Dickins 2003, 2004
  18 */
  19
  20/*
  21 * Lock ordering in mm:
  22 *
  23 * inode->i_rwsem	(while writing or truncating, not reading or faulting)
  24 *   mm->mmap_lock
  25 *     mapping->invalidate_lock (in filemap_fault)
  26 *       folio_lock
  27 *         hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share, see hugetlbfs below)
  28 *           vma_start_write
  29 *             mapping->i_mmap_rwsem
  30 *               anon_vma->rwsem
  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 block_dirty_folio)
  35 *                         i_pages lock (widely used)
  36 *                           lruvec->lru_lock (in folio_lruvec_lock_irq)
  37 *                     inode->i_lock (in set_page_dirty's __mark_inode_dirty)
  38 *                     bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
  39 *                       sb_lock (within inode_lock in fs/fs-writeback.c)
  40 *                       i_pages lock (widely used, in set_page_dirty,
  41 *                                 in arch-dependent flush_dcache_mmap_lock,
  42 *                                 within bdi.wb->list_lock in __sync_single_inode)
  43 *
  44 * anon_vma->rwsem,mapping->i_mmap_rwsem   (memory_failure, collect_procs_anon)
  45 *   ->tasklist_lock
  46 *     pte map lock
  47 *
  48 * hugetlbfs PageHuge() take locks in this order:
  49 *   hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
  50 *     vma_lock (hugetlb specific lock for pmd_sharing)
  51 *       mapping->i_mmap_rwsem (also used for hugetlb pmd sharing)
  52 *         folio_lock
  53 */
  54
  55#include <linux/mm.h>
  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/leafops.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>
  76#include <linux/mm_inline.h>
  77#include <linux/oom.h>
  78
  79#include <asm/tlb.h>
  80
  81#define CREATE_TRACE_POINTS
  82#include <trace/events/migrate.h>
  83
  84#include "internal.h"
  85
  86static struct kmem_cache *anon_vma_cachep;
  87static struct kmem_cache *anon_vma_chain_cachep;
  88
  89static inline struct anon_vma *anon_vma_alloc(void)
  90{
  91	struct anon_vma *anon_vma;
  92
  93	anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
  94	if (anon_vma) {
  95		atomic_set(&anon_vma->refcount, 1);
  96		anon_vma->num_children = 0;
  97		anon_vma->num_active_vmas = 0;
  98		anon_vma->parent = anon_vma;
  99		/*
 100		 * Initialise the anon_vma root to point to itself. If called
 101		 * from fork, the root will be reset to the parents anon_vma.
 102		 */
 103		anon_vma->root = anon_vma;
 104	}
 105
 106	return anon_vma;
 107}
 108
 109static inline void anon_vma_free(struct anon_vma *anon_vma)
 110{
 111	VM_BUG_ON(atomic_read(&anon_vma->refcount));
 112
 113	/*
 114	 * Synchronize against folio_lock_anon_vma_read() such that
 115	 * we can safely hold the lock without the anon_vma getting
 116	 * freed.
 117	 *
 118	 * Relies on the full mb implied by the atomic_dec_and_test() from
 119	 * put_anon_vma() against the acquire barrier implied by
 120	 * down_read_trylock() from folio_lock_anon_vma_read(). This orders:
 121	 *
 122	 * folio_lock_anon_vma_read()	VS	put_anon_vma()
 123	 *   down_read_trylock()		  atomic_dec_and_test()
 124	 *   LOCK				  MB
 125	 *   atomic_read()			  rwsem_is_locked()
 126	 *
 127	 * LOCK should suffice since the actual taking of the lock must
 128	 * happen _before_ what follows.
 129	 */
 130	might_sleep();
 131	if (rwsem_is_locked(&anon_vma->root->rwsem)) {
 132		anon_vma_lock_write(anon_vma);
 133		anon_vma_unlock_write(anon_vma);
 134	}
 135
 136	kmem_cache_free(anon_vma_cachep, anon_vma);
 137}
 138
 139static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
 140{
 141	return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
 142}
 143
 144static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
 145{
 146	kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
 147}
 148
 149static void anon_vma_chain_link(struct vm_area_struct *vma,
 150				struct anon_vma_chain *avc,
 151				struct anon_vma *anon_vma)
 152{
 153	avc->vma = vma;
 154	avc->anon_vma = anon_vma;
 155	list_add(&avc->same_vma, &vma->anon_vma_chain);
 156	anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
 157}
 158
 159/**
 160 * __anon_vma_prepare - attach an anon_vma to a memory region
 161 * @vma: the memory region in question
 162 *
 163 * This makes sure the memory mapping described by 'vma' has
 164 * an 'anon_vma' attached to it, so that we can associate the
 165 * anonymous pages mapped into it with that anon_vma.
 166 *
 167 * The common case will be that we already have one, which
 168 * is handled inline by anon_vma_prepare(). But if
 169 * not we either need to find an adjacent mapping that we
 170 * can re-use the anon_vma from (very common when the only
 171 * reason for splitting a vma has been mprotect()), or we
 172 * allocate a new one.
 173 *
 174 * Anon-vma allocations are very subtle, because we may have
 175 * optimistically looked up an anon_vma in folio_lock_anon_vma_read()
 176 * and that may actually touch the rwsem even in the newly
 177 * allocated vma (it depends on RCU to make sure that the
 178 * anon_vma isn't actually destroyed).
 179 *
 180 * As a result, we need to do proper anon_vma locking even
 181 * for the new allocation. At the same time, we do not want
 182 * to do any locking for the common case of already having
 183 * an anon_vma.
 184 */
 185int __anon_vma_prepare(struct vm_area_struct *vma)
 186{
 187	struct mm_struct *mm = vma->vm_mm;
 188	struct anon_vma *anon_vma, *allocated;
 189	struct anon_vma_chain *avc;
 190
 191	mmap_assert_locked(mm);
 192	might_sleep();
 193
 194	avc = anon_vma_chain_alloc(GFP_KERNEL);
 195	if (!avc)
 196		goto out_enomem;
 197
 198	anon_vma = find_mergeable_anon_vma(vma);
 199	allocated = NULL;
 200	if (!anon_vma) {
 201		anon_vma = anon_vma_alloc();
 202		if (unlikely(!anon_vma))
 203			goto out_enomem_free_avc;
 204		anon_vma->num_children++; /* self-parent link for new root */
 205		allocated = anon_vma;
 206	}
 207
 208	anon_vma_lock_write(anon_vma);
 209	/* page_table_lock to protect against threads */
 210	spin_lock(&mm->page_table_lock);
 211	if (likely(!vma->anon_vma)) {
 212		vma->anon_vma = anon_vma;
 213		anon_vma_chain_link(vma, avc, anon_vma);
 214		anon_vma->num_active_vmas++;
 215		allocated = NULL;
 216		avc = NULL;
 217	}
 218	spin_unlock(&mm->page_table_lock);
 219	anon_vma_unlock_write(anon_vma);
 220
 221	if (unlikely(allocated))
 222		put_anon_vma(allocated);
 223	if (unlikely(avc))
 224		anon_vma_chain_free(avc);
 225
 226	return 0;
 227
 228 out_enomem_free_avc:
 229	anon_vma_chain_free(avc);
 230 out_enomem:
 231	return -ENOMEM;
 232}
 233
 234/*
 235 * This is a useful helper function for locking the anon_vma root as
 236 * we traverse the vma->anon_vma_chain, looping over anon_vma's that
 237 * have the same vma.
 238 *
 239 * Such anon_vma's should have the same root, so you'd expect to see
 240 * just a single mutex_lock for the whole traversal.
 241 */
 242static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
 243{
 244	struct anon_vma *new_root = anon_vma->root;
 245	if (new_root != root) {
 246		if (WARN_ON_ONCE(root))
 247			up_write(&root->rwsem);
 248		root = new_root;
 249		down_write(&root->rwsem);
 250	}
 251	return root;
 252}
 253
 254static inline void unlock_anon_vma_root(struct anon_vma *root)
 255{
 256	if (root)
 257		up_write(&root->rwsem);
 258}
 259
 260/*
 261 * Attach the anon_vmas from src to dst.
 262 * Returns 0 on success, -ENOMEM on failure.
 263 *
 264 * anon_vma_clone() is called by vma_expand(), vma_merge(), __split_vma(),
 265 * copy_vma() and anon_vma_fork(). The first four want an exact copy of src,
 266 * while the last one, anon_vma_fork(), may try to reuse an existing anon_vma to
 267 * prevent endless growth of anon_vma. Since dst->anon_vma is set to NULL before
 268 * call, we can identify this case by checking (!dst->anon_vma &&
 269 * src->anon_vma).
 270 *
 271 * If (!dst->anon_vma && src->anon_vma) is true, this function tries to find
 272 * and reuse existing anon_vma which has no vmas and only one child anon_vma.
 273 * This prevents degradation of anon_vma hierarchy to endless linear chain in
 274 * case of constantly forking task. On the other hand, an anon_vma with more
 275 * than one child isn't reused even if there was no alive vma, thus rmap
 276 * walker has a good chance of avoiding scanning the whole hierarchy when it
 277 * searches where page is mapped.
 278 */
 279int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
 280{
 281	struct anon_vma_chain *avc, *pavc;
 282	struct anon_vma *root = NULL;
 283
 284	list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
 285		struct anon_vma *anon_vma;
 286
 287		avc = anon_vma_chain_alloc(GFP_NOWAIT);
 288		if (unlikely(!avc)) {
 289			unlock_anon_vma_root(root);
 290			root = NULL;
 291			avc = anon_vma_chain_alloc(GFP_KERNEL);
 292			if (!avc)
 293				goto enomem_failure;
 294		}
 295		anon_vma = pavc->anon_vma;
 296		root = lock_anon_vma_root(root, anon_vma);
 297		anon_vma_chain_link(dst, avc, anon_vma);
 298
 299		/*
 300		 * Reuse existing anon_vma if it has no vma and only one
 301		 * anon_vma child.
 302		 *
 303		 * Root anon_vma is never reused:
 304		 * it has self-parent reference and at least one child.
 305		 */
 306		if (!dst->anon_vma && src->anon_vma &&
 307		    anon_vma->num_children < 2 &&
 308		    anon_vma->num_active_vmas == 0)
 309			dst->anon_vma = anon_vma;
 310	}
 311	if (dst->anon_vma)
 312		dst->anon_vma->num_active_vmas++;
 313	unlock_anon_vma_root(root);
 314	return 0;
 315
 316 enomem_failure:
 317	/*
 318	 * dst->anon_vma is dropped here otherwise its num_active_vmas can
 319	 * be incorrectly decremented in unlink_anon_vmas().
 320	 * We can safely do this because callers of anon_vma_clone() don't care
 321	 * about dst->anon_vma if anon_vma_clone() failed.
 322	 */
 323	dst->anon_vma = NULL;
 324	unlink_anon_vmas(dst);
 325	return -ENOMEM;
 326}
 327
 328/*
 329 * Attach vma to its own anon_vma, as well as to the anon_vmas that
 330 * the corresponding VMA in the parent process is attached to.
 331 * Returns 0 on success, non-zero on failure.
 332 */
 333int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
 334{
 335	struct anon_vma_chain *avc;
 336	struct anon_vma *anon_vma;
 337	int error;
 338
 339	/* Don't bother if the parent process has no anon_vma here. */
 340	if (!pvma->anon_vma)
 341		return 0;
 342
 343	/* Drop inherited anon_vma, we'll reuse existing or allocate new. */
 344	vma->anon_vma = NULL;
 345
 346	/*
 347	 * First, attach the new VMA to the parent VMA's anon_vmas,
 348	 * so rmap can find non-COWed pages in child processes.
 349	 */
 350	error = anon_vma_clone(vma, pvma);
 351	if (error)
 352		return error;
 353
 354	/* An existing anon_vma has been reused, all done then. */
 355	if (vma->anon_vma)
 356		return 0;
 357
 358	/* Then add our own anon_vma. */
 359	anon_vma = anon_vma_alloc();
 360	if (!anon_vma)
 361		goto out_error;
 362	anon_vma->num_active_vmas++;
 363	avc = anon_vma_chain_alloc(GFP_KERNEL);
 364	if (!avc)
 365		goto out_error_free_anon_vma;
 366
 367	/*
 368	 * The root anon_vma's rwsem is the lock actually used when we
 369	 * lock any of the anon_vmas in this anon_vma tree.
 370	 */
 371	anon_vma->root = pvma->anon_vma->root;
 372	anon_vma->parent = pvma->anon_vma;
 373	/*
 374	 * With refcounts, an anon_vma can stay around longer than the
 375	 * process it belongs to. The root anon_vma needs to be pinned until
 376	 * this anon_vma is freed, because the lock lives in the root.
 377	 */
 378	get_anon_vma(anon_vma->root);
 379	/* Mark this anon_vma as the one where our new (COWed) pages go. */
 380	vma->anon_vma = anon_vma;
 381	anon_vma_lock_write(anon_vma);
 382	anon_vma_chain_link(vma, avc, anon_vma);
 383	anon_vma->parent->num_children++;
 384	anon_vma_unlock_write(anon_vma);
 385
 386	return 0;
 387
 388 out_error_free_anon_vma:
 389	put_anon_vma(anon_vma);
 390 out_error:
 391	unlink_anon_vmas(vma);
 392	return -ENOMEM;
 393}
 394
 395void unlink_anon_vmas(struct vm_area_struct *vma)
 396{
 397	struct anon_vma_chain *avc, *next;
 398	struct anon_vma *root = NULL;
 399
 400	/*
 401	 * Unlink each anon_vma chained to the VMA.  This list is ordered
 402	 * from newest to oldest, ensuring the root anon_vma gets freed last.
 403	 */
 404	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
 405		struct anon_vma *anon_vma = avc->anon_vma;
 406
 407		root = lock_anon_vma_root(root, anon_vma);
 408		anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
 409
 410		/*
 411		 * Leave empty anon_vmas on the list - we'll need
 412		 * to free them outside the lock.
 413		 */
 414		if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
 415			anon_vma->parent->num_children--;
 416			continue;
 417		}
 418
 419		list_del(&avc->same_vma);
 420		anon_vma_chain_free(avc);
 421	}
 422	if (vma->anon_vma) {
 423		vma->anon_vma->num_active_vmas--;
 424
 425		/*
 426		 * vma would still be needed after unlink, and anon_vma will be prepared
 427		 * when handle fault.
 428		 */
 429		vma->anon_vma = NULL;
 430	}
 431	unlock_anon_vma_root(root);
 432
 433	/*
 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.
 437	 */
 438	list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
 439		struct anon_vma *anon_vma = avc->anon_vma;
 440
 441		VM_WARN_ON(anon_vma->num_children);
 442		VM_WARN_ON(anon_vma->num_active_vmas);
 443		put_anon_vma(anon_vma);
 444
 445		list_del(&avc->same_vma);
 446		anon_vma_chain_free(avc);
 447	}
 448}
 449
 450static void anon_vma_ctor(void *data)
 451{
 452	struct anon_vma *anon_vma = data;
 453
 454	init_rwsem(&anon_vma->rwsem);
 455	atomic_set(&anon_vma->refcount, 0);
 456	anon_vma->rb_root = RB_ROOT_CACHED;
 457}
 458
 459void __init anon_vma_init(void)
 460{
 461	anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
 462			0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
 463			anon_vma_ctor);
 464	anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
 465			SLAB_PANIC|SLAB_ACCOUNT);
 466}
 467
 468/*
 469 * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
 470 *
 471 * Since there is no serialization what so ever against folio_remove_rmap_*()
 472 * the best this function can do is return a refcount increased anon_vma
 473 * that might have been relevant to this page.
 474 *
 475 * The page might have been remapped to a different anon_vma or the anon_vma
 476 * returned may already be freed (and even reused).
 477 *
 478 * In case it was remapped to a different anon_vma, the new anon_vma will be a
 479 * child of the old anon_vma, and the anon_vma lifetime rules will therefore
 480 * ensure that any anon_vma obtained from the page will still be valid for as
 481 * long as we observe page_mapped() [ hence all those page_mapped() tests ].
 482 *
 483 * All users of this function must be very careful when walking the anon_vma
 484 * chain and verify that the page in question is indeed mapped in it
 485 * [ something equivalent to page_mapped_in_vma() ].
 486 *
 487 * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
 488 * folio_remove_rmap_*() that the anon_vma pointer from page->mapping is valid
 489 * if there is a mapcount, we can dereference the anon_vma after observing
 490 * those.
 491 *
 492 * NOTE: the caller should hold folio lock when calling this.
 493 */
 494struct anon_vma *folio_get_anon_vma(const struct folio *folio)
 495{
 496	struct anon_vma *anon_vma = NULL;
 497	unsigned long anon_mapping;
 498
 499	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
 500
 501	rcu_read_lock();
 502	anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
 503	if ((anon_mapping & FOLIO_MAPPING_FLAGS) != FOLIO_MAPPING_ANON)
 504		goto out;
 505	if (!folio_mapped(folio))
 506		goto out;
 507
 508	anon_vma = (struct anon_vma *) (anon_mapping - FOLIO_MAPPING_ANON);
 509	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
 510		anon_vma = NULL;
 511		goto out;
 512	}
 513
 514	/*
 515	 * If this folio is still mapped, then its anon_vma cannot have been
 516	 * freed.  But if it has been unmapped, we have no security against the
 517	 * anon_vma structure being freed and reused (for another anon_vma:
 518	 * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
 519	 * above cannot corrupt).
 520	 */
 521	if (!folio_mapped(folio)) {
 522		rcu_read_unlock();
 523		put_anon_vma(anon_vma);
 524		return NULL;
 525	}
 526out:
 527	rcu_read_unlock();
 528
 529	return anon_vma;
 530}
 531
 532/*
 533 * Similar to folio_get_anon_vma() except it locks the anon_vma.
 534 *
 535 * Its a little more complex as it tries to keep the fast path to a single
 536 * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
 537 * reference like with folio_get_anon_vma() and then block on the mutex
 538 * on !rwc->try_lock case.
 539 */
 540struct anon_vma *folio_lock_anon_vma_read(const struct folio *folio,
 541					  struct rmap_walk_control *rwc)
 542{
 543	struct anon_vma *anon_vma = NULL;
 544	struct anon_vma *root_anon_vma;
 545	unsigned long anon_mapping;
 546
 547	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
 548
 549	rcu_read_lock();
 550	anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
 551	if ((anon_mapping & FOLIO_MAPPING_FLAGS) != FOLIO_MAPPING_ANON)
 552		goto out;
 553	if (!folio_mapped(folio))
 554		goto out;
 555
 556	anon_vma = (struct anon_vma *) (anon_mapping - FOLIO_MAPPING_ANON);
 557	root_anon_vma = READ_ONCE(anon_vma->root);
 558	if (down_read_trylock(&root_anon_vma->rwsem)) {
 559		/*
 560		 * If the folio is still mapped, then this anon_vma is still
 561		 * its anon_vma, and holding the mutex ensures that it will
 562		 * not go away, see anon_vma_free().
 563		 */
 564		if (!folio_mapped(folio)) {
 565			up_read(&root_anon_vma->rwsem);
 566			anon_vma = NULL;
 567		}
 568		goto out;
 569	}
 570
 571	if (rwc && rwc->try_lock) {
 572		anon_vma = NULL;
 573		rwc->contended = true;
 574		goto out;
 575	}
 576
 577	/* trylock failed, we got to sleep */
 578	if (!atomic_inc_not_zero(&anon_vma->refcount)) {
 579		anon_vma = NULL;
 580		goto out;
 581	}
 582
 583	if (!folio_mapped(folio)) {
 584		rcu_read_unlock();
 585		put_anon_vma(anon_vma);
 586		return NULL;
 587	}
 588
 589	/* we pinned the anon_vma, its safe to sleep */
 590	rcu_read_unlock();
 591	anon_vma_lock_read(anon_vma);
 592
 593	if (atomic_dec_and_test(&anon_vma->refcount)) {
 594		/*
 595		 * Oops, we held the last refcount, release the lock
 596		 * and bail -- can't simply use put_anon_vma() because
 597		 * we'll deadlock on the anon_vma_lock_write() recursion.
 598		 */
 599		anon_vma_unlock_read(anon_vma);
 600		__put_anon_vma(anon_vma);
 601		anon_vma = NULL;
 602	}
 603
 604	return anon_vma;
 605
 606out:
 607	rcu_read_unlock();
 608	return anon_vma;
 609}
 610
 611#ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
 612/*
 613 * Flush TLB entries for recently unmapped pages from remote CPUs. It is
 614 * important if a PTE was dirty when it was unmapped that it's flushed
 615 * before any IO is initiated on the page to prevent lost writes. Similarly,
 616 * it must be flushed before freeing to prevent data leakage.
 617 */
 618void try_to_unmap_flush(void)
 619{
 620	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
 621
 622	if (!tlb_ubc->flush_required)
 623		return;
 624
 625	arch_tlbbatch_flush(&tlb_ubc->arch);
 626	tlb_ubc->flush_required = false;
 627	tlb_ubc->writable = false;
 628}
 629
 630/* Flush iff there are potentially writable TLB entries that can race with IO */
 631void try_to_unmap_flush_dirty(void)
 632{
 633	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
 634
 635	if (tlb_ubc->writable)
 636		try_to_unmap_flush();
 637}
 638
 639/*
 640 * Bits 0-14 of mm->tlb_flush_batched record pending generations.
 641 * Bits 16-30 of mm->tlb_flush_batched bit record flushed generations.
 642 */
 643#define TLB_FLUSH_BATCH_FLUSHED_SHIFT	16
 644#define TLB_FLUSH_BATCH_PENDING_MASK			\
 645	((1 << (TLB_FLUSH_BATCH_FLUSHED_SHIFT - 1)) - 1)
 646#define TLB_FLUSH_BATCH_PENDING_LARGE			\
 647	(TLB_FLUSH_BATCH_PENDING_MASK / 2)
 648
 649static void set_tlb_ubc_flush_pending(struct mm_struct *mm, pte_t pteval,
 650		unsigned long start, unsigned long end)
 651{
 652	struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
 653	int batch;
 654	bool writable = pte_dirty(pteval);
 655
 656	if (!pte_accessible(mm, pteval))
 657		return;
 658
 659	arch_tlbbatch_add_pending(&tlb_ubc->arch, mm, start, end);
 660	tlb_ubc->flush_required = true;
 661
 662	/*
 663	 * Ensure compiler does not re-order the setting of tlb_flush_batched
 664	 * before the PTE is cleared.
 665	 */
 666	barrier();
 667	batch = atomic_read(&mm->tlb_flush_batched);
 668retry:
 669	if ((batch & TLB_FLUSH_BATCH_PENDING_MASK) > TLB_FLUSH_BATCH_PENDING_LARGE) {
 670		/*
 671		 * Prevent `pending' from catching up with `flushed' because of
 672		 * overflow.  Reset `pending' and `flushed' to be 1 and 0 if
 673		 * `pending' becomes large.
 674		 */
 675		if (!atomic_try_cmpxchg(&mm->tlb_flush_batched, &batch, 1))
 676			goto retry;
 677	} else {
 678		atomic_inc(&mm->tlb_flush_batched);
 679	}
 680
 681	/*
 682	 * If the PTE was dirty then it's best to assume it's writable. The
 683	 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
 684	 * before the page is queued for IO.
 685	 */
 686	if (writable)
 687		tlb_ubc->writable = true;
 688}
 689
 690/*
 691 * Returns true if the TLB flush should be deferred to the end of a batch of
 692 * unmap operations to reduce IPIs.
 693 */
 694static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
 695{
 696	if (!(flags & TTU_BATCH_FLUSH))
 697		return false;
 698
 699	return arch_tlbbatch_should_defer(mm);
 700}
 701
 702/*
 703 * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
 704 * releasing the PTL if TLB flushes are batched. It's possible for a parallel
 705 * operation such as mprotect or munmap to race between reclaim unmapping
 706 * the page and flushing the page. If this race occurs, it potentially allows
 707 * access to data via a stale TLB entry. Tracking all mm's that have TLB
 708 * batching in flight would be expensive during reclaim so instead track
 709 * whether TLB batching occurred in the past and if so then do a flush here
 710 * if required. This will cost one additional flush per reclaim cycle paid
 711 * by the first operation at risk such as mprotect and mumap.
 712 *
 713 * This must be called under the PTL so that an access to tlb_flush_batched
 714 * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
 715 * via the PTL.
 716 */
 717void flush_tlb_batched_pending(struct mm_struct *mm)
 718{
 719	int batch = atomic_read(&mm->tlb_flush_batched);
 720	int pending = batch & TLB_FLUSH_BATCH_PENDING_MASK;
 721	int flushed = batch >> TLB_FLUSH_BATCH_FLUSHED_SHIFT;
 722
 723	if (pending != flushed) {
 724		flush_tlb_mm(mm);
 725		/*
 726		 * If the new TLB flushing is pending during flushing, leave
 727		 * mm->tlb_flush_batched as is, to avoid losing flushing.
 728		 */
 729		atomic_cmpxchg(&mm->tlb_flush_batched, batch,
 730			       pending | (pending << TLB_FLUSH_BATCH_FLUSHED_SHIFT));
 731	}
 732}
 733#else
 734static void set_tlb_ubc_flush_pending(struct mm_struct *mm, pte_t pteval,
 735		unsigned long start, unsigned long end)
 736{
 737}
 738
 739static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
 740{
 741	return false;
 742}
 743#endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
 744
 745/**
 746 * page_address_in_vma - The virtual address of a page in this VMA.
 747 * @folio: The folio containing the page.
 748 * @page: The page within the folio.
 749 * @vma: The VMA we need to know the address in.
 750 *
 751 * Calculates the user virtual address of this page in the specified VMA.
 752 * It is the caller's responsibility to check the page is actually
 753 * within the VMA.  There may not currently be a PTE pointing at this
 754 * page, but if a page fault occurs at this address, this is the page
 755 * which will be accessed.
 756 *
 757 * Context: Caller should hold a reference to the folio.  Caller should
 758 * hold a lock (eg the i_mmap_lock or the mmap_lock) which keeps the
 759 * VMA from being altered.
 760 *
 761 * Return: The virtual address corresponding to this page in the VMA.
 762 */
 763unsigned long page_address_in_vma(const struct folio *folio,
 764		const struct page *page, const struct vm_area_struct *vma)
 765{
 766	if (folio_test_anon(folio)) {
 767		struct anon_vma *anon_vma = folio_anon_vma(folio);
 768		/*
 769		 * Note: swapoff's unuse_vma() is more efficient with this
 770		 * check, and needs it to match anon_vma when KSM is active.
 771		 */
 772		if (!vma->anon_vma || !anon_vma ||
 773		    vma->anon_vma->root != anon_vma->root)
 774			return -EFAULT;
 775	} else if (!vma->vm_file) {
 776		return -EFAULT;
 777	} else if (vma->vm_file->f_mapping != folio->mapping) {
 778		return -EFAULT;
 779	}
 780
 781	/* KSM folios don't reach here because of the !anon_vma check */
 782	return vma_address(vma, page_pgoff(folio, page), 1);
 783}
 784
 785/*
 786 * Returns the actual pmd_t* where we expect 'address' to be mapped from, or
 787 * NULL if it doesn't exist.  No guarantees / checks on what the pmd_t*
 788 * represents.
 789 */
 790pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
 791{
 792	pgd_t *pgd;
 793	p4d_t *p4d;
 794	pud_t *pud;
 795	pmd_t *pmd = NULL;
 796
 797	pgd = pgd_offset(mm, address);
 798	if (!pgd_present(*pgd))
 799		goto out;
 800
 801	p4d = p4d_offset(pgd, address);
 802	if (!p4d_present(*p4d))
 803		goto out;
 804
 805	pud = pud_offset(p4d, address);
 806	if (!pud_present(*pud))
 807		goto out;
 808
 809	pmd = pmd_offset(pud, address);
 810out:
 811	return pmd;
 812}
 813
 814struct folio_referenced_arg {
 815	int mapcount;
 816	int referenced;
 817	vm_flags_t vm_flags;
 818	struct mem_cgroup *memcg;
 819};
 820
 821/*
 822 * arg: folio_referenced_arg will be passed
 823 */
 824static bool folio_referenced_one(struct folio *folio,
 825		struct vm_area_struct *vma, unsigned long address, void *arg)
 826{
 827	struct folio_referenced_arg *pra = arg;
 828	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
 829	int ptes = 0, referenced = 0;
 830
 831	while (page_vma_mapped_walk(&pvmw)) {
 832		address = pvmw.address;
 833
 834		if (vma->vm_flags & VM_LOCKED) {
 835			ptes++;
 836			pra->mapcount--;
 837
 838			/* Only mlock fully mapped pages */
 839			if (pvmw.pte && ptes != pvmw.nr_pages)
 840				continue;
 841
 842			/*
 843			 * All PTEs must be protected by page table lock in
 844			 * order to mlock the page.
 845			 *
 846			 * If page table boundary has been cross, current ptl
 847			 * only protect part of ptes.
 848			 */
 849			if (pvmw.flags & PVMW_PGTABLE_CROSSED)
 850				continue;
 851
 852			/* Restore the mlock which got missed */
 853			mlock_vma_folio(folio, vma);
 854			page_vma_mapped_walk_done(&pvmw);
 855			pra->vm_flags |= VM_LOCKED;
 856			return false; /* To break the loop */
 857		}
 858
 859		/*
 860		 * Skip the non-shared swapbacked folio mapped solely by
 861		 * the exiting or OOM-reaped process. This avoids redundant
 862		 * swap-out followed by an immediate unmap.
 863		 */
 864		if ((!atomic_read(&vma->vm_mm->mm_users) ||
 865		    check_stable_address_space(vma->vm_mm)) &&
 866		    folio_test_anon(folio) && folio_test_swapbacked(folio) &&
 867		    !folio_maybe_mapped_shared(folio)) {
 868			pra->referenced = -1;
 869			page_vma_mapped_walk_done(&pvmw);
 870			return false;
 871		}
 872
 873		if (lru_gen_enabled() && pvmw.pte) {
 874			if (lru_gen_look_around(&pvmw))
 875				referenced++;
 876		} else if (pvmw.pte) {
 877			if (ptep_clear_flush_young_notify(vma, address,
 878						pvmw.pte))
 879				referenced++;
 880		} else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
 881			if (pmdp_clear_flush_young_notify(vma, address,
 882						pvmw.pmd))
 883				referenced++;
 884		} else {
 885			/* unexpected pmd-mapped folio? */
 886			WARN_ON_ONCE(1);
 887		}
 888
 889		pra->mapcount--;
 890	}
 891
 892	if (referenced)
 893		folio_clear_idle(folio);
 894	if (folio_test_clear_young(folio))
 895		referenced++;
 896
 897	if (referenced) {
 898		pra->referenced++;
 899		pra->vm_flags |= vma->vm_flags & ~VM_LOCKED;
 900	}
 901
 902	if (!pra->mapcount)
 903		return false; /* To break the loop */
 904
 905	return true;
 906}
 907
 908static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
 909{
 910	struct folio_referenced_arg *pra = arg;
 911	struct mem_cgroup *memcg = pra->memcg;
 912
 913	/*
 914	 * Ignore references from this mapping if it has no recency. If the
 915	 * folio has been used in another mapping, we will catch it; if this
 916	 * other mapping is already gone, the unmap path will have set the
 917	 * referenced flag or activated the folio in zap_pte_range().
 918	 */
 919	if (!vma_has_recency(vma))
 920		return true;
 921
 922	/*
 923	 * If we are reclaiming on behalf of a cgroup, skip counting on behalf
 924	 * of references from different cgroups.
 925	 */
 926	if (memcg && !mm_match_cgroup(vma->vm_mm, memcg))
 927		return true;
 928
 929	return false;
 930}
 931
 932/**
 933 * folio_referenced() - Test if the folio was referenced.
 934 * @folio: The folio to test.
 935 * @is_locked: Caller holds lock on the folio.
 936 * @memcg: target memory cgroup
 937 * @vm_flags: A combination of all the vma->vm_flags which referenced the folio.
 938 *
 939 * Quick test_and_clear_referenced for all mappings of a folio,
 940 *
 941 * Return: The number of mappings which referenced the folio. Return -1 if
 942 * the function bailed out due to rmap lock contention.
 943 */
 944int folio_referenced(struct folio *folio, int is_locked,
 945		     struct mem_cgroup *memcg, vm_flags_t *vm_flags)
 946{
 947	bool we_locked = false;
 948	struct folio_referenced_arg pra = {
 949		.mapcount = folio_mapcount(folio),
 950		.memcg = memcg,
 951	};
 952	struct rmap_walk_control rwc = {
 953		.rmap_one = folio_referenced_one,
 954		.arg = (void *)&pra,
 955		.anon_lock = folio_lock_anon_vma_read,
 956		.try_lock = true,
 957		.invalid_vma = invalid_folio_referenced_vma,
 958	};
 959
 960	*vm_flags = 0;
 961	if (!pra.mapcount)
 962		return 0;
 963
 964	if (!folio_raw_mapping(folio))
 965		return 0;
 966
 967	if (!is_locked) {
 968		we_locked = folio_trylock(folio);
 969		if (!we_locked)
 970			return 1;
 971	}
 972
 973	rmap_walk(folio, &rwc);
 974	*vm_flags = pra.vm_flags;
 975
 976	if (we_locked)
 977		folio_unlock(folio);
 978
 979	return rwc.contended ? -1 : pra.referenced;
 980}
 981
 982static int page_vma_mkclean_one(struct page_vma_mapped_walk *pvmw)
 983{
 984	int cleaned = 0;
 985	struct vm_area_struct *vma = pvmw->vma;
 986	struct mmu_notifier_range range;
 987	unsigned long address = pvmw->address;
 988
 989	/*
 990	 * We have to assume the worse case ie pmd for invalidation. Note that
 991	 * the folio can not be freed from this function.
 992	 */
 993	mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE, 0,
 994				vma->vm_mm, address, vma_address_end(pvmw));
 995	mmu_notifier_invalidate_range_start(&range);
 996
 997	while (page_vma_mapped_walk(pvmw)) {
 998		int ret = 0;
 999
1000		address = pvmw->address;
1001		if (pvmw->pte) {
1002			pte_t *pte = pvmw->pte;
1003			pte_t entry = ptep_get(pte);
1004
1005			/*
1006			 * PFN swap PTEs, such as device-exclusive ones, that
1007			 * actually map pages are clean and not writable from a
1008			 * CPU perspective. The MMU notifier takes care of any
1009			 * device aspects.
1010			 */
1011			if (!pte_present(entry))
1012				continue;
1013			if (!pte_dirty(entry) && !pte_write(entry))
1014				continue;
1015
1016			flush_cache_page(vma, address, pte_pfn(entry));
1017			entry = ptep_clear_flush(vma, address, pte);
1018			entry = pte_wrprotect(entry);
1019			entry = pte_mkclean(entry);
1020			set_pte_at(vma->vm_mm, address, pte, entry);
1021			ret = 1;
1022		} else {
1023#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1024			pmd_t *pmd = pvmw->pmd;
1025			pmd_t entry = pmdp_get(pmd);
1026
1027			/*
1028			 * Please see the comment above (!pte_present).
1029			 * A non present PMD is not writable from a CPU
1030			 * perspective.
1031			 */
1032			if (!pmd_present(entry))
1033				continue;
1034			if (!pmd_dirty(entry) && !pmd_write(entry))
1035				continue;
1036
1037			flush_cache_range(vma, address,
1038					  address + HPAGE_PMD_SIZE);
1039			entry = pmdp_invalidate(vma, address, pmd);
1040			entry = pmd_wrprotect(entry);
1041			entry = pmd_mkclean(entry);
1042			set_pmd_at(vma->vm_mm, address, pmd, entry);
1043			ret = 1;
1044#else
1045			/* unexpected pmd-mapped folio? */
1046			WARN_ON_ONCE(1);
1047#endif
1048		}
1049
1050		if (ret)
1051			cleaned++;
1052	}
1053
1054	mmu_notifier_invalidate_range_end(&range);
1055
1056	return cleaned;
1057}
1058
1059static bool page_mkclean_one(struct folio *folio, struct vm_area_struct *vma,
1060			     unsigned long address, void *arg)
1061{
1062	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, PVMW_SYNC);
1063	int *cleaned = arg;
1064
1065	*cleaned += page_vma_mkclean_one(&pvmw);
1066
1067	return true;
1068}
1069
1070static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
1071{
1072	if (vma->vm_flags & VM_SHARED)
1073		return false;
1074
1075	return true;
1076}
1077
1078int folio_mkclean(struct folio *folio)
1079{
1080	int cleaned = 0;
1081	struct address_space *mapping;
1082	struct rmap_walk_control rwc = {
1083		.arg = (void *)&cleaned,
1084		.rmap_one = page_mkclean_one,
1085		.invalid_vma = invalid_mkclean_vma,
1086	};
1087
1088	BUG_ON(!folio_test_locked(folio));
1089
1090	if (!folio_mapped(folio))
1091		return 0;
1092
1093	mapping = folio_mapping(folio);
1094	if (!mapping)
1095		return 0;
1096
1097	rmap_walk(folio, &rwc);
1098
1099	return cleaned;
1100}
1101EXPORT_SYMBOL_GPL(folio_mkclean);
1102
1103struct wrprotect_file_state {
1104	int cleaned;
1105	pgoff_t pgoff;
1106	unsigned long pfn;
1107	unsigned long nr_pages;
1108};
1109
1110static bool mapping_wrprotect_range_one(struct folio *folio,
1111		struct vm_area_struct *vma, unsigned long address, void *arg)
1112{
1113	struct wrprotect_file_state *state = (struct wrprotect_file_state *)arg;
1114	struct page_vma_mapped_walk pvmw = {
1115		.pfn		= state->pfn,
1116		.nr_pages	= state->nr_pages,
1117		.pgoff		= state->pgoff,
1118		.vma		= vma,
1119		.address	= address,
1120		.flags		= PVMW_SYNC,
1121	};
1122
1123	state->cleaned += page_vma_mkclean_one(&pvmw);
1124
1125	return true;
1126}
1127
1128static void __rmap_walk_file(struct folio *folio, struct address_space *mapping,
1129			     pgoff_t pgoff_start, unsigned long nr_pages,
1130			     struct rmap_walk_control *rwc, bool locked);
1131
1132/**
1133 * mapping_wrprotect_range() - Write-protect all mappings in a specified range.
1134 *
1135 * @mapping:	The mapping whose reverse mapping should be traversed.
1136 * @pgoff:	The page offset at which @pfn is mapped within @mapping.
1137 * @pfn:	The PFN of the page mapped in @mapping at @pgoff.
1138 * @nr_pages:	The number of physically contiguous base pages spanned.
1139 *
1140 * Traverses the reverse mapping, finding all VMAs which contain a shared
1141 * mapping of the pages in the specified range in @mapping, and write-protects
1142 * them (that is, updates the page tables to mark the mappings read-only such
1143 * that a write protection fault arises when the mappings are written to).
1144 *
1145 * The @pfn value need not refer to a folio, but rather can reference a kernel
1146 * allocation which is mapped into userland. We therefore do not require that
1147 * the page maps to a folio with a valid mapping or index field, rather the
1148 * caller specifies these in @mapping and @pgoff.
1149 *
1150 * Return: the number of write-protected PTEs, or an error.
1151 */
1152int mapping_wrprotect_range(struct address_space *mapping, pgoff_t pgoff,
1153		unsigned long pfn, unsigned long nr_pages)
1154{
1155	struct wrprotect_file_state state = {
1156		.cleaned = 0,
1157		.pgoff = pgoff,
1158		.pfn = pfn,
1159		.nr_pages = nr_pages,
1160	};
1161	struct rmap_walk_control rwc = {
1162		.arg = (void *)&state,
1163		.rmap_one = mapping_wrprotect_range_one,
1164		.invalid_vma = invalid_mkclean_vma,
1165	};
1166
1167	if (!mapping)
1168		return 0;
1169
1170	__rmap_walk_file(/* folio = */NULL, mapping, pgoff, nr_pages, &rwc,
1171			 /* locked = */false);
1172
1173	return state.cleaned;
1174}
1175EXPORT_SYMBOL_GPL(mapping_wrprotect_range);
1176
1177/**
1178 * pfn_mkclean_range - Cleans the PTEs (including PMDs) mapped with range of
1179 *                     [@pfn, @pfn + @nr_pages) at the specific offset (@pgoff)
1180 *                     within the @vma of shared mappings. And since clean PTEs
1181 *                     should also be readonly, write protects them too.
1182 * @pfn: start pfn.
1183 * @nr_pages: number of physically contiguous pages srarting with @pfn.
1184 * @pgoff: page offset that the @pfn mapped with.
1185 * @vma: vma that @pfn mapped within.
1186 *
1187 * Returns the number of cleaned PTEs (including PMDs).
1188 */
1189int pfn_mkclean_range(unsigned long pfn, unsigned long nr_pages, pgoff_t pgoff,
1190		      struct vm_area_struct *vma)
1191{
1192	struct page_vma_mapped_walk pvmw = {
1193		.pfn		= pfn,
1194		.nr_pages	= nr_pages,
1195		.pgoff		= pgoff,
1196		.vma		= vma,
1197		.flags		= PVMW_SYNC,
1198	};
1199
1200	if (invalid_mkclean_vma(vma, NULL))
1201		return 0;
1202
1203	pvmw.address = vma_address(vma, pgoff, nr_pages);
1204	VM_BUG_ON_VMA(pvmw.address == -EFAULT, vma);
1205
1206	return page_vma_mkclean_one(&pvmw);
1207}
1208
1209static void __folio_mod_stat(struct folio *folio, int nr, int nr_pmdmapped)
1210{
1211	int idx;
1212
1213	if (nr) {
1214		idx = folio_test_anon(folio) ? NR_ANON_MAPPED : NR_FILE_MAPPED;
1215		lruvec_stat_mod_folio(folio, idx, nr);
1216	}
1217	if (nr_pmdmapped) {
1218		if (folio_test_anon(folio)) {
1219			idx = NR_ANON_THPS;
1220			lruvec_stat_mod_folio(folio, idx, nr_pmdmapped);
1221		} else {
1222			/* NR_*_PMDMAPPED are not maintained per-memcg */
1223			idx = folio_test_swapbacked(folio) ?
1224				NR_SHMEM_PMDMAPPED : NR_FILE_PMDMAPPED;
1225			__mod_node_page_state(folio_pgdat(folio), idx,
1226					      nr_pmdmapped);
1227		}
1228	}
1229}
1230
1231static __always_inline void __folio_add_rmap(struct folio *folio,
1232		struct page *page, int nr_pages, struct vm_area_struct *vma,
1233		enum pgtable_level level)
1234{
1235	atomic_t *mapped = &folio->_nr_pages_mapped;
1236	const int orig_nr_pages = nr_pages;
1237	int first = 0, nr = 0, nr_pmdmapped = 0;
1238
1239	__folio_rmap_sanity_checks(folio, page, nr_pages, level);
1240
1241	switch (level) {
1242	case PGTABLE_LEVEL_PTE:
1243		if (!folio_test_large(folio)) {
1244			nr = atomic_inc_and_test(&folio->_mapcount);
1245			break;
1246		}
1247
1248		if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
1249			nr = folio_add_return_large_mapcount(folio, orig_nr_pages, vma);
1250			if (nr == orig_nr_pages)
1251				/* Was completely unmapped. */
1252				nr = folio_large_nr_pages(folio);
1253			else
1254				nr = 0;
1255			break;
1256		}
1257
1258		do {
1259			first += atomic_inc_and_test(&page->_mapcount);
1260		} while (page++, --nr_pages > 0);
1261
1262		if (first &&
1263		    atomic_add_return_relaxed(first, mapped) < ENTIRELY_MAPPED)
1264			nr = first;
1265
1266		folio_add_large_mapcount(folio, orig_nr_pages, vma);
1267		break;
1268	case PGTABLE_LEVEL_PMD:
1269	case PGTABLE_LEVEL_PUD:
1270		first = atomic_inc_and_test(&folio->_entire_mapcount);
1271		if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
1272			if (level == PGTABLE_LEVEL_PMD && first)
1273				nr_pmdmapped = folio_large_nr_pages(folio);
1274			nr = folio_inc_return_large_mapcount(folio, vma);
1275			if (nr == 1)
1276				/* Was completely unmapped. */
1277				nr = folio_large_nr_pages(folio);
1278			else
1279				nr = 0;
1280			break;
1281		}
1282
1283		if (first) {
1284			nr = atomic_add_return_relaxed(ENTIRELY_MAPPED, mapped);
1285			if (likely(nr < ENTIRELY_MAPPED + ENTIRELY_MAPPED)) {
1286				nr_pages = folio_large_nr_pages(folio);
1287				/*
1288				 * We only track PMD mappings of PMD-sized
1289				 * folios separately.
1290				 */
1291				if (level == PGTABLE_LEVEL_PMD)
1292					nr_pmdmapped = nr_pages;
1293				nr = nr_pages - (nr & FOLIO_PAGES_MAPPED);
1294				/* Raced ahead of a remove and another add? */
1295				if (unlikely(nr < 0))
1296					nr = 0;
1297			} else {
1298				/* Raced ahead of a remove of ENTIRELY_MAPPED */
1299				nr = 0;
1300			}
1301		}
1302		folio_inc_large_mapcount(folio, vma);
1303		break;
1304	default:
1305		BUILD_BUG();
1306	}
1307	__folio_mod_stat(folio, nr, nr_pmdmapped);
1308}
1309
1310/**
1311 * folio_move_anon_rmap - move a folio to our anon_vma
1312 * @folio:	The folio to move to our anon_vma
1313 * @vma:	The vma the folio belongs to
1314 *
1315 * When a folio belongs exclusively to one process after a COW event,
1316 * that folio can be moved into the anon_vma that belongs to just that
1317 * process, so the rmap code will not search the parent or sibling processes.
1318 */
1319void folio_move_anon_rmap(struct folio *folio, struct vm_area_struct *vma)
1320{
1321	void *anon_vma = vma->anon_vma;
1322
1323	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
1324	VM_BUG_ON_VMA(!anon_vma, vma);
1325
1326	anon_vma += FOLIO_MAPPING_ANON;
1327	/*
1328	 * Ensure that anon_vma and the FOLIO_MAPPING_ANON bit are written
1329	 * simultaneously, so a concurrent reader (eg folio_referenced()'s
1330	 * folio_test_anon()) will not see one without the other.
1331	 */
1332	WRITE_ONCE(folio->mapping, anon_vma);
1333}
1334
1335/**
1336 * __folio_set_anon - set up a new anonymous rmap for a folio
1337 * @folio:	The folio to set up the new anonymous rmap for.
1338 * @vma:	VM area to add the folio to.
1339 * @address:	User virtual address of the mapping
1340 * @exclusive:	Whether the folio is exclusive to the process.
1341 */
1342static void __folio_set_anon(struct folio *folio, struct vm_area_struct *vma,
1343			     unsigned long address, bool exclusive)
1344{
1345	struct anon_vma *anon_vma = vma->anon_vma;
1346
1347	BUG_ON(!anon_vma);
1348
1349	/*
1350	 * If the folio isn't exclusive to this vma, we must use the _oldest_
1351	 * possible anon_vma for the folio mapping!
1352	 */
1353	if (!exclusive)
1354		anon_vma = anon_vma->root;
1355
1356	/*
1357	 * page_idle does a lockless/optimistic rmap scan on folio->mapping.
1358	 * Make sure the compiler doesn't split the stores of anon_vma and
1359	 * the FOLIO_MAPPING_ANON type identifier, otherwise the rmap code
1360	 * could mistake the mapping for a struct address_space and crash.
1361	 */
1362	anon_vma = (void *) anon_vma + FOLIO_MAPPING_ANON;
1363	WRITE_ONCE(folio->mapping, (struct address_space *) anon_vma);
1364	folio->index = linear_page_index(vma, address);
1365}
1366
1367/**
1368 * __page_check_anon_rmap - sanity check anonymous rmap addition
1369 * @folio:	The folio containing @page.
1370 * @page:	the page to check the mapping of
1371 * @vma:	the vm area in which the mapping is added
1372 * @address:	the user virtual address mapped
1373 */
1374static void __page_check_anon_rmap(const struct folio *folio,
1375		const struct page *page, struct vm_area_struct *vma,
1376		unsigned long address)
1377{
1378	/*
1379	 * The page's anon-rmap details (mapping and index) are guaranteed to
1380	 * be set up correctly at this point.
1381	 *
1382	 * We have exclusion against folio_add_anon_rmap_*() because the caller
1383	 * always holds the page locked.
1384	 *
1385	 * We have exclusion against folio_add_new_anon_rmap because those pages
1386	 * are initially only visible via the pagetables, and the pte is locked
1387	 * over the call to folio_add_new_anon_rmap.
1388	 */
1389	VM_BUG_ON_FOLIO(folio_anon_vma(folio)->root != vma->anon_vma->root,
1390			folio);
1391	VM_BUG_ON_PAGE(page_pgoff(folio, page) != linear_page_index(vma, address),
1392		       page);
1393}
1394
1395static __always_inline void __folio_add_anon_rmap(struct folio *folio,
1396		struct page *page, int nr_pages, struct vm_area_struct *vma,
1397		unsigned long address, rmap_t flags, enum pgtable_level level)
1398{
1399	int i;
1400
1401	VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
1402
1403	__folio_add_rmap(folio, page, nr_pages, vma, level);
1404
1405	if (likely(!folio_test_ksm(folio)))
1406		__page_check_anon_rmap(folio, page, vma, address);
1407
1408	if (flags & RMAP_EXCLUSIVE) {
1409		switch (level) {
1410		case PGTABLE_LEVEL_PTE:
1411			for (i = 0; i < nr_pages; i++)
1412				SetPageAnonExclusive(page + i);
1413			break;
1414		case PGTABLE_LEVEL_PMD:
1415			SetPageAnonExclusive(page);
1416			break;
1417		case PGTABLE_LEVEL_PUD:
1418			/*
1419			 * Keep the compiler happy, we don't support anonymous
1420			 * PUD mappings.
1421			 */
1422			WARN_ON_ONCE(1);
1423			break;
1424		default:
1425			BUILD_BUG();
1426		}
1427	}
1428
1429	VM_WARN_ON_FOLIO(!folio_test_large(folio) && PageAnonExclusive(page) &&
1430			 atomic_read(&folio->_mapcount) > 0, folio);
1431	for (i = 0; i < nr_pages; i++) {
1432		struct page *cur_page = page + i;
1433
1434		VM_WARN_ON_FOLIO(folio_test_large(folio) &&
1435				 folio_entire_mapcount(folio) > 1 &&
1436				 PageAnonExclusive(cur_page), folio);
1437		if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT))
1438			continue;
1439
1440		/*
1441		 * While PTE-mapping a THP we have a PMD and a PTE
1442		 * mapping.
1443		 */
1444		VM_WARN_ON_FOLIO(atomic_read(&cur_page->_mapcount) > 0 &&
1445				 PageAnonExclusive(cur_page), folio);
1446	}
1447
1448	/*
1449	 * Only mlock it if the folio is fully mapped to the VMA.
1450	 *
1451	 * Partially mapped folios can be split on reclaim and part outside
1452	 * of mlocked VMA can be evicted or freed.
1453	 */
1454	if (folio_nr_pages(folio) == nr_pages)
1455		mlock_vma_folio(folio, vma);
1456}
1457
1458/**
1459 * folio_add_anon_rmap_ptes - add PTE mappings to a page range of an anon folio
1460 * @folio:	The folio to add the mappings to
1461 * @page:	The first page to add
1462 * @nr_pages:	The number of pages which will be mapped
1463 * @vma:	The vm area in which the mappings are added
1464 * @address:	The user virtual address of the first page to map
1465 * @flags:	The rmap flags
1466 *
1467 * The page range of folio is defined by [first_page, first_page + nr_pages)
1468 *
1469 * The caller needs to hold the page table lock, and the page must be locked in
1470 * the anon_vma case: to serialize mapping,index checking after setting,
1471 * and to ensure that an anon folio is not being upgraded racily to a KSM folio
1472 * (but KSM folios are never downgraded).
1473 */
1474void folio_add_anon_rmap_ptes(struct folio *folio, struct page *page,
1475		int nr_pages, struct vm_area_struct *vma, unsigned long address,
1476		rmap_t flags)
1477{
1478	__folio_add_anon_rmap(folio, page, nr_pages, vma, address, flags,
1479			      PGTABLE_LEVEL_PTE);
1480}
1481
1482/**
1483 * folio_add_anon_rmap_pmd - add a PMD mapping to a page range of an anon folio
1484 * @folio:	The folio to add the mapping to
1485 * @page:	The first page to add
1486 * @vma:	The vm area in which the mapping is added
1487 * @address:	The user virtual address of the first page to map
1488 * @flags:	The rmap flags
1489 *
1490 * The page range of folio is defined by [first_page, first_page + HPAGE_PMD_NR)
1491 *
1492 * The caller needs to hold the page table lock, and the page must be locked in
1493 * the anon_vma case: to serialize mapping,index checking after setting.
1494 */
1495void folio_add_anon_rmap_pmd(struct folio *folio, struct page *page,
1496		struct vm_area_struct *vma, unsigned long address, rmap_t flags)
1497{
1498#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1499	__folio_add_anon_rmap(folio, page, HPAGE_PMD_NR, vma, address, flags,
1500			      PGTABLE_LEVEL_PMD);
1501#else
1502	WARN_ON_ONCE(true);
1503#endif
1504}
1505
1506/**
1507 * folio_add_new_anon_rmap - Add mapping to a new anonymous folio.
1508 * @folio:	The folio to add the mapping to.
1509 * @vma:	the vm area in which the mapping is added
1510 * @address:	the user virtual address mapped
1511 * @flags:	The rmap flags
1512 *
1513 * Like folio_add_anon_rmap_*() but must only be called on *new* folios.
1514 * This means the inc-and-test can be bypassed.
1515 * The folio doesn't necessarily need to be locked while it's exclusive
1516 * unless two threads map it concurrently. However, the folio must be
1517 * locked if it's shared.
1518 *
1519 * If the folio is pmd-mappable, it is accounted as a THP.
1520 */
1521void folio_add_new_anon_rmap(struct folio *folio, struct vm_area_struct *vma,
1522		unsigned long address, rmap_t flags)
1523{
1524	const bool exclusive = flags & RMAP_EXCLUSIVE;
1525	int nr = 1, nr_pmdmapped = 0;
1526
1527	VM_WARN_ON_FOLIO(folio_test_hugetlb(folio), folio);
1528	VM_WARN_ON_FOLIO(!exclusive && !folio_test_locked(folio), folio);
1529
1530	/*
1531	 * VM_DROPPABLE mappings don't swap; instead they're just dropped when
1532	 * under memory pressure.
1533	 */
1534	if (!folio_test_swapbacked(folio) && !(vma->vm_flags & VM_DROPPABLE))
1535		__folio_set_swapbacked(folio);
1536	__folio_set_anon(folio, vma, address, exclusive);
1537
1538	if (likely(!folio_test_large(folio))) {
1539		/* increment count (starts at -1) */
1540		atomic_set(&folio->_mapcount, 0);
1541		if (exclusive)
1542			SetPageAnonExclusive(&folio->page);
1543	} else if (!folio_test_pmd_mappable(folio)) {
1544		int i;
1545
1546		nr = folio_large_nr_pages(folio);
1547		for (i = 0; i < nr; i++) {
1548			struct page *page = folio_page(folio, i);
1549
1550			if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT))
1551				/* increment count (starts at -1) */
1552				atomic_set(&page->_mapcount, 0);
1553			if (exclusive)
1554				SetPageAnonExclusive(page);
1555		}
1556
1557		folio_set_large_mapcount(folio, nr, vma);
1558		if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT))
1559			atomic_set(&folio->_nr_pages_mapped, nr);
1560	} else {
1561		nr = folio_large_nr_pages(folio);
1562		/* increment count (starts at -1) */
1563		atomic_set(&folio->_entire_mapcount, 0);
1564		folio_set_large_mapcount(folio, 1, vma);
1565		if (IS_ENABLED(CONFIG_PAGE_MAPCOUNT))
1566			atomic_set(&folio->_nr_pages_mapped, ENTIRELY_MAPPED);
1567		if (exclusive)
1568			SetPageAnonExclusive(&folio->page);
1569		nr_pmdmapped = nr;
1570	}
1571
1572	VM_WARN_ON_ONCE(address < vma->vm_start ||
1573			address + (nr << PAGE_SHIFT) > vma->vm_end);
1574
1575	__folio_mod_stat(folio, nr, nr_pmdmapped);
1576	mod_mthp_stat(folio_order(folio), MTHP_STAT_NR_ANON, 1);
1577}
1578
1579static __always_inline void __folio_add_file_rmap(struct folio *folio,
1580		struct page *page, int nr_pages, struct vm_area_struct *vma,
1581		enum pgtable_level level)
1582{
1583	VM_WARN_ON_FOLIO(folio_test_anon(folio), folio);
1584
1585	__folio_add_rmap(folio, page, nr_pages, vma, level);
1586
1587	/*
1588	 * Only mlock it if the folio is fully mapped to the VMA.
1589	 *
1590	 * Partially mapped folios can be split on reclaim and part outside
1591	 * of mlocked VMA can be evicted or freed.
1592	 */
1593	if (folio_nr_pages(folio) == nr_pages)
1594		mlock_vma_folio(folio, vma);
1595}
1596
1597/**
1598 * folio_add_file_rmap_ptes - add PTE mappings to a page range of a folio
1599 * @folio:	The folio to add the mappings to
1600 * @page:	The first page to add
1601 * @nr_pages:	The number of pages that will be mapped using PTEs
1602 * @vma:	The vm area in which the mappings are added
1603 *
1604 * The page range of the folio is defined by [page, page + nr_pages)
1605 *
1606 * The caller needs to hold the page table lock.
1607 */
1608void folio_add_file_rmap_ptes(struct folio *folio, struct page *page,
1609		int nr_pages, struct vm_area_struct *vma)
1610{
1611	__folio_add_file_rmap(folio, page, nr_pages, vma, PGTABLE_LEVEL_PTE);
1612}
1613
1614/**
1615 * folio_add_file_rmap_pmd - add a PMD mapping to a page range of a folio
1616 * @folio:	The folio to add the mapping to
1617 * @page:	The first page to add
1618 * @vma:	The vm area in which the mapping is added
1619 *
1620 * The page range of the folio is defined by [page, page + HPAGE_PMD_NR)
1621 *
1622 * The caller needs to hold the page table lock.
1623 */
1624void folio_add_file_rmap_pmd(struct folio *folio, struct page *page,
1625		struct vm_area_struct *vma)
1626{
1627#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1628	__folio_add_file_rmap(folio, page, HPAGE_PMD_NR, vma, PGTABLE_LEVEL_PMD);
1629#else
1630	WARN_ON_ONCE(true);
1631#endif
1632}
1633
1634/**
1635 * folio_add_file_rmap_pud - add a PUD mapping to a page range of a folio
1636 * @folio:	The folio to add the mapping to
1637 * @page:	The first page to add
1638 * @vma:	The vm area in which the mapping is added
1639 *
1640 * The page range of the folio is defined by [page, page + HPAGE_PUD_NR)
1641 *
1642 * The caller needs to hold the page table lock.
1643 */
1644void folio_add_file_rmap_pud(struct folio *folio, struct page *page,
1645		struct vm_area_struct *vma)
1646{
1647#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
1648	defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
1649	__folio_add_file_rmap(folio, page, HPAGE_PUD_NR, vma, PGTABLE_LEVEL_PUD);
1650#else
1651	WARN_ON_ONCE(true);
1652#endif
1653}
1654
1655static __always_inline void __folio_remove_rmap(struct folio *folio,
1656		struct page *page, int nr_pages, struct vm_area_struct *vma,
1657		enum pgtable_level level)
1658{
1659	atomic_t *mapped = &folio->_nr_pages_mapped;
1660	int last = 0, nr = 0, nr_pmdmapped = 0;
1661	bool partially_mapped = false;
1662
1663	__folio_rmap_sanity_checks(folio, page, nr_pages, level);
1664
1665	switch (level) {
1666	case PGTABLE_LEVEL_PTE:
1667		if (!folio_test_large(folio)) {
1668			nr = atomic_add_negative(-1, &folio->_mapcount);
1669			break;
1670		}
1671
1672		if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
1673			nr = folio_sub_return_large_mapcount(folio, nr_pages, vma);
1674			if (!nr) {
1675				/* Now completely unmapped. */
1676				nr = folio_large_nr_pages(folio);
1677			} else {
1678				partially_mapped = nr < folio_large_nr_pages(folio) &&
1679						   !folio_entire_mapcount(folio);
1680				nr = 0;
1681			}
1682			break;
1683		}
1684
1685		folio_sub_large_mapcount(folio, nr_pages, vma);
1686		do {
1687			last += atomic_add_negative(-1, &page->_mapcount);
1688		} while (page++, --nr_pages > 0);
1689
1690		if (last &&
1691		    atomic_sub_return_relaxed(last, mapped) < ENTIRELY_MAPPED)
1692			nr = last;
1693
1694		partially_mapped = nr && atomic_read(mapped);
1695		break;
1696	case PGTABLE_LEVEL_PMD:
1697	case PGTABLE_LEVEL_PUD:
1698		if (IS_ENABLED(CONFIG_NO_PAGE_MAPCOUNT)) {
1699			last = atomic_add_negative(-1, &folio->_entire_mapcount);
1700			if (level == PGTABLE_LEVEL_PMD && last)
1701				nr_pmdmapped = folio_large_nr_pages(folio);
1702			nr = folio_dec_return_large_mapcount(folio, vma);
1703			if (!nr) {
1704				/* Now completely unmapped. */
1705				nr = folio_large_nr_pages(folio);
1706			} else {
1707				partially_mapped = last &&
1708						   nr < folio_large_nr_pages(folio);
1709				nr = 0;
1710			}
1711			break;
1712		}
1713
1714		folio_dec_large_mapcount(folio, vma);
1715		last = atomic_add_negative(-1, &folio->_entire_mapcount);
1716		if (last) {
1717			nr = atomic_sub_return_relaxed(ENTIRELY_MAPPED, mapped);
1718			if (likely(nr < ENTIRELY_MAPPED)) {
1719				nr_pages = folio_large_nr_pages(folio);
1720				if (level == PGTABLE_LEVEL_PMD)
1721					nr_pmdmapped = nr_pages;
1722				nr = nr_pages - nr;
1723				/* Raced ahead of another remove and an add? */
1724				if (unlikely(nr < 0))
1725					nr = 0;
1726			} else {
1727				/* An add of ENTIRELY_MAPPED raced ahead */
1728				nr = 0;
1729			}
1730		}
1731
1732		partially_mapped = nr && nr < nr_pmdmapped;
1733		break;
1734	default:
1735		BUILD_BUG();
1736	}
1737
1738	/*
1739	 * Queue anon large folio for deferred split if at least one page of
1740	 * the folio is unmapped and at least one page is still mapped.
1741	 *
1742	 * Check partially_mapped first to ensure it is a large folio.
1743	 *
1744	 * Device private folios do not support deferred splitting and
1745	 * shrinker based scanning of the folios to free.
1746	 */
1747	if (partially_mapped && folio_test_anon(folio) &&
1748	    !folio_test_partially_mapped(folio) &&
1749	    !folio_is_device_private(folio))
1750		deferred_split_folio(folio, true);
1751
1752	__folio_mod_stat(folio, -nr, -nr_pmdmapped);
1753
1754	/*
1755	 * It would be tidy to reset folio_test_anon mapping when fully
1756	 * unmapped, but that might overwrite a racing folio_add_anon_rmap_*()
1757	 * which increments mapcount after us but sets mapping before us:
1758	 * so leave the reset to free_pages_prepare, and remember that
1759	 * it's only reliable while mapped.
1760	 */
1761
1762	munlock_vma_folio(folio, vma);
1763}
1764
1765/**
1766 * folio_remove_rmap_ptes - remove PTE mappings from a page range of a folio
1767 * @folio:	The folio to remove the mappings from
1768 * @page:	The first page to remove
1769 * @nr_pages:	The number of pages that will be removed from the mapping
1770 * @vma:	The vm area from which the mappings are removed
1771 *
1772 * The page range of the folio is defined by [page, page + nr_pages)
1773 *
1774 * The caller needs to hold the page table lock.
1775 */
1776void folio_remove_rmap_ptes(struct folio *folio, struct page *page,
1777		int nr_pages, struct vm_area_struct *vma)
1778{
1779	__folio_remove_rmap(folio, page, nr_pages, vma, PGTABLE_LEVEL_PTE);
1780}
1781
1782/**
1783 * folio_remove_rmap_pmd - remove a PMD mapping from a page range of a folio
1784 * @folio:	The folio to remove the mapping from
1785 * @page:	The first page to remove
1786 * @vma:	The vm area from which the mapping is removed
1787 *
1788 * The page range of the folio is defined by [page, page + HPAGE_PMD_NR)
1789 *
1790 * The caller needs to hold the page table lock.
1791 */
1792void folio_remove_rmap_pmd(struct folio *folio, struct page *page,
1793		struct vm_area_struct *vma)
1794{
1795#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1796	__folio_remove_rmap(folio, page, HPAGE_PMD_NR, vma, PGTABLE_LEVEL_PMD);
1797#else
1798	WARN_ON_ONCE(true);
1799#endif
1800}
1801
1802/**
1803 * folio_remove_rmap_pud - remove a PUD mapping from a page range of a folio
1804 * @folio:	The folio to remove the mapping from
1805 * @page:	The first page to remove
1806 * @vma:	The vm area from which the mapping is removed
1807 *
1808 * The page range of the folio is defined by [page, page + HPAGE_PUD_NR)
1809 *
1810 * The caller needs to hold the page table lock.
1811 */
1812void folio_remove_rmap_pud(struct folio *folio, struct page *page,
1813		struct vm_area_struct *vma)
1814{
1815#if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
1816	defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
1817	__folio_remove_rmap(folio, page, HPAGE_PUD_NR, vma, PGTABLE_LEVEL_PUD);
1818#else
1819	WARN_ON_ONCE(true);
1820#endif
1821}
1822
1823static inline unsigned int folio_unmap_pte_batch(struct folio *folio,
1824			struct page_vma_mapped_walk *pvmw,
1825			enum ttu_flags flags, pte_t pte)
1826{
1827	unsigned long end_addr, addr = pvmw->address;
1828	struct vm_area_struct *vma = pvmw->vma;
1829	unsigned int max_nr;
1830
1831	if (flags & TTU_HWPOISON)
1832		return 1;
1833	if (!folio_test_large(folio))
1834		return 1;
1835
1836	/* We may only batch within a single VMA and a single page table. */
1837	end_addr = pmd_addr_end(addr, vma->vm_end);
1838	max_nr = (end_addr - addr) >> PAGE_SHIFT;
1839
1840	/* We only support lazyfree batching for now ... */
1841	if (!folio_test_anon(folio) || folio_test_swapbacked(folio))
1842		return 1;
1843	if (pte_unused(pte))
1844		return 1;
1845
1846	/*
1847	 * If unmap fails, we need to restore the ptes. To avoid accidentally
1848	 * upgrading write permissions for ptes that were not originally
1849	 * writable, and to avoid losing the soft-dirty bit, use the
1850	 * appropriate FPB flags.
1851	 */
1852	return folio_pte_batch_flags(folio, vma, pvmw->pte, &pte, max_nr,
1853				     FPB_RESPECT_WRITE | FPB_RESPECT_SOFT_DIRTY);
1854}
1855
1856/*
1857 * @arg: enum ttu_flags will be passed to this argument
1858 */
1859static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
1860		     unsigned long address, void *arg)
1861{
1862	struct mm_struct *mm = vma->vm_mm;
1863	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
1864	bool anon_exclusive, ret = true;
1865	pte_t pteval;
1866	struct page *subpage;
1867	struct mmu_notifier_range range;
1868	enum ttu_flags flags = (enum ttu_flags)(long)arg;
1869	unsigned long nr_pages = 1, end_addr;
1870	unsigned long pfn;
1871	unsigned long hsz = 0;
1872	int ptes = 0;
1873
1874	/*
1875	 * When racing against e.g. zap_pte_range() on another cpu,
1876	 * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(),
1877	 * try_to_unmap() may return before page_mapped() has become false,
1878	 * if page table locking is skipped: use TTU_SYNC to wait for that.
1879	 */
1880	if (flags & TTU_SYNC)
1881		pvmw.flags = PVMW_SYNC;
1882
1883	/*
1884	 * For THP, we have to assume the worse case ie pmd for invalidation.
1885	 * For hugetlb, it could be much worse if we need to do pud
1886	 * invalidation in the case of pmd sharing.
1887	 *
1888	 * Note that the folio can not be freed in this function as call of
1889	 * try_to_unmap() must hold a reference on the folio.
1890	 */
1891	range.end = vma_address_end(&pvmw);
1892	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
1893				address, range.end);
1894	if (folio_test_hugetlb(folio)) {
1895		/*
1896		 * If sharing is possible, start and end will be adjusted
1897		 * accordingly.
1898		 */
1899		adjust_range_if_pmd_sharing_possible(vma, &range.start,
1900						     &range.end);
1901
1902		/* We need the huge page size for set_huge_pte_at() */
1903		hsz = huge_page_size(hstate_vma(vma));
1904	}
1905	mmu_notifier_invalidate_range_start(&range);
1906
1907	while (page_vma_mapped_walk(&pvmw)) {
1908		/*
1909		 * If the folio is in an mlock()d vma, we must not swap it out.
1910		 */
1911		if (!(flags & TTU_IGNORE_MLOCK) &&
1912		    (vma->vm_flags & VM_LOCKED)) {
1913			ptes++;
1914
1915			/*
1916			 * Set 'ret' to indicate the page cannot be unmapped.
1917			 *
1918			 * Do not jump to walk_abort immediately as additional
1919			 * iteration might be required to detect fully mapped
1920			 * folio an mlock it.
1921			 */
1922			ret = false;
1923
1924			/* Only mlock fully mapped pages */
1925			if (pvmw.pte && ptes != pvmw.nr_pages)
1926				continue;
1927
1928			/*
1929			 * All PTEs must be protected by page table lock in
1930			 * order to mlock the page.
1931			 *
1932			 * If page table boundary has been cross, current ptl
1933			 * only protect part of ptes.
1934			 */
1935			if (pvmw.flags & PVMW_PGTABLE_CROSSED)
1936				goto walk_done;
1937
1938			/* Restore the mlock which got missed */
1939			mlock_vma_folio(folio, vma);
1940			goto walk_done;
1941		}
1942
1943		if (!pvmw.pte) {
1944			if (folio_test_anon(folio) && !folio_test_swapbacked(folio)) {
1945				if (unmap_huge_pmd_locked(vma, pvmw.address, pvmw.pmd, folio))
1946					goto walk_done;
1947				/*
1948				 * unmap_huge_pmd_locked has either already marked
1949				 * the folio as swap-backed or decided to retain it
1950				 * due to GUP or speculative references.
1951				 */
1952				goto walk_abort;
1953			}
1954
1955			if (flags & TTU_SPLIT_HUGE_PMD) {
1956				/*
1957				 * We temporarily have to drop the PTL and
1958				 * restart so we can process the PTE-mapped THP.
1959				 */
1960				split_huge_pmd_locked(vma, pvmw.address,
1961						      pvmw.pmd, false);
1962				flags &= ~TTU_SPLIT_HUGE_PMD;
1963				page_vma_mapped_walk_restart(&pvmw);
1964				continue;
1965			}
1966		}
1967
1968		/* Unexpected PMD-mapped THP? */
1969		VM_BUG_ON_FOLIO(!pvmw.pte, folio);
1970
1971		/*
1972		 * Handle PFN swap PTEs, such as device-exclusive ones, that
1973		 * actually map pages.
1974		 */
1975		pteval = ptep_get(pvmw.pte);
1976		if (likely(pte_present(pteval))) {
1977			pfn = pte_pfn(pteval);
1978		} else {
1979			const softleaf_t entry = softleaf_from_pte(pteval);
1980
1981			pfn = softleaf_to_pfn(entry);
1982			VM_WARN_ON_FOLIO(folio_test_hugetlb(folio), folio);
1983		}
1984
1985		subpage = folio_page(folio, pfn - folio_pfn(folio));
1986		address = pvmw.address;
1987		anon_exclusive = folio_test_anon(folio) &&
1988				 PageAnonExclusive(subpage);
1989
1990		if (folio_test_hugetlb(folio)) {
1991			bool anon = folio_test_anon(folio);
1992
1993			/*
1994			 * The try_to_unmap() is only passed a hugetlb page
1995			 * in the case where the hugetlb page is poisoned.
1996			 */
1997			VM_BUG_ON_PAGE(!PageHWPoison(subpage), subpage);
1998			/*
1999			 * huge_pmd_unshare may unmap an entire PMD page.
2000			 * There is no way of knowing exactly which PMDs may
2001			 * be cached for this mm, so we must flush them all.
2002			 * start/end were already adjusted above to cover this
2003			 * range.
2004			 */
2005			flush_cache_range(vma, range.start, range.end);
2006
2007			/*
2008			 * To call huge_pmd_unshare, i_mmap_rwsem must be
2009			 * held in write mode.  Caller needs to explicitly
2010			 * do this outside rmap routines.
2011			 *
2012			 * We also must hold hugetlb vma_lock in write mode.
2013			 * Lock order dictates acquiring vma_lock BEFORE
2014			 * i_mmap_rwsem.  We can only try lock here and fail
2015			 * if unsuccessful.
2016			 */
2017			if (!anon) {
2018				struct mmu_gather tlb;
2019
2020				VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
2021				if (!hugetlb_vma_trylock_write(vma))
2022					goto walk_abort;
2023
2024				tlb_gather_mmu_vma(&tlb, vma);
2025				if (huge_pmd_unshare(&tlb, vma, address, pvmw.pte)) {
2026					hugetlb_vma_unlock_write(vma);
2027					huge_pmd_unshare_flush(&tlb, vma);
2028					tlb_finish_mmu(&tlb);
2029					/*
2030					 * The PMD table was unmapped,
2031					 * consequently unmapping the folio.
2032					 */
2033					goto walk_done;
2034				}
2035				hugetlb_vma_unlock_write(vma);
2036				tlb_finish_mmu(&tlb);
2037			}
2038			pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
2039			if (pte_dirty(pteval))
2040				folio_mark_dirty(folio);
2041		} else if (likely(pte_present(pteval))) {
2042			nr_pages = folio_unmap_pte_batch(folio, &pvmw, flags, pteval);
2043			end_addr = address + nr_pages * PAGE_SIZE;
2044			flush_cache_range(vma, address, end_addr);
2045
2046			/* Nuke the page table entry. */
2047			pteval = get_and_clear_ptes(mm, address, pvmw.pte, nr_pages);
2048			/*
2049			 * We clear the PTE but do not flush so potentially
2050			 * a remote CPU could still be writing to the folio.
2051			 * If the entry was previously clean then the
2052			 * architecture must guarantee that a clear->dirty
2053			 * transition on a cached TLB entry is written through
2054			 * and traps if the PTE is unmapped.
2055			 */
2056			if (should_defer_flush(mm, flags))
2057				set_tlb_ubc_flush_pending(mm, pteval, address, end_addr);
2058			else
2059				flush_tlb_range(vma, address, end_addr);
2060			if (pte_dirty(pteval))
2061				folio_mark_dirty(folio);
2062		} else {
2063			pte_clear(mm, address, pvmw.pte);
2064		}
2065
2066		/*
2067		 * Now the pte is cleared. If this pte was uffd-wp armed,
2068		 * we may want to replace a none pte with a marker pte if
2069		 * it's file-backed, so we don't lose the tracking info.
2070		 */
2071		pte_install_uffd_wp_if_needed(vma, address, pvmw.pte, pteval);
2072
2073		/* Update high watermark before we lower rss */
2074		update_hiwater_rss(mm);
2075
2076		if (PageHWPoison(subpage) && (flags & TTU_HWPOISON)) {
2077			pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
2078			if (folio_test_hugetlb(folio)) {
2079				hugetlb_count_sub(folio_nr_pages(folio), mm);
2080				set_huge_pte_at(mm, address, pvmw.pte, pteval,
2081						hsz);
2082			} else {
2083				dec_mm_counter(mm, mm_counter(folio));
2084				set_pte_at(mm, address, pvmw.pte, pteval);
2085			}
2086		} else if (likely(pte_present(pteval)) && pte_unused(pteval) &&
2087			   !userfaultfd_armed(vma)) {
2088			/*
2089			 * The guest indicated that the page content is of no
2090			 * interest anymore. Simply discard the pte, vmscan
2091			 * will take care of the rest.
2092			 * A future reference will then fault in a new zero
2093			 * page. When userfaultfd is active, we must not drop
2094			 * this page though, as its main user (postcopy
2095			 * migration) will not expect userfaults on already
2096			 * copied pages.
2097			 */
2098			dec_mm_counter(mm, mm_counter(folio));
2099		} else if (folio_test_anon(folio)) {
2100			swp_entry_t entry = page_swap_entry(subpage);
2101			pte_t swp_pte;
2102			/*
2103			 * Store the swap location in the pte.
2104			 * See handle_pte_fault() ...
2105			 */
2106			if (unlikely(folio_test_swapbacked(folio) !=
2107					folio_test_swapcache(folio))) {
2108				WARN_ON_ONCE(1);
2109				goto walk_abort;
2110			}
2111
2112			/* MADV_FREE page check */
2113			if (!folio_test_swapbacked(folio)) {
2114				int ref_count, map_count;
2115
2116				/*
2117				 * Synchronize with gup_pte_range():
2118				 * - clear PTE; barrier; read refcount
2119				 * - inc refcount; barrier; read PTE
2120				 */
2121				smp_mb();
2122
2123				ref_count = folio_ref_count(folio);
2124				map_count = folio_mapcount(folio);
2125
2126				/*
2127				 * Order reads for page refcount and dirty flag
2128				 * (see comments in __remove_mapping()).
2129				 */
2130				smp_rmb();
2131
2132				if (folio_test_dirty(folio) && !(vma->vm_flags & VM_DROPPABLE)) {
2133					/*
2134					 * redirtied either using the page table or a previously
2135					 * obtained GUP reference.
2136					 */
2137					set_ptes(mm, address, pvmw.pte, pteval, nr_pages);
2138					folio_set_swapbacked(folio);
2139					goto walk_abort;
2140				} else if (ref_count != 1 + map_count) {
2141					/*
2142					 * Additional reference. Could be a GUP reference or any
2143					 * speculative reference. GUP users must mark the folio
2144					 * dirty if there was a modification. This folio cannot be
2145					 * reclaimed right now either way, so act just like nothing
2146					 * happened.
2147					 * We'll come back here later and detect if the folio was
2148					 * dirtied when the additional reference is gone.
2149					 */
2150					set_ptes(mm, address, pvmw.pte, pteval, nr_pages);
2151					goto walk_abort;
2152				}
2153				add_mm_counter(mm, MM_ANONPAGES, -nr_pages);
2154				goto discard;
2155			}
2156
2157			if (swap_duplicate(entry) < 0) {
2158				set_pte_at(mm, address, pvmw.pte, pteval);
2159				goto walk_abort;
2160			}
2161
2162			/*
2163			 * arch_unmap_one() is expected to be a NOP on
2164			 * architectures where we could have PFN swap PTEs,
2165			 * so we'll not check/care.
2166			 */
2167			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
2168				swap_free(entry);
2169				set_pte_at(mm, address, pvmw.pte, pteval);
2170				goto walk_abort;
2171			}
2172
2173			/* See folio_try_share_anon_rmap(): clear PTE first. */
2174			if (anon_exclusive &&
2175			    folio_try_share_anon_rmap_pte(folio, subpage)) {
2176				swap_free(entry);
2177				set_pte_at(mm, address, pvmw.pte, pteval);
2178				goto walk_abort;
2179			}
2180			if (list_empty(&mm->mmlist)) {
2181				spin_lock(&mmlist_lock);
2182				if (list_empty(&mm->mmlist))
2183					list_add(&mm->mmlist, &init_mm.mmlist);
2184				spin_unlock(&mmlist_lock);
2185			}
2186			dec_mm_counter(mm, MM_ANONPAGES);
2187			inc_mm_counter(mm, MM_SWAPENTS);
2188			swp_pte = swp_entry_to_pte(entry);
2189			if (anon_exclusive)
2190				swp_pte = pte_swp_mkexclusive(swp_pte);
2191			if (likely(pte_present(pteval))) {
2192				if (pte_soft_dirty(pteval))
2193					swp_pte = pte_swp_mksoft_dirty(swp_pte);
2194				if (pte_uffd_wp(pteval))
2195					swp_pte = pte_swp_mkuffd_wp(swp_pte);
2196			} else {
2197				if (pte_swp_soft_dirty(pteval))
2198					swp_pte = pte_swp_mksoft_dirty(swp_pte);
2199				if (pte_swp_uffd_wp(pteval))
2200					swp_pte = pte_swp_mkuffd_wp(swp_pte);
2201			}
2202			set_pte_at(mm, address, pvmw.pte, swp_pte);
2203		} else {
2204			/*
2205			 * This is a locked file-backed folio,
2206			 * so it cannot be removed from the page
2207			 * cache and replaced by a new folio before
2208			 * mmu_notifier_invalidate_range_end, so no
2209			 * concurrent thread might update its page table
2210			 * to point at a new folio while a device is
2211			 * still using this folio.
2212			 *
2213			 * See Documentation/mm/mmu_notifier.rst
2214			 */
2215			dec_mm_counter(mm, mm_counter_file(folio));
2216		}
2217discard:
2218		if (unlikely(folio_test_hugetlb(folio))) {
2219			hugetlb_remove_rmap(folio);
2220		} else {
2221			folio_remove_rmap_ptes(folio, subpage, nr_pages, vma);
2222		}
2223		if (vma->vm_flags & VM_LOCKED)
2224			mlock_drain_local();
2225		folio_put_refs(folio, nr_pages);
2226
2227		/*
2228		 * If we are sure that we batched the entire folio and cleared
2229		 * all PTEs, we can just optimize and stop right here.
2230		 */
2231		if (nr_pages == folio_nr_pages(folio))
2232			goto walk_done;
2233		continue;
2234walk_abort:
2235		ret = false;
2236walk_done:
2237		page_vma_mapped_walk_done(&pvmw);
2238		break;
2239	}
2240
2241	mmu_notifier_invalidate_range_end(&range);
2242
2243	return ret;
2244}
2245
2246static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
2247{
2248	return vma_is_temporary_stack(vma);
2249}
2250
2251static int folio_not_mapped(struct folio *folio)
2252{
2253	return !folio_mapped(folio);
2254}
2255
2256/**
2257 * try_to_unmap - Try to remove all page table mappings to a folio.
2258 * @folio: The folio to unmap.
2259 * @flags: action and flags
2260 *
2261 * Tries to remove all the page table entries which are mapping this
2262 * folio.  It is the caller's responsibility to check if the folio is
2263 * still mapped if needed (use TTU_SYNC to prevent accounting races).
2264 *
2265 * Context: Caller must hold the folio lock.
2266 */
2267void try_to_unmap(struct folio *folio, enum ttu_flags flags)
2268{
2269	struct rmap_walk_control rwc = {
2270		.rmap_one = try_to_unmap_one,
2271		.arg = (void *)flags,
2272		.done = folio_not_mapped,
2273		.anon_lock = folio_lock_anon_vma_read,
2274	};
2275
2276	if (flags & TTU_RMAP_LOCKED)
2277		rmap_walk_locked(folio, &rwc);
2278	else
2279		rmap_walk(folio, &rwc);
2280}
2281
2282/*
2283 * @arg: enum ttu_flags will be passed to this argument.
2284 *
2285 * If TTU_SPLIT_HUGE_PMD is specified any PMD mappings will be split into PTEs
2286 * containing migration entries.
2287 */
2288static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,
2289		     unsigned long address, void *arg)
2290{
2291	struct mm_struct *mm = vma->vm_mm;
2292	DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
2293	bool anon_exclusive, writable, ret = true;
2294	pte_t pteval;
2295	struct page *subpage;
2296	struct mmu_notifier_range range;
2297	enum ttu_flags flags = (enum ttu_flags)(long)arg;
2298	unsigned long pfn;
2299	unsigned long hsz = 0;
2300
2301	/*
2302	 * When racing against e.g. zap_pte_range() on another cpu,
2303	 * in between its ptep_get_and_clear_full() and folio_remove_rmap_*(),
2304	 * try_to_migrate() may return before page_mapped() has become false,
2305	 * if page table locking is skipped: use TTU_SYNC to wait for that.
2306	 */
2307	if (flags & TTU_SYNC)
2308		pvmw.flags = PVMW_SYNC;
2309
2310	/*
2311	 * For THP, we have to assume the worse case ie pmd for invalidation.
2312	 * For hugetlb, it could be much worse if we need to do pud
2313	 * invalidation in the case of pmd sharing.
2314	 *
2315	 * Note that the page can not be free in this function as call of
2316	 * try_to_unmap() must hold a reference on the page.
2317	 */
2318	range.end = vma_address_end(&pvmw);
2319	mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2320				address, range.end);
2321	if (folio_test_hugetlb(folio)) {
2322		/*
2323		 * If sharing is possible, start and end will be adjusted
2324		 * accordingly.
2325		 */
2326		adjust_range_if_pmd_sharing_possible(vma, &range.start,
2327						     &range.end);
2328
2329		/* We need the huge page size for set_huge_pte_at() */
2330		hsz = huge_page_size(hstate_vma(vma));
2331	}
2332	mmu_notifier_invalidate_range_start(&range);
2333
2334	while (page_vma_mapped_walk(&pvmw)) {
2335		/* PMD-mapped THP migration entry */
2336		if (!pvmw.pte) {
2337			__maybe_unused unsigned long pfn;
2338			__maybe_unused pmd_t pmdval;
2339
2340			if (flags & TTU_SPLIT_HUGE_PMD) {
2341				/*
2342				 * split_huge_pmd_locked() might leave the
2343				 * folio mapped through PTEs. Retry the walk
2344				 * so we can detect this scenario and properly
2345				 * abort the walk.
2346				 */
2347				split_huge_pmd_locked(vma, pvmw.address,
2348						      pvmw.pmd, true);
2349				flags &= ~TTU_SPLIT_HUGE_PMD;
2350				page_vma_mapped_walk_restart(&pvmw);
2351				continue;
2352			}
2353#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
2354			pmdval = pmdp_get(pvmw.pmd);
2355			if (likely(pmd_present(pmdval)))
2356				pfn = pmd_pfn(pmdval);
2357			else
2358				pfn = softleaf_to_pfn(softleaf_from_pmd(pmdval));
2359
2360			subpage = folio_page(folio, pfn - folio_pfn(folio));
2361
2362			VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
2363					!folio_test_pmd_mappable(folio), folio);
2364
2365			if (set_pmd_migration_entry(&pvmw, subpage)) {
2366				ret = false;
2367				page_vma_mapped_walk_done(&pvmw);
2368				break;
2369			}
2370			continue;
2371#endif
2372		}
2373
2374		/* Unexpected PMD-mapped THP? */
2375		VM_BUG_ON_FOLIO(!pvmw.pte, folio);
2376
2377		/*
2378		 * Handle PFN swap PTEs, such as device-exclusive ones, that
2379		 * actually map pages.
2380		 */
2381		pteval = ptep_get(pvmw.pte);
2382		if (likely(pte_present(pteval))) {
2383			pfn = pte_pfn(pteval);
2384		} else {
2385			const softleaf_t entry = softleaf_from_pte(pteval);
2386
2387			pfn = softleaf_to_pfn(entry);
2388			VM_WARN_ON_FOLIO(folio_test_hugetlb(folio), folio);
2389		}
2390
2391		subpage = folio_page(folio, pfn - folio_pfn(folio));
2392		address = pvmw.address;
2393		anon_exclusive = folio_test_anon(folio) &&
2394				 PageAnonExclusive(subpage);
2395
2396		if (folio_test_hugetlb(folio)) {
2397			bool anon = folio_test_anon(folio);
2398
2399			/*
2400			 * huge_pmd_unshare may unmap an entire PMD page.
2401			 * There is no way of knowing exactly which PMDs may
2402			 * be cached for this mm, so we must flush them all.
2403			 * start/end were already adjusted above to cover this
2404			 * range.
2405			 */
2406			flush_cache_range(vma, range.start, range.end);
2407
2408			/*
2409			 * To call huge_pmd_unshare, i_mmap_rwsem must be
2410			 * held in write mode.  Caller needs to explicitly
2411			 * do this outside rmap routines.
2412			 *
2413			 * We also must hold hugetlb vma_lock in write mode.
2414			 * Lock order dictates acquiring vma_lock BEFORE
2415			 * i_mmap_rwsem.  We can only try lock here and
2416			 * fail if unsuccessful.
2417			 */
2418			if (!anon) {
2419				struct mmu_gather tlb;
2420
2421				VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
2422				if (!hugetlb_vma_trylock_write(vma)) {
2423					page_vma_mapped_walk_done(&pvmw);
2424					ret = false;
2425					break;
2426				}
2427
2428				tlb_gather_mmu_vma(&tlb, vma);
2429				if (huge_pmd_unshare(&tlb, vma, address, pvmw.pte)) {
2430					hugetlb_vma_unlock_write(vma);
2431					huge_pmd_unshare_flush(&tlb, vma);
2432					tlb_finish_mmu(&tlb);
2433					/*
2434					 * The PMD table was unmapped,
2435					 * consequently unmapping the folio.
2436					 */
2437					page_vma_mapped_walk_done(&pvmw);
2438					break;
2439				}
2440				hugetlb_vma_unlock_write(vma);
2441				tlb_finish_mmu(&tlb);
2442			}
2443			/* Nuke the hugetlb page table entry */
2444			pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
2445			if (pte_dirty(pteval))
2446				folio_mark_dirty(folio);
2447			writable = pte_write(pteval);
2448		} else if (likely(pte_present(pteval))) {
2449			flush_cache_page(vma, address, pfn);
2450			/* Nuke the page table entry. */
2451			if (should_defer_flush(mm, flags)) {
2452				/*
2453				 * We clear the PTE but do not flush so potentially
2454				 * a remote CPU could still be writing to the folio.
2455				 * If the entry was previously clean then the
2456				 * architecture must guarantee that a clear->dirty
2457				 * transition on a cached TLB entry is written through
2458				 * and traps if the PTE is unmapped.
2459				 */
2460				pteval = ptep_get_and_clear(mm, address, pvmw.pte);
2461
2462				set_tlb_ubc_flush_pending(mm, pteval, address, address + PAGE_SIZE);
2463			} else {
2464				pteval = ptep_clear_flush(vma, address, pvmw.pte);
2465			}
2466			if (pte_dirty(pteval))
2467				folio_mark_dirty(folio);
2468			writable = pte_write(pteval);
2469		} else {
2470			const softleaf_t entry = softleaf_from_pte(pteval);
2471
2472			pte_clear(mm, address, pvmw.pte);
2473
2474			writable = softleaf_is_device_private_write(entry);
2475		}
2476
2477		VM_WARN_ON_FOLIO(writable && folio_test_anon(folio) &&
2478				!anon_exclusive, folio);
2479
2480		/* Update high watermark before we lower rss */
2481		update_hiwater_rss(mm);
2482
2483		if (PageHWPoison(subpage)) {
2484			VM_WARN_ON_FOLIO(folio_is_device_private(folio), folio);
2485
2486			pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
2487			if (folio_test_hugetlb(folio)) {
2488				hugetlb_count_sub(folio_nr_pages(folio), mm);
2489				set_huge_pte_at(mm, address, pvmw.pte, pteval,
2490						hsz);
2491			} else {
2492				dec_mm_counter(mm, mm_counter(folio));
2493				set_pte_at(mm, address, pvmw.pte, pteval);
2494			}
2495		} else if (likely(pte_present(pteval)) && pte_unused(pteval) &&
2496			   !userfaultfd_armed(vma)) {
2497			/*
2498			 * The guest indicated that the page content is of no
2499			 * interest anymore. Simply discard the pte, vmscan
2500			 * will take care of the rest.
2501			 * A future reference will then fault in a new zero
2502			 * page. When userfaultfd is active, we must not drop
2503			 * this page though, as its main user (postcopy
2504			 * migration) will not expect userfaults on already
2505			 * copied pages.
2506			 */
2507			dec_mm_counter(mm, mm_counter(folio));
2508		} else {
2509			swp_entry_t entry;
2510			pte_t swp_pte;
2511
2512			/*
2513			 * arch_unmap_one() is expected to be a NOP on
2514			 * architectures where we could have PFN swap PTEs,
2515			 * so we'll not check/care.
2516			 */
2517			if (arch_unmap_one(mm, vma, address, pteval) < 0) {
2518				if (folio_test_hugetlb(folio))
2519					set_huge_pte_at(mm, address, pvmw.pte,
2520							pteval, hsz);
2521				else
2522					set_pte_at(mm, address, pvmw.pte, pteval);
2523				ret = false;
2524				page_vma_mapped_walk_done(&pvmw);
2525				break;
2526			}
2527
2528			/* See folio_try_share_anon_rmap_pte(): clear PTE first. */
2529			if (folio_test_hugetlb(folio)) {
2530				if (anon_exclusive &&
2531				    hugetlb_try_share_anon_rmap(folio)) {
2532					set_huge_pte_at(mm, address, pvmw.pte,
2533							pteval, hsz);
2534					ret = false;
2535					page_vma_mapped_walk_done(&pvmw);
2536					break;
2537				}
2538			} else if (anon_exclusive &&
2539				   folio_try_share_anon_rmap_pte(folio, subpage)) {
2540				set_pte_at(mm, address, pvmw.pte, pteval);
2541				ret = false;
2542				page_vma_mapped_walk_done(&pvmw);
2543				break;
2544			}
2545
2546			/*
2547			 * Store the pfn of the page in a special migration
2548			 * pte. do_swap_page() will wait until the migration
2549			 * pte is removed and then restart fault handling.
2550			 */
2551			if (writable)
2552				entry = make_writable_migration_entry(
2553							page_to_pfn(subpage));
2554			else if (anon_exclusive)
2555				entry = make_readable_exclusive_migration_entry(
2556							page_to_pfn(subpage));
2557			else
2558				entry = make_readable_migration_entry(
2559							page_to_pfn(subpage));
2560			if (likely(pte_present(pteval))) {
2561				if (pte_young(pteval))
2562					entry = make_migration_entry_young(entry);
2563				if (pte_dirty(pteval))
2564					entry = make_migration_entry_dirty(entry);
2565				swp_pte = swp_entry_to_pte(entry);
2566				if (pte_soft_dirty(pteval))
2567					swp_pte = pte_swp_mksoft_dirty(swp_pte);
2568				if (pte_uffd_wp(pteval))
2569					swp_pte = pte_swp_mkuffd_wp(swp_pte);
2570			} else {
2571				swp_pte = swp_entry_to_pte(entry);
2572				if (pte_swp_soft_dirty(pteval))
2573					swp_pte = pte_swp_mksoft_dirty(swp_pte);
2574				if (pte_swp_uffd_wp(pteval))
2575					swp_pte = pte_swp_mkuffd_wp(swp_pte);
2576			}
2577			if (folio_test_hugetlb(folio))
2578				set_huge_pte_at(mm, address, pvmw.pte, swp_pte,
2579						hsz);
2580			else
2581				set_pte_at(mm, address, pvmw.pte, swp_pte);
2582			trace_set_migration_pte(address, pte_val(swp_pte),
2583						folio_order(folio));
2584			/*
2585			 * No need to invalidate here it will synchronize on
2586			 * against the special swap migration pte.
2587			 */
2588		}
2589
2590		if (unlikely(folio_test_hugetlb(folio)))
2591			hugetlb_remove_rmap(folio);
2592		else
2593			folio_remove_rmap_pte(folio, subpage, vma);
2594		if (vma->vm_flags & VM_LOCKED)
2595			mlock_drain_local();
2596		folio_put(folio);
2597	}
2598
2599	mmu_notifier_invalidate_range_end(&range);
2600
2601	return ret;
2602}
2603
2604/**
2605 * try_to_migrate - try to replace all page table mappings with swap entries
2606 * @folio: the folio to replace page table entries for
2607 * @flags: action and flags
2608 *
2609 * Tries to remove all the page table entries which are mapping this folio and
2610 * replace them with special swap entries. Caller must hold the folio lock.
2611 */
2612void try_to_migrate(struct folio *folio, enum ttu_flags flags)
2613{
2614	struct rmap_walk_control rwc = {
2615		.rmap_one = try_to_migrate_one,
2616		.arg = (void *)flags,
2617		.done = folio_not_mapped,
2618		.anon_lock = folio_lock_anon_vma_read,
2619	};
2620
2621	/*
2622	 * Migration always ignores mlock and only supports TTU_RMAP_LOCKED and
2623	 * TTU_SPLIT_HUGE_PMD, TTU_SYNC, and TTU_BATCH_FLUSH flags.
2624	 */
2625	if (WARN_ON_ONCE(flags & ~(TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
2626					TTU_SYNC | TTU_BATCH_FLUSH)))
2627		return;
2628
2629	if (folio_is_zone_device(folio) &&
2630	    (!folio_is_device_private(folio) && !folio_is_device_coherent(folio)))
2631		return;
2632
2633	/*
2634	 * During exec, a temporary VMA is setup and later moved.
2635	 * The VMA is moved under the anon_vma lock but not the
2636	 * page tables leading to a race where migration cannot
2637	 * find the migration ptes. Rather than increasing the
2638	 * locking requirements of exec(), migration skips
2639	 * temporary VMAs until after exec() completes.
2640	 */
2641	if (!folio_test_ksm(folio) && folio_test_anon(folio))
2642		rwc.invalid_vma = invalid_migration_vma;
2643
2644	if (flags & TTU_RMAP_LOCKED)
2645		rmap_walk_locked(folio, &rwc);
2646	else
2647		rmap_walk(folio, &rwc);
2648}
2649
2650#ifdef CONFIG_DEVICE_PRIVATE
2651/**
2652 * make_device_exclusive() - Mark a page for exclusive use by a device
2653 * @mm: mm_struct of associated target process
2654 * @addr: the virtual address to mark for exclusive device access
2655 * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
2656 * @foliop: folio pointer will be stored here on success.
2657 *
2658 * This function looks up the page mapped at the given address, grabs a
2659 * folio reference, locks the folio and replaces the PTE with special
2660 * device-exclusive PFN swap entry, preventing access through the process
2661 * page tables. The function will return with the folio locked and referenced.
2662 *
2663 * On fault, the device-exclusive entries are replaced with the original PTE
2664 * under folio lock, after calling MMU notifiers.
2665 *
2666 * Only anonymous non-hugetlb folios are supported and the VMA must have
2667 * write permissions such that we can fault in the anonymous page writable
2668 * in order to mark it exclusive. The caller must hold the mmap_lock in read
2669 * mode.
2670 *
2671 * A driver using this to program access from a device must use a mmu notifier
2672 * critical section to hold a device specific lock during programming. Once
2673 * programming is complete it should drop the folio lock and reference after
2674 * which point CPU access to the page will revoke the exclusive access.
2675 *
2676 * Notes:
2677 *   #. This function always operates on individual PTEs mapping individual
2678 *      pages. PMD-sized THPs are first remapped to be mapped by PTEs before
2679 *      the conversion happens on a single PTE corresponding to @addr.
2680 *   #. While concurrent access through the process page tables is prevented,
2681 *      concurrent access through other page references (e.g., earlier GUP
2682 *      invocation) is not handled and not supported.
2683 *   #. device-exclusive entries are considered "clean" and "old" by core-mm.
2684 *      Device drivers must update the folio state when informed by MMU
2685 *      notifiers.
2686 *
2687 * Returns: pointer to mapped page on success, otherwise a negative error.
2688 */
2689struct page *make_device_exclusive(struct mm_struct *mm, unsigned long addr,
2690		void *owner, struct folio **foliop)
2691{
2692	struct mmu_notifier_range range;
2693	struct folio *folio, *fw_folio;
2694	struct vm_area_struct *vma;
2695	struct folio_walk fw;
2696	struct page *page;
2697	swp_entry_t entry;
2698	pte_t swp_pte;
2699	int ret;
2700
2701	mmap_assert_locked(mm);
2702	addr = PAGE_ALIGN_DOWN(addr);
2703
2704	/*
2705	 * Fault in the page writable and try to lock it; note that if the
2706	 * address would already be marked for exclusive use by a device,
2707	 * the GUP call would undo that first by triggering a fault.
2708	 *
2709	 * If any other device would already map this page exclusively, the
2710	 * fault will trigger a conversion to an ordinary
2711	 * (non-device-exclusive) PTE and issue a MMU_NOTIFY_EXCLUSIVE.
2712	 */
2713retry:
2714	page = get_user_page_vma_remote(mm, addr,
2715					FOLL_GET | FOLL_WRITE | FOLL_SPLIT_PMD,
2716					&vma);
2717	if (IS_ERR(page))
2718		return page;
2719	folio = page_folio(page);
2720
2721	if (!folio_test_anon(folio) || folio_test_hugetlb(folio)) {
2722		folio_put(folio);
2723		return ERR_PTR(-EOPNOTSUPP);
2724	}
2725
2726	ret = folio_lock_killable(folio);
2727	if (ret) {
2728		folio_put(folio);
2729		return ERR_PTR(ret);
2730	}
2731
2732	/*
2733	 * Inform secondary MMUs that we are going to convert this PTE to
2734	 * device-exclusive, such that they unmap it now. Note that the
2735	 * caller must filter this event out to prevent livelocks.
2736	 */
2737	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0,
2738				      mm, addr, addr + PAGE_SIZE, owner);
2739	mmu_notifier_invalidate_range_start(&range);
2740
2741	/*
2742	 * Let's do a second walk and make sure we still find the same page
2743	 * mapped writable. Note that any page of an anonymous folio can
2744	 * only be mapped writable using exactly one PTE ("exclusive"), so
2745	 * there cannot be other mappings.
2746	 */
2747	fw_folio = folio_walk_start(&fw, vma, addr, 0);
2748	if (fw_folio != folio || fw.page != page ||
2749	    fw.level != FW_LEVEL_PTE || !pte_write(fw.pte)) {
2750		if (fw_folio)
2751			folio_walk_end(&fw, vma);
2752		mmu_notifier_invalidate_range_end(&range);
2753		folio_unlock(folio);
2754		folio_put(folio);
2755		goto retry;
2756	}
2757
2758	/* Nuke the page table entry so we get the uptodate dirty bit. */
2759	flush_cache_page(vma, addr, page_to_pfn(page));
2760	fw.pte = ptep_clear_flush(vma, addr, fw.ptep);
2761
2762	/* Set the dirty flag on the folio now the PTE is gone. */
2763	if (pte_dirty(fw.pte))
2764		folio_mark_dirty(folio);
2765
2766	/*
2767	 * Store the pfn of the page in a special device-exclusive PFN swap PTE.
2768	 * do_swap_page() will trigger the conversion back while holding the
2769	 * folio lock.
2770	 */
2771	entry = make_device_exclusive_entry(page_to_pfn(page));
2772	swp_pte = swp_entry_to_pte(entry);
2773	if (pte_soft_dirty(fw.pte))
2774		swp_pte = pte_swp_mksoft_dirty(swp_pte);
2775	/* The pte is writable, uffd-wp does not apply. */
2776	set_pte_at(mm, addr, fw.ptep, swp_pte);
2777
2778	folio_walk_end(&fw, vma);
2779	mmu_notifier_invalidate_range_end(&range);
2780	*foliop = folio;
2781	return page;
2782}
2783EXPORT_SYMBOL_GPL(make_device_exclusive);
2784#endif
2785
2786void __put_anon_vma(struct anon_vma *anon_vma)
2787{
2788	struct anon_vma *root = anon_vma->root;
2789
2790	anon_vma_free(anon_vma);
2791	if (root != anon_vma && atomic_dec_and_test(&root->refcount))
2792		anon_vma_free(root);
2793}
2794
2795static struct anon_vma *rmap_walk_anon_lock(const struct folio *folio,
2796					    struct rmap_walk_control *rwc)
2797{
2798	struct anon_vma *anon_vma;
2799
2800	if (rwc->anon_lock)
2801		return rwc->anon_lock(folio, rwc);
2802
2803	/*
2804	 * Note: remove_migration_ptes() cannot use folio_lock_anon_vma_read()
2805	 * because that depends on page_mapped(); but not all its usages
2806	 * are holding mmap_lock. Users without mmap_lock are required to
2807	 * take a reference count to prevent the anon_vma disappearing
2808	 */
2809	anon_vma = folio_anon_vma(folio);
2810	if (!anon_vma)
2811		return NULL;
2812
2813	if (anon_vma_trylock_read(anon_vma))
2814		goto out;
2815
2816	if (rwc->try_lock) {
2817		anon_vma = NULL;
2818		rwc->contended = true;
2819		goto out;
2820	}
2821
2822	anon_vma_lock_read(anon_vma);
2823out:
2824	return anon_vma;
2825}
2826
2827/*
2828 * rmap_walk_anon - do something to anonymous page using the object-based
2829 * rmap method
2830 * @folio: the folio to be handled
2831 * @rwc: control variable according to each walk type
2832 * @locked: caller holds relevant rmap lock
2833 *
2834 * Find all the mappings of a folio using the mapping pointer and the vma
2835 * chains contained in the anon_vma struct it points to.
2836 */
2837static void rmap_walk_anon(struct folio *folio,
2838		struct rmap_walk_control *rwc, bool locked)
2839{
2840	struct anon_vma *anon_vma;
2841	pgoff_t pgoff_start, pgoff_end;
2842	struct anon_vma_chain *avc;
2843
2844	/*
2845	 * The folio lock ensures that folio->mapping can't be changed under us
2846	 * to an anon_vma with different root.
2847	 */
2848	VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
2849
2850	if (locked) {
2851		anon_vma = folio_anon_vma(folio);
2852		/* anon_vma disappear under us? */
2853		VM_BUG_ON_FOLIO(!anon_vma, folio);
2854	} else {
2855		anon_vma = rmap_walk_anon_lock(folio, rwc);
2856	}
2857	if (!anon_vma)
2858		return;
2859
2860	pgoff_start = folio_pgoff(folio);
2861	pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
2862	anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
2863			pgoff_start, pgoff_end) {
2864		struct vm_area_struct *vma = avc->vma;
2865		unsigned long address = vma_address(vma, pgoff_start,
2866				folio_nr_pages(folio));
2867
2868		VM_BUG_ON_VMA(address == -EFAULT, vma);
2869		cond_resched();
2870
2871		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2872			continue;
2873
2874		if (!rwc->rmap_one(folio, vma, address, rwc->arg))
2875			break;
2876		if (rwc->done && rwc->done(folio))
2877			break;
2878	}
2879
2880	if (!locked)
2881		anon_vma_unlock_read(anon_vma);
2882}
2883
2884/**
2885 * __rmap_walk_file() - Traverse the reverse mapping for a file-backed mapping
2886 * of a page mapped within a specified page cache object at a specified offset.
2887 *
2888 * @folio: 		Either the folio whose mappings to traverse, or if NULL,
2889 * 			the callbacks specified in @rwc will be configured such
2890 * 			as to be able to look up mappings correctly.
2891 * @mapping: 		The page cache object whose mapping VMAs we intend to
2892 * 			traverse. If @folio is non-NULL, this should be equal to
2893 *			folio_mapping(folio).
2894 * @pgoff_start:	The offset within @mapping of the page which we are
2895 * 			looking up. If @folio is non-NULL, this should be equal
2896 * 			to folio_pgoff(folio).
2897 * @nr_pages:		The number of pages mapped by the mapping. If @folio is
2898 *			non-NULL, this should be equal to folio_nr_pages(folio).
2899 * @rwc:		The reverse mapping walk control object describing how
2900 *			the traversal should proceed.
2901 * @locked:		Is the @mapping already locked? If not, we acquire the
2902 *			lock.
2903 */
2904static void __rmap_walk_file(struct folio *folio, struct address_space *mapping,
2905			     pgoff_t pgoff_start, unsigned long nr_pages,
2906			     struct rmap_walk_control *rwc, bool locked)
2907{
2908	pgoff_t pgoff_end = pgoff_start + nr_pages - 1;
2909	struct vm_area_struct *vma;
2910
2911	VM_WARN_ON_FOLIO(folio && mapping != folio_mapping(folio), folio);
2912	VM_WARN_ON_FOLIO(folio && pgoff_start != folio_pgoff(folio), folio);
2913	VM_WARN_ON_FOLIO(folio && nr_pages != folio_nr_pages(folio), folio);
2914
2915	if (!locked) {
2916		if (i_mmap_trylock_read(mapping))
2917			goto lookup;
2918
2919		if (rwc->try_lock) {
2920			rwc->contended = true;
2921			return;
2922		}
2923
2924		i_mmap_lock_read(mapping);
2925	}
2926lookup:
2927	vma_interval_tree_foreach(vma, &mapping->i_mmap,
2928			pgoff_start, pgoff_end) {
2929		unsigned long address = vma_address(vma, pgoff_start, nr_pages);
2930
2931		VM_BUG_ON_VMA(address == -EFAULT, vma);
2932		cond_resched();
2933
2934		if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2935			continue;
2936
2937		if (!rwc->rmap_one(folio, vma, address, rwc->arg))
2938			goto done;
2939		if (rwc->done && rwc->done(folio))
2940			goto done;
2941	}
2942done:
2943	if (!locked)
2944		i_mmap_unlock_read(mapping);
2945}
2946
2947/*
2948 * rmap_walk_file - do something to file page using the object-based rmap method
2949 * @folio: the folio to be handled
2950 * @rwc: control variable according to each walk type
2951 * @locked: caller holds relevant rmap lock
2952 *
2953 * Find all the mappings of a folio using the mapping pointer and the vma chains
2954 * contained in the address_space struct it points to.
2955 */
2956static void rmap_walk_file(struct folio *folio,
2957		struct rmap_walk_control *rwc, bool locked)
2958{
2959	/*
2960	 * The folio lock not only makes sure that folio->mapping cannot
2961	 * suddenly be NULLified by truncation, it makes sure that the structure
2962	 * at mapping cannot be freed and reused yet, so we can safely take
2963	 * mapping->i_mmap_rwsem.
2964	 */
2965	VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
2966
2967	if (!folio->mapping)
2968		return;
2969
2970	__rmap_walk_file(folio, folio->mapping, folio->index,
2971			 folio_nr_pages(folio), rwc, locked);
2972}
2973
2974void rmap_walk(struct folio *folio, struct rmap_walk_control *rwc)
2975{
2976	if (unlikely(folio_test_ksm(folio)))
2977		rmap_walk_ksm(folio, rwc);
2978	else if (folio_test_anon(folio))
2979		rmap_walk_anon(folio, rwc, false);
2980	else
2981		rmap_walk_file(folio, rwc, false);
2982}
2983
2984/* Like rmap_walk, but caller holds relevant rmap lock */
2985void rmap_walk_locked(struct folio *folio, struct rmap_walk_control *rwc)
2986{
2987	/* no ksm support for now */
2988	VM_BUG_ON_FOLIO(folio_test_ksm(folio), folio);
2989	if (folio_test_anon(folio))
2990		rmap_walk_anon(folio, rwc, true);
2991	else
2992		rmap_walk_file(folio, rwc, true);
2993}
2994
2995#ifdef CONFIG_HUGETLB_PAGE
2996/*
2997 * The following two functions are for anonymous (private mapped) hugepages.
2998 * Unlike common anonymous pages, anonymous hugepages have no accounting code
2999 * and no lru code, because we handle hugepages differently from common pages.
3000 */
3001void hugetlb_add_anon_rmap(struct folio *folio, struct vm_area_struct *vma,
3002		unsigned long address, rmap_t flags)
3003{
3004	VM_WARN_ON_FOLIO(!folio_test_hugetlb(folio), folio);
3005	VM_WARN_ON_FOLIO(!folio_test_anon(folio), folio);
3006
3007	atomic_inc(&folio->_entire_mapcount);
3008	atomic_inc(&folio->_large_mapcount);
3009	if (flags & RMAP_EXCLUSIVE)
3010		SetPageAnonExclusive(&folio->page);
3011	VM_WARN_ON_FOLIO(folio_entire_mapcount(folio) > 1 &&
3012			 PageAnonExclusive(&folio->page), folio);
3013}
3014
3015void hugetlb_add_new_anon_rmap(struct folio *folio,
3016		struct vm_area_struct *vma, unsigned long address)
3017{
3018	VM_WARN_ON_FOLIO(!folio_test_hugetlb(folio), folio);
3019
3020	BUG_ON(address < vma->vm_start || address >= vma->vm_end);
3021	/* increment count (starts at -1) */
3022	atomic_set(&folio->_entire_mapcount, 0);
3023	atomic_set(&folio->_large_mapcount, 0);
3024	folio_clear_hugetlb_restore_reserve(folio);
3025	__folio_set_anon(folio, vma, address, true);
3026	SetPageAnonExclusive(&folio->page);
3027}
3028#endif /* CONFIG_HUGETLB_PAGE */
~/ Read-only file preview.