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