]> git.proxmox.com Git - mirror_ubuntu-kernels.git/blame - mm/rmap.c
Merge tag 'rpmsg-v6.1' of git://git.kernel.org/pub/scm/linux/kernel/git/remoteproc...
[mirror_ubuntu-kernels.git] / mm / rmap.c
CommitLineData
1da177e4
LT
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
98f32602 17 * Contributions by Hugh Dickins 2003, 2004
1da177e4
LT
18 */
19
20/*
21 * Lock ordering in mm:
22 *
9608703e 23 * inode->i_rwsem (while writing or truncating, not reading or faulting)
c1e8d7c6 24 * mm->mmap_lock
730633f0
JK
25 * mapping->invalidate_lock (in filemap_fault)
26 * page->flags PG_locked (lock_page) * (see hugetlbfs below)
27 * hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share)
28 * mapping->i_mmap_rwsem
29 * hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
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)
e621900a
MWO
34 * mapping->private_lock (in block_dirty_folio)
35 * folio_lock_memcg move_lock (in block_dirty_folio)
730633f0 36 * i_pages lock (widely used)
e809c3fe 37 * lruvec->lru_lock (in folio_lruvec_lock_irq)
730633f0
JK
38 * inode->i_lock (in set_page_dirty's __mark_inode_dirty)
39 * bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
40 * sb_lock (within inode_lock in fs/fs-writeback.c)
41 * i_pages lock (widely used, in set_page_dirty,
42 * in arch-dependent flush_dcache_mmap_lock,
43 * within bdi.wb->list_lock in __sync_single_inode)
6a46079c 44 *
9608703e 45 * anon_vma->rwsem,mapping->i_mmap_rwsem (memory_failure, collect_procs_anon)
9b679320 46 * ->tasklist_lock
6a46079c 47 * pte map lock
c0d0381a
MK
48 *
49 * * hugetlbfs PageHuge() pages take locks in this order:
50 * mapping->i_mmap_rwsem
51 * hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
52 * page->flags PG_locked (lock_page)
1da177e4
LT
53 */
54
55#include <linux/mm.h>
6e84f315 56#include <linux/sched/mm.h>
29930025 57#include <linux/sched/task.h>
1da177e4
LT
58#include <linux/pagemap.h>
59#include <linux/swap.h>
60#include <linux/swapops.h>
61#include <linux/slab.h>
62#include <linux/init.h>
5ad64688 63#include <linux/ksm.h>
1da177e4
LT
64#include <linux/rmap.h>
65#include <linux/rcupdate.h>
b95f1b31 66#include <linux/export.h>
8a9f3ccd 67#include <linux/memcontrol.h>
cddb8a5c 68#include <linux/mmu_notifier.h>
64cdd548 69#include <linux/migrate.h>
0fe6e20b 70#include <linux/hugetlb.h>
444f84fd 71#include <linux/huge_mm.h>
ef5d437f 72#include <linux/backing-dev.h>
33c3fc71 73#include <linux/page_idle.h>
a5430dda 74#include <linux/memremap.h>
bce73e48 75#include <linux/userfaultfd_k.h>
999dad82 76#include <linux/mm_inline.h>
1da177e4
LT
77
78#include <asm/tlbflush.h>
79
4cc79b33 80#define CREATE_TRACE_POINTS
72b252ae 81#include <trace/events/tlb.h>
4cc79b33 82#include <trace/events/migrate.h>
72b252ae 83
b291f000
NP
84#include "internal.h"
85
fdd2e5f8 86static struct kmem_cache *anon_vma_cachep;
5beb4930 87static struct kmem_cache *anon_vma_chain_cachep;
fdd2e5f8
AB
88
89static inline struct anon_vma *anon_vma_alloc(void)
90{
01d8b20d
PZ
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);
2555283e
JH
96 anon_vma->num_children = 0;
97 anon_vma->num_active_vmas = 0;
7a3ef208 98 anon_vma->parent = anon_vma;
01d8b20d
PZ
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;
fdd2e5f8
AB
107}
108
01d8b20d 109static inline void anon_vma_free(struct anon_vma *anon_vma)
fdd2e5f8 110{
01d8b20d 111 VM_BUG_ON(atomic_read(&anon_vma->refcount));
88c22088
PZ
112
113 /*
2f031c6f 114 * Synchronize against folio_lock_anon_vma_read() such that
88c22088
PZ
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
2f031c6f 120 * down_read_trylock() from folio_lock_anon_vma_read(). This orders:
88c22088 121 *
2f031c6f 122 * folio_lock_anon_vma_read() VS put_anon_vma()
4fc3f1d6 123 * down_read_trylock() atomic_dec_and_test()
88c22088 124 * LOCK MB
4fc3f1d6 125 * atomic_read() rwsem_is_locked()
88c22088
PZ
126 *
127 * LOCK should suffice since the actual taking of the lock must
128 * happen _before_ what follows.
129 */
7f39dda9 130 might_sleep();
5a505085 131 if (rwsem_is_locked(&anon_vma->root->rwsem)) {
4fc3f1d6 132 anon_vma_lock_write(anon_vma);
08b52706 133 anon_vma_unlock_write(anon_vma);
88c22088
PZ
134 }
135
fdd2e5f8
AB
136 kmem_cache_free(anon_vma_cachep, anon_vma);
137}
1da177e4 138
dd34739c 139static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
5beb4930 140{
dd34739c 141 return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
5beb4930
RR
142}
143
e574b5fd 144static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
5beb4930
RR
145{
146 kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
147}
148
6583a843
KC
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);
bf181b9f 156 anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
6583a843
KC
157}
158
d9d332e0 159/**
d5a187da 160 * __anon_vma_prepare - attach an anon_vma to a memory region
d9d332e0
LT
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 *
d5a187da
VB
167 * The common case will be that we already have one, which
168 * is handled inline by anon_vma_prepare(). But if
23a0790a 169 * not we either need to find an adjacent mapping that we
d9d332e0
LT
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
2f031c6f 175 * optimistically looked up an anon_vma in folio_lock_anon_vma_read()
aaf1f990 176 * and that may actually touch the rwsem even in the newly
d9d332e0
LT
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 *
c1e8d7c6 185 * This must be called with the mmap_lock held for reading.
d9d332e0 186 */
d5a187da 187int __anon_vma_prepare(struct vm_area_struct *vma)
1da177e4 188{
d5a187da
VB
189 struct mm_struct *mm = vma->vm_mm;
190 struct anon_vma *anon_vma, *allocated;
5beb4930 191 struct anon_vma_chain *avc;
1da177e4
LT
192
193 might_sleep();
1da177e4 194
d5a187da
VB
195 avc = anon_vma_chain_alloc(GFP_KERNEL);
196 if (!avc)
197 goto out_enomem;
198
199 anon_vma = find_mergeable_anon_vma(vma);
200 allocated = NULL;
201 if (!anon_vma) {
202 anon_vma = anon_vma_alloc();
203 if (unlikely(!anon_vma))
204 goto out_enomem_free_avc;
2555283e 205 anon_vma->num_children++; /* self-parent link for new root */
d5a187da
VB
206 allocated = anon_vma;
207 }
5beb4930 208
d5a187da
VB
209 anon_vma_lock_write(anon_vma);
210 /* page_table_lock to protect against threads */
211 spin_lock(&mm->page_table_lock);
212 if (likely(!vma->anon_vma)) {
213 vma->anon_vma = anon_vma;
214 anon_vma_chain_link(vma, avc, anon_vma);
2555283e 215 anon_vma->num_active_vmas++;
d9d332e0 216 allocated = NULL;
d5a187da
VB
217 avc = NULL;
218 }
219 spin_unlock(&mm->page_table_lock);
220 anon_vma_unlock_write(anon_vma);
1da177e4 221
d5a187da
VB
222 if (unlikely(allocated))
223 put_anon_vma(allocated);
224 if (unlikely(avc))
225 anon_vma_chain_free(avc);
31f2b0eb 226
1da177e4 227 return 0;
5beb4930
RR
228
229 out_enomem_free_avc:
230 anon_vma_chain_free(avc);
231 out_enomem:
232 return -ENOMEM;
1da177e4
LT
233}
234
bb4aa396
LT
235/*
236 * This is a useful helper function for locking the anon_vma root as
237 * we traverse the vma->anon_vma_chain, looping over anon_vma's that
238 * have the same vma.
239 *
240 * Such anon_vma's should have the same root, so you'd expect to see
241 * just a single mutex_lock for the whole traversal.
242 */
243static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
244{
245 struct anon_vma *new_root = anon_vma->root;
246 if (new_root != root) {
247 if (WARN_ON_ONCE(root))
5a505085 248 up_write(&root->rwsem);
bb4aa396 249 root = new_root;
5a505085 250 down_write(&root->rwsem);
bb4aa396
LT
251 }
252 return root;
253}
254
255static inline void unlock_anon_vma_root(struct anon_vma *root)
256{
257 if (root)
5a505085 258 up_write(&root->rwsem);
bb4aa396
LT
259}
260
5beb4930
RR
261/*
262 * Attach the anon_vmas from src to dst.
263 * Returns 0 on success, -ENOMEM on failure.
7a3ef208 264 *
cb152a1a 265 * anon_vma_clone() is called by __vma_adjust(), __split_vma(), copy_vma() and
47b390d2
WY
266 * anon_vma_fork(). The first three want an exact copy of src, while the last
267 * one, anon_vma_fork(), may try to reuse an existing anon_vma to prevent
268 * endless growth of anon_vma. Since dst->anon_vma is set to NULL before call,
269 * we can identify this case by checking (!dst->anon_vma && 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.
5beb4930
RR
278 */
279int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
1da177e4 280{
5beb4930 281 struct anon_vma_chain *avc, *pavc;
bb4aa396 282 struct anon_vma *root = NULL;
5beb4930 283
646d87b4 284 list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
bb4aa396
LT
285 struct anon_vma *anon_vma;
286
dd34739c
LT
287 avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
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 }
bb4aa396
LT
295 anon_vma = pavc->anon_vma;
296 root = lock_anon_vma_root(root, anon_vma);
297 anon_vma_chain_link(dst, avc, anon_vma);
7a3ef208
KK
298
299 /*
2555283e
JH
300 * Reuse existing anon_vma if it has no vma and only one
301 * anon_vma child.
7a3ef208 302 *
2555283e 303 * Root anon_vma is never reused:
7a3ef208
KK
304 * it has self-parent reference and at least one child.
305 */
47b390d2 306 if (!dst->anon_vma && src->anon_vma &&
2555283e
JH
307 anon_vma->num_children < 2 &&
308 anon_vma->num_active_vmas == 0)
7a3ef208 309 dst->anon_vma = anon_vma;
5beb4930 310 }
7a3ef208 311 if (dst->anon_vma)
2555283e 312 dst->anon_vma->num_active_vmas++;
bb4aa396 313 unlock_anon_vma_root(root);
5beb4930 314 return 0;
1da177e4 315
5beb4930 316 enomem_failure:
3fe89b3e
LY
317 /*
318 * dst->anon_vma is dropped here otherwise its degree can be incorrectly
319 * 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;
5beb4930
RR
324 unlink_anon_vmas(dst);
325 return -ENOMEM;
1da177e4
LT
326}
327
5beb4930
RR
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)
1da177e4 334{
5beb4930
RR
335 struct anon_vma_chain *avc;
336 struct anon_vma *anon_vma;
c4ea95d7 337 int error;
1da177e4 338
5beb4930
RR
339 /* Don't bother if the parent process has no anon_vma here. */
340 if (!pvma->anon_vma)
341 return 0;
342
7a3ef208
KK
343 /* Drop inherited anon_vma, we'll reuse existing or allocate new. */
344 vma->anon_vma = NULL;
345
5beb4930
RR
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 */
c4ea95d7
DF
350 error = anon_vma_clone(vma, pvma);
351 if (error)
352 return error;
5beb4930 353
7a3ef208
KK
354 /* An existing anon_vma has been reused, all done then. */
355 if (vma->anon_vma)
356 return 0;
357
5beb4930
RR
358 /* Then add our own anon_vma. */
359 anon_vma = anon_vma_alloc();
360 if (!anon_vma)
361 goto out_error;
2555283e 362 anon_vma->num_active_vmas++;
dd34739c 363 avc = anon_vma_chain_alloc(GFP_KERNEL);
5beb4930
RR
364 if (!avc)
365 goto out_error_free_anon_vma;
5c341ee1
RR
366
367 /*
aaf1f990 368 * The root anon_vma's rwsem is the lock actually used when we
5c341ee1
RR
369 * lock any of the anon_vmas in this anon_vma tree.
370 */
371 anon_vma->root = pvma->anon_vma->root;
7a3ef208 372 anon_vma->parent = pvma->anon_vma;
76545066 373 /*
01d8b20d
PZ
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.
76545066
RR
377 */
378 get_anon_vma(anon_vma->root);
5beb4930
RR
379 /* Mark this anon_vma as the one where our new (COWed) pages go. */
380 vma->anon_vma = anon_vma;
4fc3f1d6 381 anon_vma_lock_write(anon_vma);
5c341ee1 382 anon_vma_chain_link(vma, avc, anon_vma);
2555283e 383 anon_vma->parent->num_children++;
08b52706 384 anon_vma_unlock_write(anon_vma);
5beb4930
RR
385
386 return 0;
387
388 out_error_free_anon_vma:
01d8b20d 389 put_anon_vma(anon_vma);
5beb4930 390 out_error:
4946d54c 391 unlink_anon_vmas(vma);
5beb4930 392 return -ENOMEM;
1da177e4
LT
393}
394
5beb4930
RR
395void unlink_anon_vmas(struct vm_area_struct *vma)
396{
397 struct anon_vma_chain *avc, *next;
eee2acba 398 struct anon_vma *root = NULL;
5beb4930 399
5c341ee1
RR
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 */
5beb4930 404 list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
eee2acba
PZ
405 struct anon_vma *anon_vma = avc->anon_vma;
406
407 root = lock_anon_vma_root(root, anon_vma);
bf181b9f 408 anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
eee2acba
PZ
409
410 /*
411 * Leave empty anon_vmas on the list - we'll need
412 * to free them outside the lock.
413 */
f808c13f 414 if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
2555283e 415 anon_vma->parent->num_children--;
eee2acba 416 continue;
7a3ef208 417 }
eee2acba
PZ
418
419 list_del(&avc->same_vma);
420 anon_vma_chain_free(avc);
421 }
ee8ab190 422 if (vma->anon_vma) {
2555283e 423 vma->anon_vma->num_active_vmas--;
ee8ab190
LX
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 }
eee2acba
PZ
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()
5a505085 436 * needing to write-acquire the anon_vma->root->rwsem.
eee2acba
PZ
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
2555283e
JH
441 VM_WARN_ON(anon_vma->num_children);
442 VM_WARN_ON(anon_vma->num_active_vmas);
eee2acba
PZ
443 put_anon_vma(anon_vma);
444
5beb4930
RR
445 list_del(&avc->same_vma);
446 anon_vma_chain_free(avc);
447 }
448}
449
51cc5068 450static void anon_vma_ctor(void *data)
1da177e4 451{
a35afb83 452 struct anon_vma *anon_vma = data;
1da177e4 453
5a505085 454 init_rwsem(&anon_vma->rwsem);
83813267 455 atomic_set(&anon_vma->refcount, 0);
f808c13f 456 anon_vma->rb_root = RB_ROOT_CACHED;
1da177e4
LT
457}
458
459void __init anon_vma_init(void)
460{
461 anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
5f0d5a3a 462 0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
5d097056
VD
463 anon_vma_ctor);
464 anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
465 SLAB_PANIC|SLAB_ACCOUNT);
1da177e4
LT
466}
467
468/*
6111e4ca
PZ
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 page_remove_rmap()
ad8a20cf
ML
472 * the best this function can do is return a refcount increased anon_vma
473 * that might have been relevant to this page.
6111e4ca
PZ
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 *
bc658c96
PZ
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 *
6111e4ca
PZ
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 *
091e4299
MC
487 * Since anon_vma's slab is SLAB_TYPESAFE_BY_RCU and we know from
488 * page_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.
1da177e4 491 */
746b18d4 492struct anon_vma *page_get_anon_vma(struct page *page)
1da177e4 493{
746b18d4 494 struct anon_vma *anon_vma = NULL;
1da177e4
LT
495 unsigned long anon_mapping;
496
497 rcu_read_lock();
4db0c3c2 498 anon_mapping = (unsigned long)READ_ONCE(page->mapping);
3ca7b3c5 499 if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
1da177e4
LT
500 goto out;
501 if (!page_mapped(page))
502 goto out;
503
504 anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
746b18d4
PZ
505 if (!atomic_inc_not_zero(&anon_vma->refcount)) {
506 anon_vma = NULL;
507 goto out;
508 }
f1819427
HD
509
510 /*
511 * If this page is still mapped, then its anon_vma cannot have been
746b18d4
PZ
512 * freed. But if it has been unmapped, we have no security against the
513 * anon_vma structure being freed and reused (for another anon_vma:
5f0d5a3a 514 * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
746b18d4 515 * above cannot corrupt).
f1819427 516 */
746b18d4 517 if (!page_mapped(page)) {
7f39dda9 518 rcu_read_unlock();
746b18d4 519 put_anon_vma(anon_vma);
7f39dda9 520 return NULL;
746b18d4 521 }
1da177e4
LT
522out:
523 rcu_read_unlock();
746b18d4
PZ
524
525 return anon_vma;
526}
527
88c22088
PZ
528/*
529 * Similar to page_get_anon_vma() except it locks the anon_vma.
530 *
531 * Its a little more complex as it tries to keep the fast path to a single
532 * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
6d4675e6
MK
533 * reference like with page_get_anon_vma() and then block on the mutex
534 * on !rwc->try_lock case.
88c22088 535 */
6d4675e6
MK
536struct anon_vma *folio_lock_anon_vma_read(struct folio *folio,
537 struct rmap_walk_control *rwc)
746b18d4 538{
88c22088 539 struct anon_vma *anon_vma = NULL;
eee0f252 540 struct anon_vma *root_anon_vma;
88c22088 541 unsigned long anon_mapping;
746b18d4 542
88c22088 543 rcu_read_lock();
9595d769 544 anon_mapping = (unsigned long)READ_ONCE(folio->mapping);
88c22088
PZ
545 if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
546 goto out;
9595d769 547 if (!folio_mapped(folio))
88c22088
PZ
548 goto out;
549
550 anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
4db0c3c2 551 root_anon_vma = READ_ONCE(anon_vma->root);
4fc3f1d6 552 if (down_read_trylock(&root_anon_vma->rwsem)) {
88c22088 553 /*
9595d769 554 * If the folio is still mapped, then this anon_vma is still
eee0f252 555 * its anon_vma, and holding the mutex ensures that it will
bc658c96 556 * not go away, see anon_vma_free().
88c22088 557 */
9595d769 558 if (!folio_mapped(folio)) {
4fc3f1d6 559 up_read(&root_anon_vma->rwsem);
88c22088
PZ
560 anon_vma = NULL;
561 }
562 goto out;
563 }
746b18d4 564
6d4675e6
MK
565 if (rwc && rwc->try_lock) {
566 anon_vma = NULL;
567 rwc->contended = true;
568 goto out;
569 }
570
88c22088
PZ
571 /* trylock failed, we got to sleep */
572 if (!atomic_inc_not_zero(&anon_vma->refcount)) {
573 anon_vma = NULL;
574 goto out;
575 }
576
9595d769 577 if (!folio_mapped(folio)) {
7f39dda9 578 rcu_read_unlock();
88c22088 579 put_anon_vma(anon_vma);
7f39dda9 580 return NULL;
88c22088
PZ
581 }
582
583 /* we pinned the anon_vma, its safe to sleep */
584 rcu_read_unlock();
4fc3f1d6 585 anon_vma_lock_read(anon_vma);
88c22088
PZ
586
587 if (atomic_dec_and_test(&anon_vma->refcount)) {
588 /*
589 * Oops, we held the last refcount, release the lock
590 * and bail -- can't simply use put_anon_vma() because
4fc3f1d6 591 * we'll deadlock on the anon_vma_lock_write() recursion.
88c22088 592 */
4fc3f1d6 593 anon_vma_unlock_read(anon_vma);
88c22088
PZ
594 __put_anon_vma(anon_vma);
595 anon_vma = NULL;
596 }
597
598 return anon_vma;
599
600out:
601 rcu_read_unlock();
746b18d4 602 return anon_vma;
34bbd704
ON
603}
604
4fc3f1d6 605void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
34bbd704 606{
4fc3f1d6 607 anon_vma_unlock_read(anon_vma);
1da177e4
LT
608}
609
72b252ae 610#ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
72b252ae
MG
611/*
612 * Flush TLB entries for recently unmapped pages from remote CPUs. It is
613 * important if a PTE was dirty when it was unmapped that it's flushed
614 * before any IO is initiated on the page to prevent lost writes. Similarly,
615 * it must be flushed before freeing to prevent data leakage.
616 */
617void try_to_unmap_flush(void)
618{
619 struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
72b252ae
MG
620
621 if (!tlb_ubc->flush_required)
622 return;
623
e73ad5ff 624 arch_tlbbatch_flush(&tlb_ubc->arch);
72b252ae 625 tlb_ubc->flush_required = false;
d950c947 626 tlb_ubc->writable = false;
72b252ae
MG
627}
628
d950c947
MG
629/* Flush iff there are potentially writable TLB entries that can race with IO */
630void try_to_unmap_flush_dirty(void)
631{
632 struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
633
634 if (tlb_ubc->writable)
635 try_to_unmap_flush();
636}
637
5ee2fa2f
HY
638/*
639 * Bits 0-14 of mm->tlb_flush_batched record pending generations.
640 * Bits 16-30 of mm->tlb_flush_batched bit record flushed generations.
641 */
642#define TLB_FLUSH_BATCH_FLUSHED_SHIFT 16
643#define TLB_FLUSH_BATCH_PENDING_MASK \
644 ((1 << (TLB_FLUSH_BATCH_FLUSHED_SHIFT - 1)) - 1)
645#define TLB_FLUSH_BATCH_PENDING_LARGE \
646 (TLB_FLUSH_BATCH_PENDING_MASK / 2)
647
c7ab0d2f 648static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
72b252ae
MG
649{
650 struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
5ee2fa2f 651 int batch, nbatch;
72b252ae 652
e73ad5ff 653 arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
72b252ae 654 tlb_ubc->flush_required = true;
d950c947 655
3ea27719
MG
656 /*
657 * Ensure compiler does not re-order the setting of tlb_flush_batched
658 * before the PTE is cleared.
659 */
660 barrier();
5ee2fa2f
HY
661 batch = atomic_read(&mm->tlb_flush_batched);
662retry:
663 if ((batch & TLB_FLUSH_BATCH_PENDING_MASK) > TLB_FLUSH_BATCH_PENDING_LARGE) {
664 /*
665 * Prevent `pending' from catching up with `flushed' because of
666 * overflow. Reset `pending' and `flushed' to be 1 and 0 if
667 * `pending' becomes large.
668 */
669 nbatch = atomic_cmpxchg(&mm->tlb_flush_batched, batch, 1);
670 if (nbatch != batch) {
671 batch = nbatch;
672 goto retry;
673 }
674 } else {
675 atomic_inc(&mm->tlb_flush_batched);
676 }
3ea27719 677
d950c947
MG
678 /*
679 * If the PTE was dirty then it's best to assume it's writable. The
680 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
681 * before the page is queued for IO.
682 */
683 if (writable)
684 tlb_ubc->writable = true;
72b252ae
MG
685}
686
687/*
688 * Returns true if the TLB flush should be deferred to the end of a batch of
689 * unmap operations to reduce IPIs.
690 */
691static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
692{
693 bool should_defer = false;
694
695 if (!(flags & TTU_BATCH_FLUSH))
696 return false;
697
698 /* If remote CPUs need to be flushed then defer batch the flush */
699 if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
700 should_defer = true;
701 put_cpu();
702
703 return should_defer;
704}
3ea27719
MG
705
706/*
707 * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
708 * releasing the PTL if TLB flushes are batched. It's possible for a parallel
709 * operation such as mprotect or munmap to race between reclaim unmapping
710 * the page and flushing the page. If this race occurs, it potentially allows
711 * access to data via a stale TLB entry. Tracking all mm's that have TLB
712 * batching in flight would be expensive during reclaim so instead track
713 * whether TLB batching occurred in the past and if so then do a flush here
714 * if required. This will cost one additional flush per reclaim cycle paid
715 * by the first operation at risk such as mprotect and mumap.
716 *
717 * This must be called under the PTL so that an access to tlb_flush_batched
718 * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
719 * via the PTL.
720 */
721void flush_tlb_batched_pending(struct mm_struct *mm)
722{
5ee2fa2f
HY
723 int batch = atomic_read(&mm->tlb_flush_batched);
724 int pending = batch & TLB_FLUSH_BATCH_PENDING_MASK;
725 int flushed = batch >> TLB_FLUSH_BATCH_FLUSHED_SHIFT;
3ea27719 726
5ee2fa2f
HY
727 if (pending != flushed) {
728 flush_tlb_mm(mm);
3ea27719 729 /*
5ee2fa2f
HY
730 * If the new TLB flushing is pending during flushing, leave
731 * mm->tlb_flush_batched as is, to avoid losing flushing.
3ea27719 732 */
5ee2fa2f
HY
733 atomic_cmpxchg(&mm->tlb_flush_batched, batch,
734 pending | (pending << TLB_FLUSH_BATCH_FLUSHED_SHIFT));
3ea27719
MG
735 }
736}
72b252ae 737#else
c7ab0d2f 738static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
72b252ae
MG
739{
740}
741
742static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
743{
744 return false;
745}
746#endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
747
1da177e4 748/*
bf89c8c8 749 * At what user virtual address is page expected in vma?
ab941e0f 750 * Caller should check the page is actually part of the vma.
1da177e4
LT
751 */
752unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
753{
e05b3453
MWO
754 struct folio *folio = page_folio(page);
755 if (folio_test_anon(folio)) {
756 struct anon_vma *page__anon_vma = folio_anon_vma(folio);
4829b906
HD
757 /*
758 * Note: swapoff's unuse_vma() is more efficient with this
759 * check, and needs it to match anon_vma when KSM is active.
760 */
761 if (!vma->anon_vma || !page__anon_vma ||
762 vma->anon_vma->root != page__anon_vma->root)
21d0d443 763 return -EFAULT;
31657170
JW
764 } else if (!vma->vm_file) {
765 return -EFAULT;
e05b3453 766 } else if (vma->vm_file->f_mapping != folio->mapping) {
1da177e4 767 return -EFAULT;
31657170 768 }
494334e4
HD
769
770 return vma_address(page, vma);
1da177e4
LT
771}
772
6219049a
BL
773pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
774{
775 pgd_t *pgd;
c2febafc 776 p4d_t *p4d;
6219049a
BL
777 pud_t *pud;
778 pmd_t *pmd = NULL;
f72e7dcd 779 pmd_t pmde;
6219049a
BL
780
781 pgd = pgd_offset(mm, address);
782 if (!pgd_present(*pgd))
783 goto out;
784
c2febafc
KS
785 p4d = p4d_offset(pgd, address);
786 if (!p4d_present(*p4d))
787 goto out;
788
789 pud = pud_offset(p4d, address);
6219049a
BL
790 if (!pud_present(*pud))
791 goto out;
792
793 pmd = pmd_offset(pud, address);
f72e7dcd 794 /*
8809aa2d 795 * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
f72e7dcd
HD
796 * without holding anon_vma lock for write. So when looking for a
797 * genuine pmde (in which to find pte), test present and !THP together.
798 */
e37c6982
CB
799 pmde = *pmd;
800 barrier();
f72e7dcd 801 if (!pmd_present(pmde) || pmd_trans_huge(pmde))
6219049a
BL
802 pmd = NULL;
803out:
804 return pmd;
805}
806
b3ac0413 807struct folio_referenced_arg {
8749cfea
VD
808 int mapcount;
809 int referenced;
810 unsigned long vm_flags;
811 struct mem_cgroup *memcg;
812};
813/*
b3ac0413 814 * arg: folio_referenced_arg will be passed
8749cfea 815 */
2f031c6f
MWO
816static bool folio_referenced_one(struct folio *folio,
817 struct vm_area_struct *vma, unsigned long address, void *arg)
8749cfea 818{
b3ac0413
MWO
819 struct folio_referenced_arg *pra = arg;
820 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
8749cfea
VD
821 int referenced = 0;
822
8eaedede
KS
823 while (page_vma_mapped_walk(&pvmw)) {
824 address = pvmw.address;
b20ce5e0 825
47d4f3ee 826 if ((vma->vm_flags & VM_LOCKED) &&
b3ac0413 827 (!folio_test_large(folio) || !pvmw.pte)) {
47d4f3ee 828 /* Restore the mlock which got missed */
b3ac0413 829 mlock_vma_folio(folio, vma, !pvmw.pte);
8eaedede
KS
830 page_vma_mapped_walk_done(&pvmw);
831 pra->vm_flags |= VM_LOCKED;
e4b82222 832 return false; /* To break the loop */
8eaedede 833 }
71e3aac0 834
8eaedede
KS
835 if (pvmw.pte) {
836 if (ptep_clear_flush_young_notify(vma, address,
837 pvmw.pte)) {
838 /*
839 * Don't treat a reference through
840 * a sequentially read mapping as such.
b3ac0413 841 * If the folio has been used in another mapping,
8eaedede
KS
842 * we will catch it; if this other mapping is
843 * already gone, the unmap path will have set
b3ac0413 844 * the referenced flag or activated the folio.
8eaedede
KS
845 */
846 if (likely(!(vma->vm_flags & VM_SEQ_READ)))
847 referenced++;
848 }
849 } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
850 if (pmdp_clear_flush_young_notify(vma, address,
851 pvmw.pmd))
8749cfea 852 referenced++;
8eaedede 853 } else {
b3ac0413 854 /* unexpected pmd-mapped folio? */
8eaedede 855 WARN_ON_ONCE(1);
8749cfea 856 }
8eaedede
KS
857
858 pra->mapcount--;
b20ce5e0 859 }
b20ce5e0 860
33c3fc71 861 if (referenced)
b3ac0413
MWO
862 folio_clear_idle(folio);
863 if (folio_test_clear_young(folio))
33c3fc71
VD
864 referenced++;
865
9f32624b
JK
866 if (referenced) {
867 pra->referenced++;
47d4f3ee 868 pra->vm_flags |= vma->vm_flags & ~VM_LOCKED;
1da177e4 869 }
34bbd704 870
9f32624b 871 if (!pra->mapcount)
e4b82222 872 return false; /* To break the loop */
9f32624b 873
e4b82222 874 return true;
1da177e4
LT
875}
876
b3ac0413 877static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
1da177e4 878{
b3ac0413 879 struct folio_referenced_arg *pra = arg;
9f32624b 880 struct mem_cgroup *memcg = pra->memcg;
1da177e4 881
9f32624b
JK
882 if (!mm_match_cgroup(vma->vm_mm, memcg))
883 return true;
1da177e4 884
9f32624b 885 return false;
1da177e4
LT
886}
887
888/**
b3ac0413
MWO
889 * folio_referenced() - Test if the folio was referenced.
890 * @folio: The folio to test.
891 * @is_locked: Caller holds lock on the folio.
72835c86 892 * @memcg: target memory cgroup
b3ac0413 893 * @vm_flags: A combination of all the vma->vm_flags which referenced the folio.
1da177e4 894 *
b3ac0413
MWO
895 * Quick test_and_clear_referenced for all mappings of a folio,
896 *
6d4675e6
MK
897 * Return: The number of mappings which referenced the folio. Return -1 if
898 * the function bailed out due to rmap lock contention.
1da177e4 899 */
b3ac0413
MWO
900int folio_referenced(struct folio *folio, int is_locked,
901 struct mem_cgroup *memcg, unsigned long *vm_flags)
1da177e4 902{
5ad64688 903 int we_locked = 0;
b3ac0413
MWO
904 struct folio_referenced_arg pra = {
905 .mapcount = folio_mapcount(folio),
9f32624b
JK
906 .memcg = memcg,
907 };
908 struct rmap_walk_control rwc = {
b3ac0413 909 .rmap_one = folio_referenced_one,
9f32624b 910 .arg = (void *)&pra,
2f031c6f 911 .anon_lock = folio_lock_anon_vma_read,
6d4675e6 912 .try_lock = true,
9f32624b 913 };
1da177e4 914
6fe6b7e3 915 *vm_flags = 0;
059d8442 916 if (!pra.mapcount)
9f32624b
JK
917 return 0;
918
b3ac0413 919 if (!folio_raw_mapping(folio))
9f32624b
JK
920 return 0;
921
b3ac0413
MWO
922 if (!is_locked && (!folio_test_anon(folio) || folio_test_ksm(folio))) {
923 we_locked = folio_trylock(folio);
9f32624b
JK
924 if (!we_locked)
925 return 1;
1da177e4 926 }
9f32624b
JK
927
928 /*
929 * If we are reclaiming on behalf of a cgroup, skip
930 * counting on behalf of references from different
931 * cgroups
932 */
933 if (memcg) {
b3ac0413 934 rwc.invalid_vma = invalid_folio_referenced_vma;
9f32624b
JK
935 }
936
2f031c6f 937 rmap_walk(folio, &rwc);
9f32624b
JK
938 *vm_flags = pra.vm_flags;
939
940 if (we_locked)
b3ac0413 941 folio_unlock(folio);
9f32624b 942
6d4675e6 943 return rwc.contended ? -1 : pra.referenced;
1da177e4
LT
944}
945
6a8e0596 946static int page_vma_mkclean_one(struct page_vma_mapped_walk *pvmw)
d08b3851 947{
6a8e0596
MS
948 int cleaned = 0;
949 struct vm_area_struct *vma = pvmw->vma;
ac46d4f3 950 struct mmu_notifier_range range;
6a8e0596 951 unsigned long address = pvmw->address;
d08b3851 952
369ea824
JG
953 /*
954 * We have to assume the worse case ie pmd for invalidation. Note that
e83c09a2 955 * the folio can not be freed from this function.
369ea824 956 */
7269f999
JG
957 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
958 0, vma, vma->vm_mm, address,
6a8e0596 959 vma_address_end(pvmw));
ac46d4f3 960 mmu_notifier_invalidate_range_start(&range);
369ea824 961
6a8e0596 962 while (page_vma_mapped_walk(pvmw)) {
f27176cf 963 int ret = 0;
369ea824 964
6a8e0596
MS
965 address = pvmw->address;
966 if (pvmw->pte) {
f27176cf 967 pte_t entry;
6a8e0596 968 pte_t *pte = pvmw->pte;
f27176cf
KS
969
970 if (!pte_dirty(*pte) && !pte_write(*pte))
971 continue;
972
785373b4
LT
973 flush_cache_page(vma, address, pte_pfn(*pte));
974 entry = ptep_clear_flush(vma, address, pte);
f27176cf
KS
975 entry = pte_wrprotect(entry);
976 entry = pte_mkclean(entry);
785373b4 977 set_pte_at(vma->vm_mm, address, pte, entry);
f27176cf
KS
978 ret = 1;
979 } else {
396bcc52 980#ifdef CONFIG_TRANSPARENT_HUGEPAGE
6a8e0596 981 pmd_t *pmd = pvmw->pmd;
f27176cf
KS
982 pmd_t entry;
983
984 if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
985 continue;
986
7f9c9b60
MS
987 flush_cache_range(vma, address,
988 address + HPAGE_PMD_SIZE);
024eee0e 989 entry = pmdp_invalidate(vma, address, pmd);
f27176cf
KS
990 entry = pmd_wrprotect(entry);
991 entry = pmd_mkclean(entry);
785373b4 992 set_pmd_at(vma->vm_mm, address, pmd, entry);
f27176cf
KS
993 ret = 1;
994#else
e83c09a2 995 /* unexpected pmd-mapped folio? */
f27176cf
KS
996 WARN_ON_ONCE(1);
997#endif
998 }
d08b3851 999
0f10851e
JG
1000 /*
1001 * No need to call mmu_notifier_invalidate_range() as we are
1002 * downgrading page table protection not changing it to point
1003 * to a new page.
1004 *
ee65728e 1005 * See Documentation/mm/mmu_notifier.rst
0f10851e
JG
1006 */
1007 if (ret)
6a8e0596 1008 cleaned++;
c2fda5fe 1009 }
d08b3851 1010
ac46d4f3 1011 mmu_notifier_invalidate_range_end(&range);
369ea824 1012
6a8e0596
MS
1013 return cleaned;
1014}
1015
1016static bool page_mkclean_one(struct folio *folio, struct vm_area_struct *vma,
1017 unsigned long address, void *arg)
1018{
1019 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, PVMW_SYNC);
1020 int *cleaned = arg;
1021
1022 *cleaned += page_vma_mkclean_one(&pvmw);
1023
e4b82222 1024 return true;
d08b3851
PZ
1025}
1026
9853a407 1027static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
d08b3851 1028{
9853a407 1029 if (vma->vm_flags & VM_SHARED)
871beb8c 1030 return false;
d08b3851 1031
871beb8c 1032 return true;
d08b3851
PZ
1033}
1034
d9c08e22 1035int folio_mkclean(struct folio *folio)
d08b3851 1036{
9853a407
JK
1037 int cleaned = 0;
1038 struct address_space *mapping;
1039 struct rmap_walk_control rwc = {
1040 .arg = (void *)&cleaned,
1041 .rmap_one = page_mkclean_one,
1042 .invalid_vma = invalid_mkclean_vma,
1043 };
d08b3851 1044
d9c08e22 1045 BUG_ON(!folio_test_locked(folio));
d08b3851 1046
d9c08e22 1047 if (!folio_mapped(folio))
9853a407
JK
1048 return 0;
1049
d9c08e22 1050 mapping = folio_mapping(folio);
9853a407
JK
1051 if (!mapping)
1052 return 0;
1053
2f031c6f 1054 rmap_walk(folio, &rwc);
d08b3851 1055
9853a407 1056 return cleaned;
d08b3851 1057}
d9c08e22 1058EXPORT_SYMBOL_GPL(folio_mkclean);
d08b3851 1059
6a8e0596
MS
1060/**
1061 * pfn_mkclean_range - Cleans the PTEs (including PMDs) mapped with range of
1062 * [@pfn, @pfn + @nr_pages) at the specific offset (@pgoff)
1063 * within the @vma of shared mappings. And since clean PTEs
1064 * should also be readonly, write protects them too.
1065 * @pfn: start pfn.
1066 * @nr_pages: number of physically contiguous pages srarting with @pfn.
1067 * @pgoff: page offset that the @pfn mapped with.
1068 * @vma: vma that @pfn mapped within.
1069 *
1070 * Returns the number of cleaned PTEs (including PMDs).
1071 */
1072int pfn_mkclean_range(unsigned long pfn, unsigned long nr_pages, pgoff_t pgoff,
1073 struct vm_area_struct *vma)
1074{
1075 struct page_vma_mapped_walk pvmw = {
1076 .pfn = pfn,
1077 .nr_pages = nr_pages,
1078 .pgoff = pgoff,
1079 .vma = vma,
1080 .flags = PVMW_SYNC,
1081 };
1082
1083 if (invalid_mkclean_vma(vma, NULL))
1084 return 0;
1085
1086 pvmw.address = vma_pgoff_address(pgoff, nr_pages, vma);
1087 VM_BUG_ON_VMA(pvmw.address == -EFAULT, vma);
1088
1089 return page_vma_mkclean_one(&pvmw);
1090}
1091
c44b6743
RR
1092/**
1093 * page_move_anon_rmap - move a page to our anon_vma
1094 * @page: the page to move to our anon_vma
1095 * @vma: the vma the page belongs to
c44b6743
RR
1096 *
1097 * When a page belongs exclusively to one process after a COW event,
1098 * that page can be moved into the anon_vma that belongs to just that
1099 * process, so the rmap code will not search the parent or sibling
1100 * processes.
1101 */
5a49973d 1102void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
c44b6743
RR
1103{
1104 struct anon_vma *anon_vma = vma->anon_vma;
6c287605 1105 struct page *subpage = page;
c44b6743 1106
5a49973d
HD
1107 page = compound_head(page);
1108
309381fe 1109 VM_BUG_ON_PAGE(!PageLocked(page), page);
81d1b09c 1110 VM_BUG_ON_VMA(!anon_vma, vma);
c44b6743
RR
1111
1112 anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
414e2fb8
VD
1113 /*
1114 * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
b3ac0413
MWO
1115 * simultaneously, so a concurrent reader (eg folio_referenced()'s
1116 * folio_test_anon()) will not see one without the other.
414e2fb8
VD
1117 */
1118 WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
6c287605 1119 SetPageAnonExclusive(subpage);
c44b6743
RR
1120}
1121
9617d95e 1122/**
4e1c1975 1123 * __page_set_anon_rmap - set up new anonymous rmap
451b9514 1124 * @page: Page or Hugepage to add to rmap
4e1c1975
AK
1125 * @vma: VM area to add page to.
1126 * @address: User virtual address of the mapping
e8a03feb 1127 * @exclusive: the page is exclusively owned by the current process
9617d95e
NP
1128 */
1129static void __page_set_anon_rmap(struct page *page,
e8a03feb 1130 struct vm_area_struct *vma, unsigned long address, int exclusive)
9617d95e 1131{
e8a03feb 1132 struct anon_vma *anon_vma = vma->anon_vma;
ea90002b 1133
e8a03feb 1134 BUG_ON(!anon_vma);
ea90002b 1135
4e1c1975 1136 if (PageAnon(page))
6c287605 1137 goto out;
4e1c1975 1138
ea90002b 1139 /*
e8a03feb
RR
1140 * If the page isn't exclusively mapped into this vma,
1141 * we must use the _oldest_ possible anon_vma for the
1142 * page mapping!
ea90002b 1143 */
4e1c1975 1144 if (!exclusive)
288468c3 1145 anon_vma = anon_vma->root;
9617d95e 1146
16f5e707
AS
1147 /*
1148 * page_idle does a lockless/optimistic rmap scan on page->mapping.
1149 * Make sure the compiler doesn't split the stores of anon_vma and
1150 * the PAGE_MAPPING_ANON type identifier, otherwise the rmap code
1151 * could mistake the mapping for a struct address_space and crash.
1152 */
9617d95e 1153 anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
16f5e707 1154 WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
9617d95e 1155 page->index = linear_page_index(vma, address);
6c287605
DH
1156out:
1157 if (exclusive)
1158 SetPageAnonExclusive(page);
9617d95e
NP
1159}
1160
c97a9e10 1161/**
43d8eac4 1162 * __page_check_anon_rmap - sanity check anonymous rmap addition
c97a9e10
NP
1163 * @page: the page to add the mapping to
1164 * @vma: the vm area in which the mapping is added
1165 * @address: the user virtual address mapped
1166 */
1167static void __page_check_anon_rmap(struct page *page,
1168 struct vm_area_struct *vma, unsigned long address)
1169{
e05b3453 1170 struct folio *folio = page_folio(page);
c97a9e10
NP
1171 /*
1172 * The page's anon-rmap details (mapping and index) are guaranteed to
1173 * be set up correctly at this point.
1174 *
1175 * We have exclusion against page_add_anon_rmap because the caller
90aaca85 1176 * always holds the page locked.
c97a9e10
NP
1177 *
1178 * We have exclusion against page_add_new_anon_rmap because those pages
1179 * are initially only visible via the pagetables, and the pte is locked
1180 * over the call to page_add_new_anon_rmap.
1181 */
e05b3453
MWO
1182 VM_BUG_ON_FOLIO(folio_anon_vma(folio)->root != vma->anon_vma->root,
1183 folio);
30c46382
YS
1184 VM_BUG_ON_PAGE(page_to_pgoff(page) != linear_page_index(vma, address),
1185 page);
c97a9e10
NP
1186}
1187
1da177e4
LT
1188/**
1189 * page_add_anon_rmap - add pte mapping to an anonymous page
1190 * @page: the page to add the mapping to
1191 * @vma: the vm area in which the mapping is added
1192 * @address: the user virtual address mapped
f1e2db12 1193 * @flags: the rmap flags
1da177e4 1194 *
5ad64688 1195 * The caller needs to hold the pte lock, and the page must be locked in
80e14822
HD
1196 * the anon_vma case: to serialize mapping,index checking after setting,
1197 * and to ensure that PageAnon is not being upgraded racily to PageKsm
1198 * (but PageKsm is never downgraded to PageAnon).
1da177e4
LT
1199 */
1200void page_add_anon_rmap(struct page *page,
14f9135d 1201 struct vm_area_struct *vma, unsigned long address, rmap_t flags)
1da177e4 1202{
53f9263b
KS
1203 bool compound = flags & RMAP_COMPOUND;
1204 bool first;
1205
be5d0a74
JW
1206 if (unlikely(PageKsm(page)))
1207 lock_page_memcg(page);
1208 else
1209 VM_BUG_ON_PAGE(!PageLocked(page), page);
1210
e9b61f19
KS
1211 if (compound) {
1212 atomic_t *mapcount;
53f9263b 1213 VM_BUG_ON_PAGE(!PageLocked(page), page);
e9b61f19
KS
1214 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
1215 mapcount = compound_mapcount_ptr(page);
1216 first = atomic_inc_and_test(mapcount);
53f9263b
KS
1217 } else {
1218 first = atomic_inc_and_test(&page->_mapcount);
1219 }
6c287605
DH
1220 VM_BUG_ON_PAGE(!first && (flags & RMAP_EXCLUSIVE), page);
1221 VM_BUG_ON_PAGE(!first && PageAnonExclusive(page), page);
53f9263b 1222
79134171 1223 if (first) {
6c357848 1224 int nr = compound ? thp_nr_pages(page) : 1;
bea04b07
JZ
1225 /*
1226 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1227 * these counters are not modified in interrupt context, and
1228 * pte lock(a spinlock) is held, which implies preemption
1229 * disabled.
1230 */
65c45377 1231 if (compound)
69473e5d 1232 __mod_lruvec_page_state(page, NR_ANON_THPS, nr);
be5d0a74 1233 __mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
79134171 1234 }
5ad64688 1235
cea86fe2 1236 if (unlikely(PageKsm(page)))
be5d0a74 1237 unlock_page_memcg(page);
53f9263b 1238
5dbe0af4 1239 /* address might be in next vma when migration races vma_adjust */
cea86fe2 1240 else if (first)
d281ee61 1241 __page_set_anon_rmap(page, vma, address,
14f9135d 1242 !!(flags & RMAP_EXCLUSIVE));
69029cd5 1243 else
c97a9e10 1244 __page_check_anon_rmap(page, vma, address);
cea86fe2
HD
1245
1246 mlock_vma_page(page, vma, compound);
1da177e4
LT
1247}
1248
43d8eac4 1249/**
40f2bbf7 1250 * page_add_new_anon_rmap - add mapping to a new anonymous page
9617d95e
NP
1251 * @page: the page to add the mapping to
1252 * @vma: the vm area in which the mapping is added
1253 * @address: the user virtual address mapped
40f2bbf7
DH
1254 *
1255 * If it's a compound page, it is accounted as a compound page. As the page
1256 * is new, it's assume to get mapped exclusively by a single process.
9617d95e
NP
1257 *
1258 * Same as page_add_anon_rmap but must only be called on *new* pages.
1259 * This means the inc-and-test can be bypassed.
c97a9e10 1260 * Page does not have to be locked.
9617d95e
NP
1261 */
1262void page_add_new_anon_rmap(struct page *page,
40f2bbf7 1263 struct vm_area_struct *vma, unsigned long address)
9617d95e 1264{
40f2bbf7 1265 const bool compound = PageCompound(page);
6c357848 1266 int nr = compound ? thp_nr_pages(page) : 1;
d281ee61 1267
81d1b09c 1268 VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
fa9949da 1269 __SetPageSwapBacked(page);
d281ee61
KS
1270 if (compound) {
1271 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
53f9263b
KS
1272 /* increment count (starts at -1) */
1273 atomic_set(compound_mapcount_ptr(page), 0);
5232c63f 1274 atomic_set(compound_pincount_ptr(page), 0);
47e29d32 1275
69473e5d 1276 __mod_lruvec_page_state(page, NR_ANON_THPS, nr);
53f9263b 1277 } else {
53f9263b
KS
1278 /* increment count (starts at -1) */
1279 atomic_set(&page->_mapcount, 0);
d281ee61 1280 }
be5d0a74 1281 __mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
e8a03feb 1282 __page_set_anon_rmap(page, vma, address, 1);
9617d95e
NP
1283}
1284
1da177e4
LT
1285/**
1286 * page_add_file_rmap - add pte mapping to a file page
cea86fe2
HD
1287 * @page: the page to add the mapping to
1288 * @vma: the vm area in which the mapping is added
1289 * @compound: charge the page as compound or small page
1da177e4 1290 *
b8072f09 1291 * The caller needs to hold the pte lock.
1da177e4 1292 */
cea86fe2
HD
1293void page_add_file_rmap(struct page *page,
1294 struct vm_area_struct *vma, bool compound)
1da177e4 1295{
5d543f13 1296 int i, nr = 0;
dd78fedd
KS
1297
1298 VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
62cccb8c 1299 lock_page_memcg(page);
dd78fedd 1300 if (compound && PageTransHuge(page)) {
a1528e21
MS
1301 int nr_pages = thp_nr_pages(page);
1302
5d543f13 1303 for (i = 0; i < nr_pages; i++) {
dd78fedd
KS
1304 if (atomic_inc_and_test(&page[i]._mapcount))
1305 nr++;
1306 }
1307 if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
1308 goto out;
bd55b0c2
HD
1309
1310 /*
1311 * It is racy to ClearPageDoubleMap in page_remove_file_rmap();
1312 * but page lock is held by all page_add_file_rmap() compound
1313 * callers, and SetPageDoubleMap below warns if !PageLocked:
1314 * so here is a place that DoubleMap can be safely cleared.
1315 */
1316 VM_WARN_ON_ONCE(!PageLocked(page));
1317 if (nr == nr_pages && PageDoubleMap(page))
1318 ClearPageDoubleMap(page);
1319
99cb0dbd 1320 if (PageSwapBacked(page))
a1528e21
MS
1321 __mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1322 nr_pages);
99cb0dbd 1323 else
380780e7
MS
1324 __mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1325 nr_pages);
dd78fedd 1326 } else {
c8efc390
KS
1327 if (PageTransCompound(page) && page_mapping(page)) {
1328 VM_WARN_ON_ONCE(!PageLocked(page));
cea86fe2 1329 SetPageDoubleMap(compound_head(page));
9a73f61b 1330 }
5d543f13
HD
1331 if (atomic_inc_and_test(&page->_mapcount))
1332 nr++;
d69b042f 1333 }
dd78fedd 1334out:
5d543f13
HD
1335 if (nr)
1336 __mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
62cccb8c 1337 unlock_page_memcg(page);
cea86fe2
HD
1338
1339 mlock_vma_page(page, vma, compound);
1da177e4
LT
1340}
1341
dd78fedd 1342static void page_remove_file_rmap(struct page *page, bool compound)
8186eb6a 1343{
5d543f13 1344 int i, nr = 0;
dd78fedd 1345
57dea93a 1346 VM_BUG_ON_PAGE(compound && !PageHead(page), page);
8186eb6a 1347
53f9263b
KS
1348 /* Hugepages are not counted in NR_FILE_MAPPED for now. */
1349 if (unlikely(PageHuge(page))) {
1350 /* hugetlb pages are always mapped with pmds */
1351 atomic_dec(compound_mapcount_ptr(page));
be5d0a74 1352 return;
53f9263b 1353 }
8186eb6a 1354
53f9263b 1355 /* page still mapped by someone else? */
dd78fedd 1356 if (compound && PageTransHuge(page)) {
a1528e21
MS
1357 int nr_pages = thp_nr_pages(page);
1358
5d543f13 1359 for (i = 0; i < nr_pages; i++) {
dd78fedd
KS
1360 if (atomic_add_negative(-1, &page[i]._mapcount))
1361 nr++;
1362 }
1363 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
5d543f13 1364 goto out;
99cb0dbd 1365 if (PageSwapBacked(page))
a1528e21
MS
1366 __mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1367 -nr_pages);
99cb0dbd 1368 else
380780e7
MS
1369 __mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1370 -nr_pages);
dd78fedd 1371 } else {
5d543f13
HD
1372 if (atomic_add_negative(-1, &page->_mapcount))
1373 nr++;
dd78fedd 1374 }
5d543f13
HD
1375out:
1376 if (nr)
1377 __mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
8186eb6a
JW
1378}
1379
53f9263b
KS
1380static void page_remove_anon_compound_rmap(struct page *page)
1381{
1382 int i, nr;
1383
1384 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1385 return;
1386
1387 /* Hugepages are not counted in NR_ANON_PAGES for now. */
1388 if (unlikely(PageHuge(page)))
1389 return;
1390
1391 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1392 return;
1393
69473e5d 1394 __mod_lruvec_page_state(page, NR_ANON_THPS, -thp_nr_pages(page));
53f9263b
KS
1395
1396 if (TestClearPageDoubleMap(page)) {
1397 /*
1398 * Subpages can be mapped with PTEs too. Check how many of
f1fe80d4 1399 * them are still mapped.
53f9263b 1400 */
5eaf35ab 1401 for (i = 0, nr = 0; i < thp_nr_pages(page); i++) {
53f9263b
KS
1402 if (atomic_add_negative(-1, &page[i]._mapcount))
1403 nr++;
1404 }
f1fe80d4
KS
1405
1406 /*
1407 * Queue the page for deferred split if at least one small
1408 * page of the compound page is unmapped, but at least one
1409 * small page is still mapped.
1410 */
5eaf35ab 1411 if (nr && nr < thp_nr_pages(page))
f1fe80d4 1412 deferred_split_huge_page(page);
53f9263b 1413 } else {
5eaf35ab 1414 nr = thp_nr_pages(page);
53f9263b
KS
1415 }
1416
f1fe80d4 1417 if (nr)
be5d0a74 1418 __mod_lruvec_page_state(page, NR_ANON_MAPPED, -nr);
53f9263b
KS
1419}
1420
1da177e4
LT
1421/**
1422 * page_remove_rmap - take down pte mapping from a page
d281ee61 1423 * @page: page to remove mapping from
cea86fe2 1424 * @vma: the vm area from which the mapping is removed
d281ee61 1425 * @compound: uncharge the page as compound or small page
1da177e4 1426 *
b8072f09 1427 * The caller needs to hold the pte lock.
1da177e4 1428 */
cea86fe2
HD
1429void page_remove_rmap(struct page *page,
1430 struct vm_area_struct *vma, bool compound)
1da177e4 1431{
be5d0a74 1432 lock_page_memcg(page);
89c06bd5 1433
be5d0a74
JW
1434 if (!PageAnon(page)) {
1435 page_remove_file_rmap(page, compound);
1436 goto out;
1437 }
1438
1439 if (compound) {
1440 page_remove_anon_compound_rmap(page);
1441 goto out;
1442 }
53f9263b 1443
b904dcfe
KM
1444 /* page still mapped by someone else? */
1445 if (!atomic_add_negative(-1, &page->_mapcount))
be5d0a74 1446 goto out;
8186eb6a 1447
0fe6e20b 1448 /*
bea04b07
JZ
1449 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1450 * these counters are not modified in interrupt context, and
bea04b07 1451 * pte lock(a spinlock) is held, which implies preemption disabled.
0fe6e20b 1452 */
be5d0a74 1453 __dec_lruvec_page_state(page, NR_ANON_MAPPED);
8186eb6a 1454
9a982250
KS
1455 if (PageTransCompound(page))
1456 deferred_split_huge_page(compound_head(page));
1457
b904dcfe
KM
1458 /*
1459 * It would be tidy to reset the PageAnon mapping here,
1460 * but that might overwrite a racing page_add_anon_rmap
1461 * which increments mapcount after us but sets mapping
2d4894b5 1462 * before us: so leave the reset to free_unref_page,
b904dcfe
KM
1463 * and remember that it's only reliable while mapped.
1464 * Leaving it set also helps swapoff to reinstate ptes
1465 * faster for those pages still in swapcache.
1466 */
be5d0a74
JW
1467out:
1468 unlock_page_memcg(page);
cea86fe2
HD
1469
1470 munlock_vma_page(page, vma, compound);
1da177e4
LT
1471}
1472
1473/*
52629506 1474 * @arg: enum ttu_flags will be passed to this argument
1da177e4 1475 */
2f031c6f 1476static bool try_to_unmap_one(struct folio *folio, struct vm_area_struct *vma,
52629506 1477 unsigned long address, void *arg)
1da177e4
LT
1478{
1479 struct mm_struct *mm = vma->vm_mm;
869f7ee6 1480 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
1da177e4 1481 pte_t pteval;
c7ab0d2f 1482 struct page *subpage;
6c287605 1483 bool anon_exclusive, ret = true;
ac46d4f3 1484 struct mmu_notifier_range range;
4708f318 1485 enum ttu_flags flags = (enum ttu_flags)(long)arg;
1da177e4 1486
732ed558
HD
1487 /*
1488 * When racing against e.g. zap_pte_range() on another cpu,
1489 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
1fb08ac6 1490 * try_to_unmap() may return before page_mapped() has become false,
732ed558
HD
1491 * if page table locking is skipped: use TTU_SYNC to wait for that.
1492 */
1493 if (flags & TTU_SYNC)
1494 pvmw.flags = PVMW_SYNC;
1495
a98a2f0c 1496 if (flags & TTU_SPLIT_HUGE_PMD)
af28a988 1497 split_huge_pmd_address(vma, address, false, folio);
fec89c10 1498
369ea824 1499 /*
017b1660
MK
1500 * For THP, we have to assume the worse case ie pmd for invalidation.
1501 * For hugetlb, it could be much worse if we need to do pud
1502 * invalidation in the case of pmd sharing.
1503 *
869f7ee6
MWO
1504 * Note that the folio can not be freed in this function as call of
1505 * try_to_unmap() must hold a reference on the folio.
369ea824 1506 */
2aff7a47 1507 range.end = vma_address_end(&pvmw);
7269f999 1508 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
494334e4 1509 address, range.end);
869f7ee6 1510 if (folio_test_hugetlb(folio)) {
017b1660
MK
1511 /*
1512 * If sharing is possible, start and end will be adjusted
1513 * accordingly.
1514 */
ac46d4f3
JG
1515 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1516 &range.end);
017b1660 1517 }
ac46d4f3 1518 mmu_notifier_invalidate_range_start(&range);
369ea824 1519
c7ab0d2f 1520 while (page_vma_mapped_walk(&pvmw)) {
cea86fe2 1521 /* Unexpected PMD-mapped THP? */
869f7ee6 1522 VM_BUG_ON_FOLIO(!pvmw.pte, folio);
cea86fe2 1523
c7ab0d2f 1524 /*
869f7ee6 1525 * If the folio is in an mlock()d vma, we must not swap it out.
c7ab0d2f 1526 */
efdb6720
HD
1527 if (!(flags & TTU_IGNORE_MLOCK) &&
1528 (vma->vm_flags & VM_LOCKED)) {
cea86fe2 1529 /* Restore the mlock which got missed */
869f7ee6 1530 mlock_vma_folio(folio, vma, false);
efdb6720
HD
1531 page_vma_mapped_walk_done(&pvmw);
1532 ret = false;
1533 break;
b87537d9 1534 }
c7ab0d2f 1535
869f7ee6
MWO
1536 subpage = folio_page(folio,
1537 pte_pfn(*pvmw.pte) - folio_pfn(folio));
785373b4 1538 address = pvmw.address;
6c287605
DH
1539 anon_exclusive = folio_test_anon(folio) &&
1540 PageAnonExclusive(subpage);
785373b4 1541
dfc7ab57 1542 if (folio_test_hugetlb(folio)) {
0506c31d
BW
1543 bool anon = folio_test_anon(folio);
1544
a00a8759
BW
1545 /*
1546 * The try_to_unmap() is only passed a hugetlb page
1547 * in the case where the hugetlb page is poisoned.
1548 */
1549 VM_BUG_ON_PAGE(!PageHWPoison(subpage), subpage);
54205e9c
BW
1550 /*
1551 * huge_pmd_unshare may unmap an entire PMD page.
1552 * There is no way of knowing exactly which PMDs may
1553 * be cached for this mm, so we must flush them all.
1554 * start/end were already adjusted above to cover this
1555 * range.
1556 */
1557 flush_cache_range(vma, range.start, range.end);
1558
0506c31d
BW
1559 /*
1560 * To call huge_pmd_unshare, i_mmap_rwsem must be
1561 * held in write mode. Caller needs to explicitly
1562 * do this outside rmap routines.
1563 */
1564 VM_BUG_ON(!anon && !(flags & TTU_RMAP_LOCKED));
4ddb4d91 1565 if (!anon && huge_pmd_unshare(mm, vma, address, pvmw.pte)) {
0506c31d
BW
1566 flush_tlb_range(vma, range.start, range.end);
1567 mmu_notifier_invalidate_range(mm, range.start,
1568 range.end);
1569
017b1660 1570 /*
0506c31d
BW
1571 * The ref count of the PMD page was dropped
1572 * which is part of the way map counting
1573 * is done for shared PMDs. Return 'true'
1574 * here. When there is no other sharing,
1575 * huge_pmd_unshare returns false and we will
1576 * unmap the actual page and drop map count
1577 * to zero.
017b1660 1578 */
0506c31d
BW
1579 page_vma_mapped_walk_done(&pvmw);
1580 break;
017b1660 1581 }
a00a8759 1582 pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
54205e9c
BW
1583 } else {
1584 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
c7ab0d2f 1585 /*
a00a8759
BW
1586 * Nuke the page table entry. When having to clear
1587 * PageAnonExclusive(), we always have to flush.
c7ab0d2f 1588 */
a00a8759
BW
1589 if (should_defer_flush(mm, flags) && !anon_exclusive) {
1590 /*
1591 * We clear the PTE but do not flush so potentially
1592 * a remote CPU could still be writing to the folio.
1593 * If the entry was previously clean then the
1594 * architecture must guarantee that a clear->dirty
1595 * transition on a cached TLB entry is written through
1596 * and traps if the PTE is unmapped.
1597 */
1598 pteval = ptep_get_and_clear(mm, address, pvmw.pte);
c7ab0d2f 1599
a00a8759
BW
1600 set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
1601 } else {
1602 pteval = ptep_clear_flush(vma, address, pvmw.pte);
1603 }
c7ab0d2f 1604 }
72b252ae 1605
999dad82
PX
1606 /*
1607 * Now the pte is cleared. If this pte was uffd-wp armed,
1608 * we may want to replace a none pte with a marker pte if
1609 * it's file-backed, so we don't lose the tracking info.
1610 */
1611 pte_install_uffd_wp_if_needed(vma, address, pvmw.pte, pteval);
1612
869f7ee6 1613 /* Set the dirty flag on the folio now the pte is gone. */
c7ab0d2f 1614 if (pte_dirty(pteval))
869f7ee6 1615 folio_mark_dirty(folio);
1da177e4 1616
c7ab0d2f
KS
1617 /* Update high watermark before we lower rss */
1618 update_hiwater_rss(mm);
1da177e4 1619
da358d5c 1620 if (PageHWPoison(subpage) && !(flags & TTU_IGNORE_HWPOISON)) {
5fd27b8e 1621 pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
869f7ee6
MWO
1622 if (folio_test_hugetlb(folio)) {
1623 hugetlb_count_sub(folio_nr_pages(folio), mm);
18f39629 1624 set_huge_pte_at(mm, address, pvmw.pte, pteval);
c7ab0d2f 1625 } else {
869f7ee6 1626 dec_mm_counter(mm, mm_counter(&folio->page));
785373b4 1627 set_pte_at(mm, address, pvmw.pte, pteval);
c7ab0d2f 1628 }
365e9c87 1629
bce73e48 1630 } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
c7ab0d2f
KS
1631 /*
1632 * The guest indicated that the page content is of no
1633 * interest anymore. Simply discard the pte, vmscan
1634 * will take care of the rest.
bce73e48
CB
1635 * A future reference will then fault in a new zero
1636 * page. When userfaultfd is active, we must not drop
1637 * this page though, as its main user (postcopy
1638 * migration) will not expect userfaults on already
1639 * copied pages.
c7ab0d2f 1640 */
869f7ee6 1641 dec_mm_counter(mm, mm_counter(&folio->page));
0f10851e
JG
1642 /* We have to invalidate as we cleared the pte */
1643 mmu_notifier_invalidate_range(mm, address,
1644 address + PAGE_SIZE);
869f7ee6 1645 } else if (folio_test_anon(folio)) {
c7ab0d2f
KS
1646 swp_entry_t entry = { .val = page_private(subpage) };
1647 pte_t swp_pte;
1648 /*
1649 * Store the swap location in the pte.
1650 * See handle_pte_fault() ...
1651 */
869f7ee6
MWO
1652 if (unlikely(folio_test_swapbacked(folio) !=
1653 folio_test_swapcache(folio))) {
eb94a878 1654 WARN_ON_ONCE(1);
83612a94 1655 ret = false;
369ea824 1656 /* We have to invalidate as we cleared the pte */
0f10851e
JG
1657 mmu_notifier_invalidate_range(mm, address,
1658 address + PAGE_SIZE);
eb94a878
MK
1659 page_vma_mapped_walk_done(&pvmw);
1660 break;
1661 }
c7ab0d2f 1662
802a3a92 1663 /* MADV_FREE page check */
869f7ee6 1664 if (!folio_test_swapbacked(folio)) {
6c8e2a25
MFO
1665 int ref_count, map_count;
1666
1667 /*
1668 * Synchronize with gup_pte_range():
1669 * - clear PTE; barrier; read refcount
1670 * - inc refcount; barrier; read PTE
1671 */
1672 smp_mb();
1673
1674 ref_count = folio_ref_count(folio);
1675 map_count = folio_mapcount(folio);
1676
1677 /*
1678 * Order reads for page refcount and dirty flag
1679 * (see comments in __remove_mapping()).
1680 */
1681 smp_rmb();
1682
1683 /*
1684 * The only page refs must be one from isolation
1685 * plus the rmap(s) (dropped by discard:).
1686 */
1687 if (ref_count == 1 + map_count &&
1688 !folio_test_dirty(folio)) {
0f10851e
JG
1689 /* Invalidate as we cleared the pte */
1690 mmu_notifier_invalidate_range(mm,
1691 address, address + PAGE_SIZE);
802a3a92
SL
1692 dec_mm_counter(mm, MM_ANONPAGES);
1693 goto discard;
1694 }
1695
1696 /*
869f7ee6 1697 * If the folio was redirtied, it cannot be
802a3a92
SL
1698 * discarded. Remap the page to page table.
1699 */
785373b4 1700 set_pte_at(mm, address, pvmw.pte, pteval);
869f7ee6 1701 folio_set_swapbacked(folio);
e4b82222 1702 ret = false;
802a3a92
SL
1703 page_vma_mapped_walk_done(&pvmw);
1704 break;
c7ab0d2f 1705 }
854e9ed0 1706
c7ab0d2f 1707 if (swap_duplicate(entry) < 0) {
785373b4 1708 set_pte_at(mm, address, pvmw.pte, pteval);
e4b82222 1709 ret = false;
c7ab0d2f
KS
1710 page_vma_mapped_walk_done(&pvmw);
1711 break;
1712 }
ca827d55 1713 if (arch_unmap_one(mm, vma, address, pteval) < 0) {
322842ea 1714 swap_free(entry);
ca827d55
KA
1715 set_pte_at(mm, address, pvmw.pte, pteval);
1716 ret = false;
1717 page_vma_mapped_walk_done(&pvmw);
1718 break;
1719 }
6c287605
DH
1720 if (anon_exclusive &&
1721 page_try_share_anon_rmap(subpage)) {
1722 swap_free(entry);
1723 set_pte_at(mm, address, pvmw.pte, pteval);
1724 ret = false;
1725 page_vma_mapped_walk_done(&pvmw);
1726 break;
1727 }
1728 /*
1493a191
DH
1729 * Note: We *don't* remember if the page was mapped
1730 * exclusively in the swap pte if the architecture
1731 * doesn't support __HAVE_ARCH_PTE_SWP_EXCLUSIVE. In
1732 * that case, swapin code has to re-determine that
1733 * manually and might detect the page as possibly
1734 * shared, for example, if there are other references on
1735 * the page or if the page is under writeback. We made
1736 * sure that there are no GUP pins on the page that
1737 * would rely on it, so for GUP pins this is fine.
6c287605 1738 */
c7ab0d2f
KS
1739 if (list_empty(&mm->mmlist)) {
1740 spin_lock(&mmlist_lock);
1741 if (list_empty(&mm->mmlist))
1742 list_add(&mm->mmlist, &init_mm.mmlist);
1743 spin_unlock(&mmlist_lock);
1744 }
854e9ed0 1745 dec_mm_counter(mm, MM_ANONPAGES);
c7ab0d2f
KS
1746 inc_mm_counter(mm, MM_SWAPENTS);
1747 swp_pte = swp_entry_to_pte(entry);
1493a191
DH
1748 if (anon_exclusive)
1749 swp_pte = pte_swp_mkexclusive(swp_pte);
c7ab0d2f
KS
1750 if (pte_soft_dirty(pteval))
1751 swp_pte = pte_swp_mksoft_dirty(swp_pte);
f45ec5ff
PX
1752 if (pte_uffd_wp(pteval))
1753 swp_pte = pte_swp_mkuffd_wp(swp_pte);
785373b4 1754 set_pte_at(mm, address, pvmw.pte, swp_pte);
0f10851e
JG
1755 /* Invalidate as we cleared the pte */
1756 mmu_notifier_invalidate_range(mm, address,
1757 address + PAGE_SIZE);
1758 } else {
1759 /*
869f7ee6
MWO
1760 * This is a locked file-backed folio,
1761 * so it cannot be removed from the page
1762 * cache and replaced by a new folio before
1763 * mmu_notifier_invalidate_range_end, so no
1764 * concurrent thread might update its page table
1765 * to point at a new folio while a device is
1766 * still using this folio.
0f10851e 1767 *
ee65728e 1768 * See Documentation/mm/mmu_notifier.rst
0f10851e 1769 */
869f7ee6 1770 dec_mm_counter(mm, mm_counter_file(&folio->page));
0f10851e 1771 }
854e9ed0 1772discard:
0f10851e
JG
1773 /*
1774 * No need to call mmu_notifier_invalidate_range() it has be
1775 * done above for all cases requiring it to happen under page
1776 * table lock before mmu_notifier_invalidate_range_end()
1777 *
ee65728e 1778 * See Documentation/mm/mmu_notifier.rst
0f10851e 1779 */
869f7ee6 1780 page_remove_rmap(subpage, vma, folio_test_hugetlb(folio));
b7435507 1781 if (vma->vm_flags & VM_LOCKED)
adb11e78 1782 mlock_page_drain_local();
869f7ee6 1783 folio_put(folio);
c7ab0d2f 1784 }
369ea824 1785
ac46d4f3 1786 mmu_notifier_invalidate_range_end(&range);
369ea824 1787
caed0f48 1788 return ret;
1da177e4
LT
1789}
1790
52629506
JK
1791static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
1792{
222100ee 1793 return vma_is_temporary_stack(vma);
52629506
JK
1794}
1795
2f031c6f 1796static int page_not_mapped(struct folio *folio)
52629506 1797{
2f031c6f 1798 return !folio_mapped(folio);
2a52bcbc 1799}
52629506 1800
1da177e4 1801/**
869f7ee6
MWO
1802 * try_to_unmap - Try to remove all page table mappings to a folio.
1803 * @folio: The folio to unmap.
14fa31b8 1804 * @flags: action and flags
1da177e4
LT
1805 *
1806 * Tries to remove all the page table entries which are mapping this
869f7ee6
MWO
1807 * folio. It is the caller's responsibility to check if the folio is
1808 * still mapped if needed (use TTU_SYNC to prevent accounting races).
1da177e4 1809 *
869f7ee6 1810 * Context: Caller must hold the folio lock.
1da177e4 1811 */
869f7ee6 1812void try_to_unmap(struct folio *folio, enum ttu_flags flags)
1da177e4 1813{
52629506
JK
1814 struct rmap_walk_control rwc = {
1815 .rmap_one = try_to_unmap_one,
802a3a92 1816 .arg = (void *)flags,
b7e188ec 1817 .done = page_not_mapped,
2f031c6f 1818 .anon_lock = folio_lock_anon_vma_read,
52629506 1819 };
1da177e4 1820
a98a2f0c 1821 if (flags & TTU_RMAP_LOCKED)
2f031c6f 1822 rmap_walk_locked(folio, &rwc);
a98a2f0c 1823 else
2f031c6f 1824 rmap_walk(folio, &rwc);
a98a2f0c
AP
1825}
1826
1827/*
1828 * @arg: enum ttu_flags will be passed to this argument.
1829 *
1830 * If TTU_SPLIT_HUGE_PMD is specified any PMD mappings will be split into PTEs
64b586d1 1831 * containing migration entries.
a98a2f0c 1832 */
2f031c6f 1833static bool try_to_migrate_one(struct folio *folio, struct vm_area_struct *vma,
a98a2f0c
AP
1834 unsigned long address, void *arg)
1835{
1836 struct mm_struct *mm = vma->vm_mm;
4b8554c5 1837 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
a98a2f0c
AP
1838 pte_t pteval;
1839 struct page *subpage;
6c287605 1840 bool anon_exclusive, ret = true;
a98a2f0c
AP
1841 struct mmu_notifier_range range;
1842 enum ttu_flags flags = (enum ttu_flags)(long)arg;
1843
a98a2f0c
AP
1844 /*
1845 * When racing against e.g. zap_pte_range() on another cpu,
1846 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
1847 * try_to_migrate() may return before page_mapped() has become false,
1848 * if page table locking is skipped: use TTU_SYNC to wait for that.
1849 */
1850 if (flags & TTU_SYNC)
1851 pvmw.flags = PVMW_SYNC;
1852
1853 /*
1854 * unmap_page() in mm/huge_memory.c is the only user of migration with
1855 * TTU_SPLIT_HUGE_PMD and it wants to freeze.
1856 */
1857 if (flags & TTU_SPLIT_HUGE_PMD)
af28a988 1858 split_huge_pmd_address(vma, address, true, folio);
a98a2f0c
AP
1859
1860 /*
1861 * For THP, we have to assume the worse case ie pmd for invalidation.
1862 * For hugetlb, it could be much worse if we need to do pud
1863 * invalidation in the case of pmd sharing.
1864 *
1865 * Note that the page can not be free in this function as call of
1866 * try_to_unmap() must hold a reference on the page.
1867 */
2aff7a47 1868 range.end = vma_address_end(&pvmw);
a98a2f0c
AP
1869 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1870 address, range.end);
4b8554c5 1871 if (folio_test_hugetlb(folio)) {
a98a2f0c
AP
1872 /*
1873 * If sharing is possible, start and end will be adjusted
1874 * accordingly.
1875 */
1876 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1877 &range.end);
1878 }
1879 mmu_notifier_invalidate_range_start(&range);
1880
1881 while (page_vma_mapped_walk(&pvmw)) {
1882#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1883 /* PMD-mapped THP migration entry */
1884 if (!pvmw.pte) {
4b8554c5
MWO
1885 subpage = folio_page(folio,
1886 pmd_pfn(*pvmw.pmd) - folio_pfn(folio));
1887 VM_BUG_ON_FOLIO(folio_test_hugetlb(folio) ||
1888 !folio_test_pmd_mappable(folio), folio);
a98a2f0c 1889
7f5abe60
DH
1890 if (set_pmd_migration_entry(&pvmw, subpage)) {
1891 ret = false;
1892 page_vma_mapped_walk_done(&pvmw);
1893 break;
1894 }
a98a2f0c
AP
1895 continue;
1896 }
1897#endif
1898
1899 /* Unexpected PMD-mapped THP? */
4b8554c5 1900 VM_BUG_ON_FOLIO(!pvmw.pte, folio);
a98a2f0c 1901
1118234e
DH
1902 if (folio_is_zone_device(folio)) {
1903 /*
1904 * Our PTE is a non-present device exclusive entry and
1905 * calculating the subpage as for the common case would
1906 * result in an invalid pointer.
1907 *
1908 * Since only PAGE_SIZE pages can currently be
1909 * migrated, just set it to page. This will need to be
1910 * changed when hugepage migrations to device private
1911 * memory are supported.
1912 */
1913 VM_BUG_ON_FOLIO(folio_nr_pages(folio) > 1, folio);
1914 subpage = &folio->page;
1915 } else {
1916 subpage = folio_page(folio,
1917 pte_pfn(*pvmw.pte) - folio_pfn(folio));
1918 }
a98a2f0c 1919 address = pvmw.address;
6c287605
DH
1920 anon_exclusive = folio_test_anon(folio) &&
1921 PageAnonExclusive(subpage);
a98a2f0c 1922
dfc7ab57 1923 if (folio_test_hugetlb(folio)) {
0506c31d
BW
1924 bool anon = folio_test_anon(folio);
1925
54205e9c
BW
1926 /*
1927 * huge_pmd_unshare may unmap an entire PMD page.
1928 * There is no way of knowing exactly which PMDs may
1929 * be cached for this mm, so we must flush them all.
1930 * start/end were already adjusted above to cover this
1931 * range.
1932 */
1933 flush_cache_range(vma, range.start, range.end);
1934
0506c31d
BW
1935 /*
1936 * To call huge_pmd_unshare, i_mmap_rwsem must be
1937 * held in write mode. Caller needs to explicitly
1938 * do this outside rmap routines.
1939 */
1940 VM_BUG_ON(!anon && !(flags & TTU_RMAP_LOCKED));
4ddb4d91 1941 if (!anon && huge_pmd_unshare(mm, vma, address, pvmw.pte)) {
0506c31d
BW
1942 flush_tlb_range(vma, range.start, range.end);
1943 mmu_notifier_invalidate_range(mm, range.start,
1944 range.end);
1945
a98a2f0c 1946 /*
0506c31d
BW
1947 * The ref count of the PMD page was dropped
1948 * which is part of the way map counting
1949 * is done for shared PMDs. Return 'true'
1950 * here. When there is no other sharing,
1951 * huge_pmd_unshare returns false and we will
1952 * unmap the actual page and drop map count
1953 * to zero.
a98a2f0c 1954 */
0506c31d
BW
1955 page_vma_mapped_walk_done(&pvmw);
1956 break;
a98a2f0c 1957 }
5d4af619
BW
1958
1959 /* Nuke the hugetlb page table entry */
1960 pteval = huge_ptep_clear_flush(vma, address, pvmw.pte);
54205e9c
BW
1961 } else {
1962 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
5d4af619
BW
1963 /* Nuke the page table entry. */
1964 pteval = ptep_clear_flush(vma, address, pvmw.pte);
a98a2f0c
AP
1965 }
1966
4b8554c5 1967 /* Set the dirty flag on the folio now the pte is gone. */
a98a2f0c 1968 if (pte_dirty(pteval))
4b8554c5 1969 folio_mark_dirty(folio);
a98a2f0c
AP
1970
1971 /* Update high watermark before we lower rss */
1972 update_hiwater_rss(mm);
1973
f25cbb7a 1974 if (folio_is_device_private(folio)) {
4b8554c5 1975 unsigned long pfn = folio_pfn(folio);
a98a2f0c
AP
1976 swp_entry_t entry;
1977 pte_t swp_pte;
1978
6c287605
DH
1979 if (anon_exclusive)
1980 BUG_ON(page_try_share_anon_rmap(subpage));
1981
a98a2f0c
AP
1982 /*
1983 * Store the pfn of the page in a special migration
1984 * pte. do_swap_page() will wait until the migration
1985 * pte is removed and then restart fault handling.
1986 */
3d88705c
AP
1987 entry = pte_to_swp_entry(pteval);
1988 if (is_writable_device_private_entry(entry))
1989 entry = make_writable_migration_entry(pfn);
6c287605
DH
1990 else if (anon_exclusive)
1991 entry = make_readable_exclusive_migration_entry(pfn);
3d88705c
AP
1992 else
1993 entry = make_readable_migration_entry(pfn);
a98a2f0c
AP
1994 swp_pte = swp_entry_to_pte(entry);
1995
1996 /*
1997 * pteval maps a zone device page and is therefore
1998 * a swap pte.
1999 */
2000 if (pte_swp_soft_dirty(pteval))
2001 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2002 if (pte_swp_uffd_wp(pteval))
2003 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2004 set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
4cc79b33
AK
2005 trace_set_migration_pte(pvmw.address, pte_val(swp_pte),
2006 compound_order(&folio->page));
a98a2f0c
AP
2007 /*
2008 * No need to invalidate here it will synchronize on
2009 * against the special swap migration pte.
a98a2f0c 2010 */
da358d5c 2011 } else if (PageHWPoison(subpage)) {
a98a2f0c 2012 pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
4b8554c5
MWO
2013 if (folio_test_hugetlb(folio)) {
2014 hugetlb_count_sub(folio_nr_pages(folio), mm);
18f39629 2015 set_huge_pte_at(mm, address, pvmw.pte, pteval);
a98a2f0c 2016 } else {
4b8554c5 2017 dec_mm_counter(mm, mm_counter(&folio->page));
a98a2f0c
AP
2018 set_pte_at(mm, address, pvmw.pte, pteval);
2019 }
2020
2021 } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
2022 /*
2023 * The guest indicated that the page content is of no
2024 * interest anymore. Simply discard the pte, vmscan
2025 * will take care of the rest.
2026 * A future reference will then fault in a new zero
2027 * page. When userfaultfd is active, we must not drop
2028 * this page though, as its main user (postcopy
2029 * migration) will not expect userfaults on already
2030 * copied pages.
2031 */
4b8554c5 2032 dec_mm_counter(mm, mm_counter(&folio->page));
a98a2f0c
AP
2033 /* We have to invalidate as we cleared the pte */
2034 mmu_notifier_invalidate_range(mm, address,
2035 address + PAGE_SIZE);
2036 } else {
2037 swp_entry_t entry;
2038 pte_t swp_pte;
2039
2040 if (arch_unmap_one(mm, vma, address, pteval) < 0) {
5d4af619
BW
2041 if (folio_test_hugetlb(folio))
2042 set_huge_pte_at(mm, address, pvmw.pte, pteval);
2043 else
2044 set_pte_at(mm, address, pvmw.pte, pteval);
a98a2f0c
AP
2045 ret = false;
2046 page_vma_mapped_walk_done(&pvmw);
2047 break;
2048 }
6c287605
DH
2049 VM_BUG_ON_PAGE(pte_write(pteval) && folio_test_anon(folio) &&
2050 !anon_exclusive, subpage);
2051 if (anon_exclusive &&
2052 page_try_share_anon_rmap(subpage)) {
5d4af619
BW
2053 if (folio_test_hugetlb(folio))
2054 set_huge_pte_at(mm, address, pvmw.pte, pteval);
2055 else
2056 set_pte_at(mm, address, pvmw.pte, pteval);
6c287605
DH
2057 ret = false;
2058 page_vma_mapped_walk_done(&pvmw);
2059 break;
2060 }
a98a2f0c
AP
2061
2062 /*
2063 * Store the pfn of the page in a special migration
2064 * pte. do_swap_page() will wait until the migration
2065 * pte is removed and then restart fault handling.
2066 */
2067 if (pte_write(pteval))
2068 entry = make_writable_migration_entry(
2069 page_to_pfn(subpage));
6c287605
DH
2070 else if (anon_exclusive)
2071 entry = make_readable_exclusive_migration_entry(
2072 page_to_pfn(subpage));
a98a2f0c
AP
2073 else
2074 entry = make_readable_migration_entry(
2075 page_to_pfn(subpage));
2076
2077 swp_pte = swp_entry_to_pte(entry);
2078 if (pte_soft_dirty(pteval))
2079 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2080 if (pte_uffd_wp(pteval))
2081 swp_pte = pte_swp_mkuffd_wp(swp_pte);
5d4af619 2082 if (folio_test_hugetlb(folio))
18f39629 2083 set_huge_pte_at(mm, address, pvmw.pte, swp_pte);
5d4af619
BW
2084 else
2085 set_pte_at(mm, address, pvmw.pte, swp_pte);
4cc79b33
AK
2086 trace_set_migration_pte(address, pte_val(swp_pte),
2087 compound_order(&folio->page));
a98a2f0c
AP
2088 /*
2089 * No need to invalidate here it will synchronize on
2090 * against the special swap migration pte.
2091 */
2092 }
2093
2094 /*
2095 * No need to call mmu_notifier_invalidate_range() it has be
2096 * done above for all cases requiring it to happen under page
2097 * table lock before mmu_notifier_invalidate_range_end()
2098 *
ee65728e 2099 * See Documentation/mm/mmu_notifier.rst
a98a2f0c 2100 */
4b8554c5 2101 page_remove_rmap(subpage, vma, folio_test_hugetlb(folio));
b7435507 2102 if (vma->vm_flags & VM_LOCKED)
adb11e78 2103 mlock_page_drain_local();
4b8554c5 2104 folio_put(folio);
a98a2f0c
AP
2105 }
2106
2107 mmu_notifier_invalidate_range_end(&range);
2108
2109 return ret;
2110}
2111
2112/**
2113 * try_to_migrate - try to replace all page table mappings with swap entries
4b8554c5 2114 * @folio: the folio to replace page table entries for
a98a2f0c
AP
2115 * @flags: action and flags
2116 *
4b8554c5
MWO
2117 * Tries to remove all the page table entries which are mapping this folio and
2118 * replace them with special swap entries. Caller must hold the folio lock.
a98a2f0c 2119 */
4b8554c5 2120void try_to_migrate(struct folio *folio, enum ttu_flags flags)
a98a2f0c
AP
2121{
2122 struct rmap_walk_control rwc = {
2123 .rmap_one = try_to_migrate_one,
2124 .arg = (void *)flags,
2125 .done = page_not_mapped,
2f031c6f 2126 .anon_lock = folio_lock_anon_vma_read,
a98a2f0c
AP
2127 };
2128
2129 /*
2130 * Migration always ignores mlock and only supports TTU_RMAP_LOCKED and
2131 * TTU_SPLIT_HUGE_PMD and TTU_SYNC flags.
2132 */
2133 if (WARN_ON_ONCE(flags & ~(TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
2134 TTU_SYNC)))
2135 return;
2136
f25cbb7a
AS
2137 if (folio_is_zone_device(folio) &&
2138 (!folio_is_device_private(folio) && !folio_is_device_coherent(folio)))
6c855fce
HD
2139 return;
2140
52629506
JK
2141 /*
2142 * During exec, a temporary VMA is setup and later moved.
2143 * The VMA is moved under the anon_vma lock but not the
2144 * page tables leading to a race where migration cannot
2145 * find the migration ptes. Rather than increasing the
2146 * locking requirements of exec(), migration skips
2147 * temporary VMAs until after exec() completes.
2148 */
4b8554c5 2149 if (!folio_test_ksm(folio) && folio_test_anon(folio))
52629506
JK
2150 rwc.invalid_vma = invalid_migration_vma;
2151
2a52bcbc 2152 if (flags & TTU_RMAP_LOCKED)
2f031c6f 2153 rmap_walk_locked(folio, &rwc);
2a52bcbc 2154 else
2f031c6f 2155 rmap_walk(folio, &rwc);
b291f000 2156}
e9995ef9 2157
b756a3b5
AP
2158#ifdef CONFIG_DEVICE_PRIVATE
2159struct make_exclusive_args {
2160 struct mm_struct *mm;
2161 unsigned long address;
2162 void *owner;
2163 bool valid;
2164};
2165
2f031c6f 2166static bool page_make_device_exclusive_one(struct folio *folio,
b756a3b5
AP
2167 struct vm_area_struct *vma, unsigned long address, void *priv)
2168{
2169 struct mm_struct *mm = vma->vm_mm;
0d251485 2170 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
b756a3b5
AP
2171 struct make_exclusive_args *args = priv;
2172 pte_t pteval;
2173 struct page *subpage;
2174 bool ret = true;
2175 struct mmu_notifier_range range;
2176 swp_entry_t entry;
2177 pte_t swp_pte;
2178
2179 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma,
2180 vma->vm_mm, address, min(vma->vm_end,
0d251485
MWO
2181 address + folio_size(folio)),
2182 args->owner);
b756a3b5
AP
2183 mmu_notifier_invalidate_range_start(&range);
2184
2185 while (page_vma_mapped_walk(&pvmw)) {
2186 /* Unexpected PMD-mapped THP? */
0d251485 2187 VM_BUG_ON_FOLIO(!pvmw.pte, folio);
b756a3b5
AP
2188
2189 if (!pte_present(*pvmw.pte)) {
2190 ret = false;
2191 page_vma_mapped_walk_done(&pvmw);
2192 break;
2193 }
2194
0d251485
MWO
2195 subpage = folio_page(folio,
2196 pte_pfn(*pvmw.pte) - folio_pfn(folio));
b756a3b5
AP
2197 address = pvmw.address;
2198
2199 /* Nuke the page table entry. */
2200 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
2201 pteval = ptep_clear_flush(vma, address, pvmw.pte);
2202
0d251485 2203 /* Set the dirty flag on the folio now the pte is gone. */
b756a3b5 2204 if (pte_dirty(pteval))
0d251485 2205 folio_mark_dirty(folio);
b756a3b5
AP
2206
2207 /*
2208 * Check that our target page is still mapped at the expected
2209 * address.
2210 */
2211 if (args->mm == mm && args->address == address &&
2212 pte_write(pteval))
2213 args->valid = true;
2214
2215 /*
2216 * Store the pfn of the page in a special migration
2217 * pte. do_swap_page() will wait until the migration
2218 * pte is removed and then restart fault handling.
2219 */
2220 if (pte_write(pteval))
2221 entry = make_writable_device_exclusive_entry(
2222 page_to_pfn(subpage));
2223 else
2224 entry = make_readable_device_exclusive_entry(
2225 page_to_pfn(subpage));
2226 swp_pte = swp_entry_to_pte(entry);
2227 if (pte_soft_dirty(pteval))
2228 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2229 if (pte_uffd_wp(pteval))
2230 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2231
2232 set_pte_at(mm, address, pvmw.pte, swp_pte);
2233
2234 /*
2235 * There is a reference on the page for the swap entry which has
2236 * been removed, so shouldn't take another.
2237 */
cea86fe2 2238 page_remove_rmap(subpage, vma, false);
b756a3b5
AP
2239 }
2240
2241 mmu_notifier_invalidate_range_end(&range);
2242
2243 return ret;
2244}
2245
2246/**
0d251485
MWO
2247 * folio_make_device_exclusive - Mark the folio exclusively owned by a device.
2248 * @folio: The folio to replace page table entries for.
2249 * @mm: The mm_struct where the folio is expected to be mapped.
2250 * @address: Address where the folio is expected to be mapped.
b756a3b5
AP
2251 * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier callbacks
2252 *
0d251485
MWO
2253 * Tries to remove all the page table entries which are mapping this
2254 * folio and replace them with special device exclusive swap entries to
2255 * grant a device exclusive access to the folio.
b756a3b5 2256 *
0d251485
MWO
2257 * Context: Caller must hold the folio lock.
2258 * Return: false if the page is still mapped, or if it could not be unmapped
b756a3b5
AP
2259 * from the expected address. Otherwise returns true (success).
2260 */
0d251485
MWO
2261static bool folio_make_device_exclusive(struct folio *folio,
2262 struct mm_struct *mm, unsigned long address, void *owner)
b756a3b5
AP
2263{
2264 struct make_exclusive_args args = {
2265 .mm = mm,
2266 .address = address,
2267 .owner = owner,
2268 .valid = false,
2269 };
2270 struct rmap_walk_control rwc = {
2271 .rmap_one = page_make_device_exclusive_one,
2272 .done = page_not_mapped,
2f031c6f 2273 .anon_lock = folio_lock_anon_vma_read,
b756a3b5
AP
2274 .arg = &args,
2275 };
2276
2277 /*
0d251485
MWO
2278 * Restrict to anonymous folios for now to avoid potential writeback
2279 * issues.
b756a3b5 2280 */
0d251485 2281 if (!folio_test_anon(folio))
b756a3b5
AP
2282 return false;
2283
2f031c6f 2284 rmap_walk(folio, &rwc);
b756a3b5 2285
0d251485 2286 return args.valid && !folio_mapcount(folio);
b756a3b5
AP
2287}
2288
2289/**
2290 * make_device_exclusive_range() - Mark a range for exclusive use by a device
dd062302 2291 * @mm: mm_struct of associated target process
b756a3b5
AP
2292 * @start: start of the region to mark for exclusive device access
2293 * @end: end address of region
2294 * @pages: returns the pages which were successfully marked for exclusive access
2295 * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
2296 *
2297 * Returns: number of pages found in the range by GUP. A page is marked for
2298 * exclusive access only if the page pointer is non-NULL.
2299 *
2300 * This function finds ptes mapping page(s) to the given address range, locks
2301 * them and replaces mappings with special swap entries preventing userspace CPU
2302 * access. On fault these entries are replaced with the original mapping after
2303 * calling MMU notifiers.
2304 *
2305 * A driver using this to program access from a device must use a mmu notifier
2306 * critical section to hold a device specific lock during programming. Once
2307 * programming is complete it should drop the page lock and reference after
2308 * which point CPU access to the page will revoke the exclusive access.
2309 */
2310int make_device_exclusive_range(struct mm_struct *mm, unsigned long start,
2311 unsigned long end, struct page **pages,
2312 void *owner)
2313{
2314 long npages = (end - start) >> PAGE_SHIFT;
2315 long i;
2316
2317 npages = get_user_pages_remote(mm, start, npages,
2318 FOLL_GET | FOLL_WRITE | FOLL_SPLIT_PMD,
2319 pages, NULL, NULL);
2320 if (npages < 0)
2321 return npages;
2322
2323 for (i = 0; i < npages; i++, start += PAGE_SIZE) {
0d251485
MWO
2324 struct folio *folio = page_folio(pages[i]);
2325 if (PageTail(pages[i]) || !folio_trylock(folio)) {
2326 folio_put(folio);
b756a3b5
AP
2327 pages[i] = NULL;
2328 continue;
2329 }
2330
0d251485
MWO
2331 if (!folio_make_device_exclusive(folio, mm, start, owner)) {
2332 folio_unlock(folio);
2333 folio_put(folio);
b756a3b5
AP
2334 pages[i] = NULL;
2335 }
2336 }
2337
2338 return npages;
2339}
2340EXPORT_SYMBOL_GPL(make_device_exclusive_range);
2341#endif
2342
01d8b20d 2343void __put_anon_vma(struct anon_vma *anon_vma)
76545066 2344{
01d8b20d 2345 struct anon_vma *root = anon_vma->root;
76545066 2346
624483f3 2347 anon_vma_free(anon_vma);
01d8b20d
PZ
2348 if (root != anon_vma && atomic_dec_and_test(&root->refcount))
2349 anon_vma_free(root);
76545066 2350}
76545066 2351
2f031c6f 2352static struct anon_vma *rmap_walk_anon_lock(struct folio *folio,
6d4675e6 2353 struct rmap_walk_control *rwc)
faecd8dd
JK
2354{
2355 struct anon_vma *anon_vma;
2356
0dd1c7bb 2357 if (rwc->anon_lock)
6d4675e6 2358 return rwc->anon_lock(folio, rwc);
0dd1c7bb 2359
faecd8dd 2360 /*
2f031c6f 2361 * Note: remove_migration_ptes() cannot use folio_lock_anon_vma_read()
faecd8dd 2362 * because that depends on page_mapped(); but not all its usages
c1e8d7c6 2363 * are holding mmap_lock. Users without mmap_lock are required to
faecd8dd
JK
2364 * take a reference count to prevent the anon_vma disappearing
2365 */
e05b3453 2366 anon_vma = folio_anon_vma(folio);
faecd8dd
JK
2367 if (!anon_vma)
2368 return NULL;
2369
6d4675e6
MK
2370 if (anon_vma_trylock_read(anon_vma))
2371 goto out;
2372
2373 if (rwc->try_lock) {
2374 anon_vma = NULL;
2375 rwc->contended = true;
2376 goto out;
2377 }
2378
faecd8dd 2379 anon_vma_lock_read(anon_vma);
6d4675e6 2380out:
faecd8dd
JK
2381 return anon_vma;
2382}
2383
e9995ef9 2384/*
e8351ac9
JK
2385 * rmap_walk_anon - do something to anonymous page using the object-based
2386 * rmap method
2387 * @page: the page to be handled
2388 * @rwc: control variable according to each walk type
2389 *
2390 * Find all the mappings of a page using the mapping pointer and the vma chains
2391 * contained in the anon_vma struct it points to.
e9995ef9 2392 */
84fbbe21 2393static void rmap_walk_anon(struct folio *folio,
6d4675e6 2394 struct rmap_walk_control *rwc, bool locked)
e9995ef9
HD
2395{
2396 struct anon_vma *anon_vma;
a8fa41ad 2397 pgoff_t pgoff_start, pgoff_end;
5beb4930 2398 struct anon_vma_chain *avc;
e9995ef9 2399
b9773199 2400 if (locked) {
e05b3453 2401 anon_vma = folio_anon_vma(folio);
b9773199 2402 /* anon_vma disappear under us? */
e05b3453 2403 VM_BUG_ON_FOLIO(!anon_vma, folio);
b9773199 2404 } else {
2f031c6f 2405 anon_vma = rmap_walk_anon_lock(folio, rwc);
b9773199 2406 }
e9995ef9 2407 if (!anon_vma)
1df631ae 2408 return;
faecd8dd 2409
2f031c6f
MWO
2410 pgoff_start = folio_pgoff(folio);
2411 pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
a8fa41ad
KS
2412 anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
2413 pgoff_start, pgoff_end) {
5beb4930 2414 struct vm_area_struct *vma = avc->vma;
2f031c6f 2415 unsigned long address = vma_address(&folio->page, vma);
0dd1c7bb 2416
494334e4 2417 VM_BUG_ON_VMA(address == -EFAULT, vma);
ad12695f
AA
2418 cond_resched();
2419
0dd1c7bb
JK
2420 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2421 continue;
2422
2f031c6f 2423 if (!rwc->rmap_one(folio, vma, address, rwc->arg))
e9995ef9 2424 break;
2f031c6f 2425 if (rwc->done && rwc->done(folio))
0dd1c7bb 2426 break;
e9995ef9 2427 }
b9773199
KS
2428
2429 if (!locked)
2430 anon_vma_unlock_read(anon_vma);
e9995ef9
HD
2431}
2432
e8351ac9
JK
2433/*
2434 * rmap_walk_file - do something to file page using the object-based rmap method
2435 * @page: the page to be handled
2436 * @rwc: control variable according to each walk type
2437 *
2438 * Find all the mappings of a page using the mapping pointer and the vma chains
2439 * contained in the address_space struct it points to.
e8351ac9 2440 */
84fbbe21 2441static void rmap_walk_file(struct folio *folio,
6d4675e6 2442 struct rmap_walk_control *rwc, bool locked)
e9995ef9 2443{
2f031c6f 2444 struct address_space *mapping = folio_mapping(folio);
a8fa41ad 2445 pgoff_t pgoff_start, pgoff_end;
e9995ef9 2446 struct vm_area_struct *vma;
e9995ef9 2447
9f32624b
JK
2448 /*
2449 * The page lock not only makes sure that page->mapping cannot
2450 * suddenly be NULLified by truncation, it makes sure that the
2451 * structure at mapping cannot be freed and reused yet,
c8c06efa 2452 * so we can safely take mapping->i_mmap_rwsem.
9f32624b 2453 */
2f031c6f 2454 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
9f32624b 2455
e9995ef9 2456 if (!mapping)
1df631ae 2457 return;
3dec0ba0 2458
2f031c6f
MWO
2459 pgoff_start = folio_pgoff(folio);
2460 pgoff_end = pgoff_start + folio_nr_pages(folio) - 1;
6d4675e6
MK
2461 if (!locked) {
2462 if (i_mmap_trylock_read(mapping))
2463 goto lookup;
2464
2465 if (rwc->try_lock) {
2466 rwc->contended = true;
2467 return;
2468 }
2469
b9773199 2470 i_mmap_lock_read(mapping);
6d4675e6
MK
2471 }
2472lookup:
a8fa41ad
KS
2473 vma_interval_tree_foreach(vma, &mapping->i_mmap,
2474 pgoff_start, pgoff_end) {
2f031c6f 2475 unsigned long address = vma_address(&folio->page, vma);
0dd1c7bb 2476
494334e4 2477 VM_BUG_ON_VMA(address == -EFAULT, vma);
ad12695f
AA
2478 cond_resched();
2479
0dd1c7bb
JK
2480 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2481 continue;
2482
2f031c6f 2483 if (!rwc->rmap_one(folio, vma, address, rwc->arg))
0dd1c7bb 2484 goto done;
2f031c6f 2485 if (rwc->done && rwc->done(folio))
0dd1c7bb 2486 goto done;
e9995ef9 2487 }
0dd1c7bb 2488
0dd1c7bb 2489done:
b9773199
KS
2490 if (!locked)
2491 i_mmap_unlock_read(mapping);
e9995ef9
HD
2492}
2493
6d4675e6 2494void rmap_walk(struct folio *folio, struct rmap_walk_control *rwc)
e9995ef9 2495{
2f031c6f
MWO
2496 if (unlikely(folio_test_ksm(folio)))
2497 rmap_walk_ksm(folio, rwc);
2498 else if (folio_test_anon(folio))
2499 rmap_walk_anon(folio, rwc, false);
b9773199 2500 else
2f031c6f 2501 rmap_walk_file(folio, rwc, false);
b9773199
KS
2502}
2503
2504/* Like rmap_walk, but caller holds relevant rmap lock */
6d4675e6 2505void rmap_walk_locked(struct folio *folio, struct rmap_walk_control *rwc)
b9773199
KS
2506{
2507 /* no ksm support for now */
2f031c6f
MWO
2508 VM_BUG_ON_FOLIO(folio_test_ksm(folio), folio);
2509 if (folio_test_anon(folio))
2510 rmap_walk_anon(folio, rwc, true);
e9995ef9 2511 else
2f031c6f 2512 rmap_walk_file(folio, rwc, true);
e9995ef9 2513}
0fe6e20b 2514
e3390f67 2515#ifdef CONFIG_HUGETLB_PAGE
0fe6e20b 2516/*
451b9514 2517 * The following two functions are for anonymous (private mapped) hugepages.
0fe6e20b
NH
2518 * Unlike common anonymous pages, anonymous hugepages have no accounting code
2519 * and no lru code, because we handle hugepages differently from common pages.
28c5209d
DH
2520 *
2521 * RMAP_COMPOUND is ignored.
0fe6e20b 2522 */
28c5209d
DH
2523void hugepage_add_anon_rmap(struct page *page, struct vm_area_struct *vma,
2524 unsigned long address, rmap_t flags)
0fe6e20b
NH
2525{
2526 struct anon_vma *anon_vma = vma->anon_vma;
2527 int first;
a850ea30
NH
2528
2529 BUG_ON(!PageLocked(page));
0fe6e20b 2530 BUG_ON(!anon_vma);
5dbe0af4 2531 /* address might be in next vma when migration races vma_adjust */
53f9263b 2532 first = atomic_inc_and_test(compound_mapcount_ptr(page));
6c287605
DH
2533 VM_BUG_ON_PAGE(!first && (flags & RMAP_EXCLUSIVE), page);
2534 VM_BUG_ON_PAGE(!first && PageAnonExclusive(page), page);
0fe6e20b 2535 if (first)
28c5209d
DH
2536 __page_set_anon_rmap(page, vma, address,
2537 !!(flags & RMAP_EXCLUSIVE));
0fe6e20b
NH
2538}
2539
2540void hugepage_add_new_anon_rmap(struct page *page,
2541 struct vm_area_struct *vma, unsigned long address)
2542{
2543 BUG_ON(address < vma->vm_start || address >= vma->vm_end);
53f9263b 2544 atomic_set(compound_mapcount_ptr(page), 0);
5232c63f 2545 atomic_set(compound_pincount_ptr(page), 0);
47e29d32 2546
451b9514 2547 __page_set_anon_rmap(page, vma, address, 1);
0fe6e20b 2548}
e3390f67 2549#endif /* CONFIG_HUGETLB_PAGE */