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