mm/rmap: Turn page_referenced() into folio_referenced()
[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)
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)
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
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
5ee2fa2f
HY
624/*
625 * Bits 0-14 of mm->tlb_flush_batched record pending generations.
626 * Bits 16-30 of mm->tlb_flush_batched bit record flushed generations.
627 */
628#define TLB_FLUSH_BATCH_FLUSHED_SHIFT 16
629#define TLB_FLUSH_BATCH_PENDING_MASK \
630 ((1 << (TLB_FLUSH_BATCH_FLUSHED_SHIFT - 1)) - 1)
631#define TLB_FLUSH_BATCH_PENDING_LARGE \
632 (TLB_FLUSH_BATCH_PENDING_MASK / 2)
633
c7ab0d2f 634static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
72b252ae
MG
635{
636 struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
5ee2fa2f 637 int batch, nbatch;
72b252ae 638
e73ad5ff 639 arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
72b252ae 640 tlb_ubc->flush_required = true;
d950c947 641
3ea27719
MG
642 /*
643 * Ensure compiler does not re-order the setting of tlb_flush_batched
644 * before the PTE is cleared.
645 */
646 barrier();
5ee2fa2f
HY
647 batch = atomic_read(&mm->tlb_flush_batched);
648retry:
649 if ((batch & TLB_FLUSH_BATCH_PENDING_MASK) > TLB_FLUSH_BATCH_PENDING_LARGE) {
650 /*
651 * Prevent `pending' from catching up with `flushed' because of
652 * overflow. Reset `pending' and `flushed' to be 1 and 0 if
653 * `pending' becomes large.
654 */
655 nbatch = atomic_cmpxchg(&mm->tlb_flush_batched, batch, 1);
656 if (nbatch != batch) {
657 batch = nbatch;
658 goto retry;
659 }
660 } else {
661 atomic_inc(&mm->tlb_flush_batched);
662 }
3ea27719 663
d950c947
MG
664 /*
665 * If the PTE was dirty then it's best to assume it's writable. The
666 * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
667 * before the page is queued for IO.
668 */
669 if (writable)
670 tlb_ubc->writable = true;
72b252ae
MG
671}
672
673/*
674 * Returns true if the TLB flush should be deferred to the end of a batch of
675 * unmap operations to reduce IPIs.
676 */
677static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
678{
679 bool should_defer = false;
680
681 if (!(flags & TTU_BATCH_FLUSH))
682 return false;
683
684 /* If remote CPUs need to be flushed then defer batch the flush */
685 if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
686 should_defer = true;
687 put_cpu();
688
689 return should_defer;
690}
3ea27719
MG
691
692/*
693 * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
694 * releasing the PTL if TLB flushes are batched. It's possible for a parallel
695 * operation such as mprotect or munmap to race between reclaim unmapping
696 * the page and flushing the page. If this race occurs, it potentially allows
697 * access to data via a stale TLB entry. Tracking all mm's that have TLB
698 * batching in flight would be expensive during reclaim so instead track
699 * whether TLB batching occurred in the past and if so then do a flush here
700 * if required. This will cost one additional flush per reclaim cycle paid
701 * by the first operation at risk such as mprotect and mumap.
702 *
703 * This must be called under the PTL so that an access to tlb_flush_batched
704 * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
705 * via the PTL.
706 */
707void flush_tlb_batched_pending(struct mm_struct *mm)
708{
5ee2fa2f
HY
709 int batch = atomic_read(&mm->tlb_flush_batched);
710 int pending = batch & TLB_FLUSH_BATCH_PENDING_MASK;
711 int flushed = batch >> TLB_FLUSH_BATCH_FLUSHED_SHIFT;
3ea27719 712
5ee2fa2f
HY
713 if (pending != flushed) {
714 flush_tlb_mm(mm);
3ea27719 715 /*
5ee2fa2f
HY
716 * If the new TLB flushing is pending during flushing, leave
717 * mm->tlb_flush_batched as is, to avoid losing flushing.
3ea27719 718 */
5ee2fa2f
HY
719 atomic_cmpxchg(&mm->tlb_flush_batched, batch,
720 pending | (pending << TLB_FLUSH_BATCH_FLUSHED_SHIFT));
3ea27719
MG
721 }
722}
72b252ae 723#else
c7ab0d2f 724static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
72b252ae
MG
725{
726}
727
728static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
729{
730 return false;
731}
732#endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
733
1da177e4 734/*
bf89c8c8 735 * At what user virtual address is page expected in vma?
ab941e0f 736 * Caller should check the page is actually part of the vma.
1da177e4
LT
737 */
738unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
739{
21d0d443 740 if (PageAnon(page)) {
4829b906
HD
741 struct anon_vma *page__anon_vma = page_anon_vma(page);
742 /*
743 * Note: swapoff's unuse_vma() is more efficient with this
744 * check, and needs it to match anon_vma when KSM is active.
745 */
746 if (!vma->anon_vma || !page__anon_vma ||
747 vma->anon_vma->root != page__anon_vma->root)
21d0d443 748 return -EFAULT;
31657170
JW
749 } else if (!vma->vm_file) {
750 return -EFAULT;
751 } else if (vma->vm_file->f_mapping != compound_head(page)->mapping) {
1da177e4 752 return -EFAULT;
31657170 753 }
494334e4
HD
754
755 return vma_address(page, vma);
1da177e4
LT
756}
757
6219049a
BL
758pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
759{
760 pgd_t *pgd;
c2febafc 761 p4d_t *p4d;
6219049a
BL
762 pud_t *pud;
763 pmd_t *pmd = NULL;
f72e7dcd 764 pmd_t pmde;
6219049a
BL
765
766 pgd = pgd_offset(mm, address);
767 if (!pgd_present(*pgd))
768 goto out;
769
c2febafc
KS
770 p4d = p4d_offset(pgd, address);
771 if (!p4d_present(*p4d))
772 goto out;
773
774 pud = pud_offset(p4d, address);
6219049a
BL
775 if (!pud_present(*pud))
776 goto out;
777
778 pmd = pmd_offset(pud, address);
f72e7dcd 779 /*
8809aa2d 780 * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
f72e7dcd
HD
781 * without holding anon_vma lock for write. So when looking for a
782 * genuine pmde (in which to find pte), test present and !THP together.
783 */
e37c6982
CB
784 pmde = *pmd;
785 barrier();
f72e7dcd 786 if (!pmd_present(pmde) || pmd_trans_huge(pmde))
6219049a
BL
787 pmd = NULL;
788out:
789 return pmd;
790}
791
b3ac0413 792struct folio_referenced_arg {
8749cfea
VD
793 int mapcount;
794 int referenced;
795 unsigned long vm_flags;
796 struct mem_cgroup *memcg;
797};
798/*
b3ac0413 799 * arg: folio_referenced_arg will be passed
8749cfea 800 */
b3ac0413 801static bool folio_referenced_one(struct page *page, struct vm_area_struct *vma,
8749cfea
VD
802 unsigned long address, void *arg)
803{
b3ac0413
MWO
804 struct folio *folio = page_folio(page);
805 struct folio_referenced_arg *pra = arg;
806 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, 0);
8749cfea
VD
807 int referenced = 0;
808
8eaedede
KS
809 while (page_vma_mapped_walk(&pvmw)) {
810 address = pvmw.address;
b20ce5e0 811
47d4f3ee 812 if ((vma->vm_flags & VM_LOCKED) &&
b3ac0413 813 (!folio_test_large(folio) || !pvmw.pte)) {
47d4f3ee 814 /* Restore the mlock which got missed */
b3ac0413 815 mlock_vma_folio(folio, vma, !pvmw.pte);
8eaedede
KS
816 page_vma_mapped_walk_done(&pvmw);
817 pra->vm_flags |= VM_LOCKED;
e4b82222 818 return false; /* To break the loop */
8eaedede 819 }
71e3aac0 820
8eaedede
KS
821 if (pvmw.pte) {
822 if (ptep_clear_flush_young_notify(vma, address,
823 pvmw.pte)) {
824 /*
825 * Don't treat a reference through
826 * a sequentially read mapping as such.
b3ac0413 827 * If the folio has been used in another mapping,
8eaedede
KS
828 * we will catch it; if this other mapping is
829 * already gone, the unmap path will have set
b3ac0413 830 * the referenced flag or activated the folio.
8eaedede
KS
831 */
832 if (likely(!(vma->vm_flags & VM_SEQ_READ)))
833 referenced++;
834 }
835 } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
836 if (pmdp_clear_flush_young_notify(vma, address,
837 pvmw.pmd))
8749cfea 838 referenced++;
8eaedede 839 } else {
b3ac0413 840 /* unexpected pmd-mapped folio? */
8eaedede 841 WARN_ON_ONCE(1);
8749cfea 842 }
8eaedede
KS
843
844 pra->mapcount--;
b20ce5e0 845 }
b20ce5e0 846
33c3fc71 847 if (referenced)
b3ac0413
MWO
848 folio_clear_idle(folio);
849 if (folio_test_clear_young(folio))
33c3fc71
VD
850 referenced++;
851
9f32624b
JK
852 if (referenced) {
853 pra->referenced++;
47d4f3ee 854 pra->vm_flags |= vma->vm_flags & ~VM_LOCKED;
1da177e4 855 }
34bbd704 856
9f32624b 857 if (!pra->mapcount)
e4b82222 858 return false; /* To break the loop */
9f32624b 859
e4b82222 860 return true;
1da177e4
LT
861}
862
b3ac0413 863static bool invalid_folio_referenced_vma(struct vm_area_struct *vma, void *arg)
1da177e4 864{
b3ac0413 865 struct folio_referenced_arg *pra = arg;
9f32624b 866 struct mem_cgroup *memcg = pra->memcg;
1da177e4 867
9f32624b
JK
868 if (!mm_match_cgroup(vma->vm_mm, memcg))
869 return true;
1da177e4 870
9f32624b 871 return false;
1da177e4
LT
872}
873
874/**
b3ac0413
MWO
875 * folio_referenced() - Test if the folio was referenced.
876 * @folio: The folio to test.
877 * @is_locked: Caller holds lock on the folio.
72835c86 878 * @memcg: target memory cgroup
b3ac0413 879 * @vm_flags: A combination of all the vma->vm_flags which referenced the folio.
1da177e4 880 *
b3ac0413
MWO
881 * Quick test_and_clear_referenced for all mappings of a folio,
882 *
883 * Return: The number of mappings which referenced the folio.
1da177e4 884 */
b3ac0413
MWO
885int folio_referenced(struct folio *folio, int is_locked,
886 struct mem_cgroup *memcg, unsigned long *vm_flags)
1da177e4 887{
5ad64688 888 int we_locked = 0;
b3ac0413
MWO
889 struct folio_referenced_arg pra = {
890 .mapcount = folio_mapcount(folio),
9f32624b
JK
891 .memcg = memcg,
892 };
893 struct rmap_walk_control rwc = {
b3ac0413 894 .rmap_one = folio_referenced_one,
9f32624b
JK
895 .arg = (void *)&pra,
896 .anon_lock = page_lock_anon_vma_read,
897 };
1da177e4 898
6fe6b7e3 899 *vm_flags = 0;
059d8442 900 if (!pra.mapcount)
9f32624b
JK
901 return 0;
902
b3ac0413 903 if (!folio_raw_mapping(folio))
9f32624b
JK
904 return 0;
905
b3ac0413
MWO
906 if (!is_locked && (!folio_test_anon(folio) || folio_test_ksm(folio))) {
907 we_locked = folio_trylock(folio);
9f32624b
JK
908 if (!we_locked)
909 return 1;
1da177e4 910 }
9f32624b
JK
911
912 /*
913 * If we are reclaiming on behalf of a cgroup, skip
914 * counting on behalf of references from different
915 * cgroups
916 */
917 if (memcg) {
b3ac0413 918 rwc.invalid_vma = invalid_folio_referenced_vma;
9f32624b
JK
919 }
920
b3ac0413 921 rmap_walk(&folio->page, &rwc);
9f32624b
JK
922 *vm_flags = pra.vm_flags;
923
924 if (we_locked)
b3ac0413 925 folio_unlock(folio);
9f32624b
JK
926
927 return pra.referenced;
1da177e4
LT
928}
929
e4b82222 930static bool page_mkclean_one(struct page *page, struct vm_area_struct *vma,
9853a407 931 unsigned long address, void *arg)
d08b3851 932{
e83c09a2
MWO
933 struct folio *folio = page_folio(page);
934 DEFINE_FOLIO_VMA_WALK(pvmw, folio, vma, address, PVMW_SYNC);
ac46d4f3 935 struct mmu_notifier_range range;
9853a407 936 int *cleaned = arg;
d08b3851 937
369ea824
JG
938 /*
939 * We have to assume the worse case ie pmd for invalidation. Note that
e83c09a2 940 * the folio can not be freed from this function.
369ea824 941 */
7269f999
JG
942 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
943 0, vma, vma->vm_mm, address,
2aff7a47 944 vma_address_end(&pvmw));
ac46d4f3 945 mmu_notifier_invalidate_range_start(&range);
369ea824 946
f27176cf
KS
947 while (page_vma_mapped_walk(&pvmw)) {
948 int ret = 0;
369ea824 949
1f18b296 950 address = pvmw.address;
f27176cf
KS
951 if (pvmw.pte) {
952 pte_t entry;
953 pte_t *pte = pvmw.pte;
954
955 if (!pte_dirty(*pte) && !pte_write(*pte))
956 continue;
957
785373b4
LT
958 flush_cache_page(vma, address, pte_pfn(*pte));
959 entry = ptep_clear_flush(vma, address, pte);
f27176cf
KS
960 entry = pte_wrprotect(entry);
961 entry = pte_mkclean(entry);
785373b4 962 set_pte_at(vma->vm_mm, address, pte, entry);
f27176cf
KS
963 ret = 1;
964 } else {
396bcc52 965#ifdef CONFIG_TRANSPARENT_HUGEPAGE
f27176cf
KS
966 pmd_t *pmd = pvmw.pmd;
967 pmd_t entry;
968
969 if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
970 continue;
971
e83c09a2 972 flush_cache_page(vma, address, folio_pfn(folio));
024eee0e 973 entry = pmdp_invalidate(vma, address, pmd);
f27176cf
KS
974 entry = pmd_wrprotect(entry);
975 entry = pmd_mkclean(entry);
785373b4 976 set_pmd_at(vma->vm_mm, address, pmd, entry);
f27176cf
KS
977 ret = 1;
978#else
e83c09a2 979 /* unexpected pmd-mapped folio? */
f27176cf
KS
980 WARN_ON_ONCE(1);
981#endif
982 }
d08b3851 983
0f10851e
JG
984 /*
985 * No need to call mmu_notifier_invalidate_range() as we are
986 * downgrading page table protection not changing it to point
987 * to a new page.
988 *
ad56b738 989 * See Documentation/vm/mmu_notifier.rst
0f10851e
JG
990 */
991 if (ret)
f27176cf 992 (*cleaned)++;
c2fda5fe 993 }
d08b3851 994
ac46d4f3 995 mmu_notifier_invalidate_range_end(&range);
369ea824 996
e4b82222 997 return true;
d08b3851
PZ
998}
999
9853a407 1000static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
d08b3851 1001{
9853a407 1002 if (vma->vm_flags & VM_SHARED)
871beb8c 1003 return false;
d08b3851 1004
871beb8c 1005 return true;
d08b3851
PZ
1006}
1007
d9c08e22 1008int folio_mkclean(struct folio *folio)
d08b3851 1009{
9853a407
JK
1010 int cleaned = 0;
1011 struct address_space *mapping;
1012 struct rmap_walk_control rwc = {
1013 .arg = (void *)&cleaned,
1014 .rmap_one = page_mkclean_one,
1015 .invalid_vma = invalid_mkclean_vma,
1016 };
d08b3851 1017
d9c08e22 1018 BUG_ON(!folio_test_locked(folio));
d08b3851 1019
d9c08e22 1020 if (!folio_mapped(folio))
9853a407
JK
1021 return 0;
1022
d9c08e22 1023 mapping = folio_mapping(folio);
9853a407
JK
1024 if (!mapping)
1025 return 0;
1026
d9c08e22 1027 rmap_walk(&folio->page, &rwc);
d08b3851 1028
9853a407 1029 return cleaned;
d08b3851 1030}
d9c08e22 1031EXPORT_SYMBOL_GPL(folio_mkclean);
d08b3851 1032
c44b6743
RR
1033/**
1034 * page_move_anon_rmap - move a page to our anon_vma
1035 * @page: the page to move to our anon_vma
1036 * @vma: the vma the page belongs to
c44b6743
RR
1037 *
1038 * When a page belongs exclusively to one process after a COW event,
1039 * that page can be moved into the anon_vma that belongs to just that
1040 * process, so the rmap code will not search the parent or sibling
1041 * processes.
1042 */
5a49973d 1043void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
c44b6743
RR
1044{
1045 struct anon_vma *anon_vma = vma->anon_vma;
1046
5a49973d
HD
1047 page = compound_head(page);
1048
309381fe 1049 VM_BUG_ON_PAGE(!PageLocked(page), page);
81d1b09c 1050 VM_BUG_ON_VMA(!anon_vma, vma);
c44b6743
RR
1051
1052 anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
414e2fb8
VD
1053 /*
1054 * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
b3ac0413
MWO
1055 * simultaneously, so a concurrent reader (eg folio_referenced()'s
1056 * folio_test_anon()) will not see one without the other.
414e2fb8
VD
1057 */
1058 WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
c44b6743
RR
1059}
1060
9617d95e 1061/**
4e1c1975 1062 * __page_set_anon_rmap - set up new anonymous rmap
451b9514 1063 * @page: Page or Hugepage to add to rmap
4e1c1975
AK
1064 * @vma: VM area to add page to.
1065 * @address: User virtual address of the mapping
e8a03feb 1066 * @exclusive: the page is exclusively owned by the current process
9617d95e
NP
1067 */
1068static void __page_set_anon_rmap(struct page *page,
e8a03feb 1069 struct vm_area_struct *vma, unsigned long address, int exclusive)
9617d95e 1070{
e8a03feb 1071 struct anon_vma *anon_vma = vma->anon_vma;
ea90002b 1072
e8a03feb 1073 BUG_ON(!anon_vma);
ea90002b 1074
4e1c1975
AK
1075 if (PageAnon(page))
1076 return;
1077
ea90002b 1078 /*
e8a03feb
RR
1079 * If the page isn't exclusively mapped into this vma,
1080 * we must use the _oldest_ possible anon_vma for the
1081 * page mapping!
ea90002b 1082 */
4e1c1975 1083 if (!exclusive)
288468c3 1084 anon_vma = anon_vma->root;
9617d95e 1085
16f5e707
AS
1086 /*
1087 * page_idle does a lockless/optimistic rmap scan on page->mapping.
1088 * Make sure the compiler doesn't split the stores of anon_vma and
1089 * the PAGE_MAPPING_ANON type identifier, otherwise the rmap code
1090 * could mistake the mapping for a struct address_space and crash.
1091 */
9617d95e 1092 anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
16f5e707 1093 WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
9617d95e 1094 page->index = linear_page_index(vma, address);
9617d95e
NP
1095}
1096
c97a9e10 1097/**
43d8eac4 1098 * __page_check_anon_rmap - sanity check anonymous rmap addition
c97a9e10
NP
1099 * @page: the page to add the mapping to
1100 * @vma: the vm area in which the mapping is added
1101 * @address: the user virtual address mapped
1102 */
1103static void __page_check_anon_rmap(struct page *page,
1104 struct vm_area_struct *vma, unsigned long address)
1105{
c97a9e10
NP
1106 /*
1107 * The page's anon-rmap details (mapping and index) are guaranteed to
1108 * be set up correctly at this point.
1109 *
1110 * We have exclusion against page_add_anon_rmap because the caller
90aaca85 1111 * always holds the page locked.
c97a9e10
NP
1112 *
1113 * We have exclusion against page_add_new_anon_rmap because those pages
1114 * are initially only visible via the pagetables, and the pte is locked
1115 * over the call to page_add_new_anon_rmap.
1116 */
30c46382
YS
1117 VM_BUG_ON_PAGE(page_anon_vma(page)->root != vma->anon_vma->root, page);
1118 VM_BUG_ON_PAGE(page_to_pgoff(page) != linear_page_index(vma, address),
1119 page);
c97a9e10
NP
1120}
1121
1da177e4
LT
1122/**
1123 * page_add_anon_rmap - add pte mapping to an anonymous page
1124 * @page: the page to add the mapping to
1125 * @vma: the vm area in which the mapping is added
1126 * @address: the user virtual address mapped
d281ee61 1127 * @compound: charge the page as compound or small page
1da177e4 1128 *
5ad64688 1129 * The caller needs to hold the pte lock, and the page must be locked in
80e14822
HD
1130 * the anon_vma case: to serialize mapping,index checking after setting,
1131 * and to ensure that PageAnon is not being upgraded racily to PageKsm
1132 * (but PageKsm is never downgraded to PageAnon).
1da177e4
LT
1133 */
1134void page_add_anon_rmap(struct page *page,
d281ee61 1135 struct vm_area_struct *vma, unsigned long address, bool compound)
ad8c2ee8 1136{
d281ee61 1137 do_page_add_anon_rmap(page, vma, address, compound ? RMAP_COMPOUND : 0);
ad8c2ee8
RR
1138}
1139
1140/*
1141 * Special version of the above for do_swap_page, which often runs
1142 * into pages that are exclusively owned by the current process.
1143 * Everybody else should continue to use page_add_anon_rmap above.
1144 */
1145void do_page_add_anon_rmap(struct page *page,
d281ee61 1146 struct vm_area_struct *vma, unsigned long address, int flags)
1da177e4 1147{
53f9263b
KS
1148 bool compound = flags & RMAP_COMPOUND;
1149 bool first;
1150
be5d0a74
JW
1151 if (unlikely(PageKsm(page)))
1152 lock_page_memcg(page);
1153 else
1154 VM_BUG_ON_PAGE(!PageLocked(page), page);
1155
e9b61f19
KS
1156 if (compound) {
1157 atomic_t *mapcount;
53f9263b 1158 VM_BUG_ON_PAGE(!PageLocked(page), page);
e9b61f19
KS
1159 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
1160 mapcount = compound_mapcount_ptr(page);
1161 first = atomic_inc_and_test(mapcount);
53f9263b
KS
1162 } else {
1163 first = atomic_inc_and_test(&page->_mapcount);
1164 }
1165
79134171 1166 if (first) {
6c357848 1167 int nr = compound ? thp_nr_pages(page) : 1;
bea04b07
JZ
1168 /*
1169 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1170 * these counters are not modified in interrupt context, and
1171 * pte lock(a spinlock) is held, which implies preemption
1172 * disabled.
1173 */
65c45377 1174 if (compound)
69473e5d 1175 __mod_lruvec_page_state(page, NR_ANON_THPS, nr);
be5d0a74 1176 __mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
79134171 1177 }
5ad64688 1178
cea86fe2 1179 if (unlikely(PageKsm(page)))
be5d0a74 1180 unlock_page_memcg(page);
53f9263b 1181
5dbe0af4 1182 /* address might be in next vma when migration races vma_adjust */
cea86fe2 1183 else if (first)
d281ee61
KS
1184 __page_set_anon_rmap(page, vma, address,
1185 flags & RMAP_EXCLUSIVE);
69029cd5 1186 else
c97a9e10 1187 __page_check_anon_rmap(page, vma, address);
cea86fe2
HD
1188
1189 mlock_vma_page(page, vma, compound);
1da177e4
LT
1190}
1191
43d8eac4 1192/**
9617d95e
NP
1193 * page_add_new_anon_rmap - add pte mapping to a new anonymous page
1194 * @page: the page to add the mapping to
1195 * @vma: the vm area in which the mapping is added
1196 * @address: the user virtual address mapped
d281ee61 1197 * @compound: charge the page as compound or small page
9617d95e
NP
1198 *
1199 * Same as page_add_anon_rmap but must only be called on *new* pages.
1200 * This means the inc-and-test can be bypassed.
c97a9e10 1201 * Page does not have to be locked.
9617d95e
NP
1202 */
1203void page_add_new_anon_rmap(struct page *page,
d281ee61 1204 struct vm_area_struct *vma, unsigned long address, bool compound)
9617d95e 1205{
6c357848 1206 int nr = compound ? thp_nr_pages(page) : 1;
d281ee61 1207
81d1b09c 1208 VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
fa9949da 1209 __SetPageSwapBacked(page);
d281ee61
KS
1210 if (compound) {
1211 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
53f9263b
KS
1212 /* increment count (starts at -1) */
1213 atomic_set(compound_mapcount_ptr(page), 0);
5232c63f 1214 atomic_set(compound_pincount_ptr(page), 0);
47e29d32 1215
69473e5d 1216 __mod_lruvec_page_state(page, NR_ANON_THPS, nr);
53f9263b
KS
1217 } else {
1218 /* Anon THP always mapped first with PMD */
1219 VM_BUG_ON_PAGE(PageTransCompound(page), page);
1220 /* increment count (starts at -1) */
1221 atomic_set(&page->_mapcount, 0);
d281ee61 1222 }
be5d0a74 1223 __mod_lruvec_page_state(page, NR_ANON_MAPPED, nr);
e8a03feb 1224 __page_set_anon_rmap(page, vma, address, 1);
9617d95e
NP
1225}
1226
1da177e4
LT
1227/**
1228 * page_add_file_rmap - add pte mapping to a file page
cea86fe2
HD
1229 * @page: the page to add the mapping to
1230 * @vma: the vm area in which the mapping is added
1231 * @compound: charge the page as compound or small page
1da177e4 1232 *
b8072f09 1233 * The caller needs to hold the pte lock.
1da177e4 1234 */
cea86fe2
HD
1235void page_add_file_rmap(struct page *page,
1236 struct vm_area_struct *vma, bool compound)
1da177e4 1237{
dd78fedd
KS
1238 int i, nr = 1;
1239
1240 VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
62cccb8c 1241 lock_page_memcg(page);
dd78fedd 1242 if (compound && PageTransHuge(page)) {
a1528e21
MS
1243 int nr_pages = thp_nr_pages(page);
1244
1245 for (i = 0, nr = 0; i < nr_pages; i++) {
dd78fedd
KS
1246 if (atomic_inc_and_test(&page[i]._mapcount))
1247 nr++;
1248 }
1249 if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
1250 goto out;
99cb0dbd 1251 if (PageSwapBacked(page))
a1528e21
MS
1252 __mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1253 nr_pages);
99cb0dbd 1254 else
380780e7
MS
1255 __mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1256 nr_pages);
dd78fedd 1257 } else {
c8efc390
KS
1258 if (PageTransCompound(page) && page_mapping(page)) {
1259 VM_WARN_ON_ONCE(!PageLocked(page));
cea86fe2 1260 SetPageDoubleMap(compound_head(page));
9a73f61b 1261 }
dd78fedd
KS
1262 if (!atomic_inc_and_test(&page->_mapcount))
1263 goto out;
d69b042f 1264 }
00f3ca2c 1265 __mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
dd78fedd 1266out:
62cccb8c 1267 unlock_page_memcg(page);
cea86fe2
HD
1268
1269 mlock_vma_page(page, vma, compound);
1da177e4
LT
1270}
1271
dd78fedd 1272static void page_remove_file_rmap(struct page *page, bool compound)
8186eb6a 1273{
dd78fedd
KS
1274 int i, nr = 1;
1275
57dea93a 1276 VM_BUG_ON_PAGE(compound && !PageHead(page), page);
8186eb6a 1277
53f9263b
KS
1278 /* Hugepages are not counted in NR_FILE_MAPPED for now. */
1279 if (unlikely(PageHuge(page))) {
1280 /* hugetlb pages are always mapped with pmds */
1281 atomic_dec(compound_mapcount_ptr(page));
be5d0a74 1282 return;
53f9263b 1283 }
8186eb6a 1284
53f9263b 1285 /* page still mapped by someone else? */
dd78fedd 1286 if (compound && PageTransHuge(page)) {
a1528e21
MS
1287 int nr_pages = thp_nr_pages(page);
1288
1289 for (i = 0, nr = 0; i < nr_pages; i++) {
dd78fedd
KS
1290 if (atomic_add_negative(-1, &page[i]._mapcount))
1291 nr++;
1292 }
1293 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
be5d0a74 1294 return;
99cb0dbd 1295 if (PageSwapBacked(page))
a1528e21
MS
1296 __mod_lruvec_page_state(page, NR_SHMEM_PMDMAPPED,
1297 -nr_pages);
99cb0dbd 1298 else
380780e7
MS
1299 __mod_lruvec_page_state(page, NR_FILE_PMDMAPPED,
1300 -nr_pages);
dd78fedd
KS
1301 } else {
1302 if (!atomic_add_negative(-1, &page->_mapcount))
be5d0a74 1303 return;
dd78fedd 1304 }
8186eb6a
JW
1305
1306 /*
00f3ca2c 1307 * We use the irq-unsafe __{inc|mod}_lruvec_page_state because
8186eb6a
JW
1308 * these counters are not modified in interrupt context, and
1309 * pte lock(a spinlock) is held, which implies preemption disabled.
1310 */
00f3ca2c 1311 __mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
8186eb6a
JW
1312}
1313
53f9263b
KS
1314static void page_remove_anon_compound_rmap(struct page *page)
1315{
1316 int i, nr;
1317
1318 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1319 return;
1320
1321 /* Hugepages are not counted in NR_ANON_PAGES for now. */
1322 if (unlikely(PageHuge(page)))
1323 return;
1324
1325 if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1326 return;
1327
69473e5d 1328 __mod_lruvec_page_state(page, NR_ANON_THPS, -thp_nr_pages(page));
53f9263b
KS
1329
1330 if (TestClearPageDoubleMap(page)) {
1331 /*
1332 * Subpages can be mapped with PTEs too. Check how many of
f1fe80d4 1333 * them are still mapped.
53f9263b 1334 */
5eaf35ab 1335 for (i = 0, nr = 0; i < thp_nr_pages(page); i++) {
53f9263b
KS
1336 if (atomic_add_negative(-1, &page[i]._mapcount))
1337 nr++;
1338 }
f1fe80d4
KS
1339
1340 /*
1341 * Queue the page for deferred split if at least one small
1342 * page of the compound page is unmapped, but at least one
1343 * small page is still mapped.
1344 */
5eaf35ab 1345 if (nr && nr < thp_nr_pages(page))
f1fe80d4 1346 deferred_split_huge_page(page);
53f9263b 1347 } else {
5eaf35ab 1348 nr = thp_nr_pages(page);
53f9263b
KS
1349 }
1350
f1fe80d4 1351 if (nr)
be5d0a74 1352 __mod_lruvec_page_state(page, NR_ANON_MAPPED, -nr);
53f9263b
KS
1353}
1354
1da177e4
LT
1355/**
1356 * page_remove_rmap - take down pte mapping from a page
d281ee61 1357 * @page: page to remove mapping from
cea86fe2 1358 * @vma: the vm area from which the mapping is removed
d281ee61 1359 * @compound: uncharge the page as compound or small page
1da177e4 1360 *
b8072f09 1361 * The caller needs to hold the pte lock.
1da177e4 1362 */
cea86fe2
HD
1363void page_remove_rmap(struct page *page,
1364 struct vm_area_struct *vma, bool compound)
1da177e4 1365{
be5d0a74 1366 lock_page_memcg(page);
89c06bd5 1367
be5d0a74
JW
1368 if (!PageAnon(page)) {
1369 page_remove_file_rmap(page, compound);
1370 goto out;
1371 }
1372
1373 if (compound) {
1374 page_remove_anon_compound_rmap(page);
1375 goto out;
1376 }
53f9263b 1377
b904dcfe
KM
1378 /* page still mapped by someone else? */
1379 if (!atomic_add_negative(-1, &page->_mapcount))
be5d0a74 1380 goto out;
8186eb6a 1381
0fe6e20b 1382 /*
bea04b07
JZ
1383 * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1384 * these counters are not modified in interrupt context, and
bea04b07 1385 * pte lock(a spinlock) is held, which implies preemption disabled.
0fe6e20b 1386 */
be5d0a74 1387 __dec_lruvec_page_state(page, NR_ANON_MAPPED);
8186eb6a 1388
9a982250
KS
1389 if (PageTransCompound(page))
1390 deferred_split_huge_page(compound_head(page));
1391
b904dcfe
KM
1392 /*
1393 * It would be tidy to reset the PageAnon mapping here,
1394 * but that might overwrite a racing page_add_anon_rmap
1395 * which increments mapcount after us but sets mapping
2d4894b5 1396 * before us: so leave the reset to free_unref_page,
b904dcfe
KM
1397 * and remember that it's only reliable while mapped.
1398 * Leaving it set also helps swapoff to reinstate ptes
1399 * faster for those pages still in swapcache.
1400 */
be5d0a74
JW
1401out:
1402 unlock_page_memcg(page);
cea86fe2
HD
1403
1404 munlock_vma_page(page, vma, compound);
1da177e4
LT
1405}
1406
1407/*
52629506 1408 * @arg: enum ttu_flags will be passed to this argument
1da177e4 1409 */
e4b82222 1410static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,
52629506 1411 unsigned long address, void *arg)
1da177e4
LT
1412{
1413 struct mm_struct *mm = vma->vm_mm;
eed05e54 1414 DEFINE_PAGE_VMA_WALK(pvmw, page, vma, address, 0);
1da177e4 1415 pte_t pteval;
c7ab0d2f 1416 struct page *subpage;
785373b4 1417 bool ret = true;
ac46d4f3 1418 struct mmu_notifier_range range;
4708f318 1419 enum ttu_flags flags = (enum ttu_flags)(long)arg;
1da177e4 1420
732ed558
HD
1421 /*
1422 * When racing against e.g. zap_pte_range() on another cpu,
1423 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
1fb08ac6 1424 * try_to_unmap() may return before page_mapped() has become false,
732ed558
HD
1425 * if page table locking is skipped: use TTU_SYNC to wait for that.
1426 */
1427 if (flags & TTU_SYNC)
1428 pvmw.flags = PVMW_SYNC;
1429
a98a2f0c
AP
1430 if (flags & TTU_SPLIT_HUGE_PMD)
1431 split_huge_pmd_address(vma, address, false, page);
fec89c10 1432
369ea824 1433 /*
017b1660
MK
1434 * For THP, we have to assume the worse case ie pmd for invalidation.
1435 * For hugetlb, it could be much worse if we need to do pud
1436 * invalidation in the case of pmd sharing.
1437 *
1438 * Note that the page can not be free in this function as call of
1439 * try_to_unmap() must hold a reference on the page.
369ea824 1440 */
2aff7a47 1441 range.end = vma_address_end(&pvmw);
7269f999 1442 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
494334e4 1443 address, range.end);
017b1660
MK
1444 if (PageHuge(page)) {
1445 /*
1446 * If sharing is possible, start and end will be adjusted
1447 * accordingly.
1448 */
ac46d4f3
JG
1449 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1450 &range.end);
017b1660 1451 }
ac46d4f3 1452 mmu_notifier_invalidate_range_start(&range);
369ea824 1453
c7ab0d2f 1454 while (page_vma_mapped_walk(&pvmw)) {
cea86fe2
HD
1455 /* Unexpected PMD-mapped THP? */
1456 VM_BUG_ON_PAGE(!pvmw.pte, page);
1457
c7ab0d2f 1458 /*
cea86fe2 1459 * If the page is in an mlock()d vma, we must not swap it out.
c7ab0d2f 1460 */
efdb6720
HD
1461 if (!(flags & TTU_IGNORE_MLOCK) &&
1462 (vma->vm_flags & VM_LOCKED)) {
cea86fe2
HD
1463 /* Restore the mlock which got missed */
1464 mlock_vma_page(page, vma, false);
efdb6720
HD
1465 page_vma_mapped_walk_done(&pvmw);
1466 ret = false;
1467 break;
b87537d9 1468 }
c7ab0d2f 1469
8346242a 1470 subpage = page - page_to_pfn(page) + pte_pfn(*pvmw.pte);
785373b4
LT
1471 address = pvmw.address;
1472
336bf30e 1473 if (PageHuge(page) && !PageAnon(page)) {
c0d0381a
MK
1474 /*
1475 * To call huge_pmd_unshare, i_mmap_rwsem must be
1476 * held in write mode. Caller needs to explicitly
1477 * do this outside rmap routines.
1478 */
1479 VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
34ae204f 1480 if (huge_pmd_unshare(mm, vma, &address, pvmw.pte)) {
017b1660
MK
1481 /*
1482 * huge_pmd_unshare unmapped an entire PMD
1483 * page. There is no way of knowing exactly
1484 * which PMDs may be cached for this mm, so
1485 * we must flush them all. start/end were
1486 * already adjusted above to cover this range.
1487 */
ac46d4f3
JG
1488 flush_cache_range(vma, range.start, range.end);
1489 flush_tlb_range(vma, range.start, range.end);
1490 mmu_notifier_invalidate_range(mm, range.start,
1491 range.end);
017b1660
MK
1492
1493 /*
1494 * The ref count of the PMD page was dropped
1495 * which is part of the way map counting
1496 * is done for shared PMDs. Return 'true'
1497 * here. When there is no other sharing,
1498 * huge_pmd_unshare returns false and we will
1499 * unmap the actual page and drop map count
1500 * to zero.
1501 */
1502 page_vma_mapped_walk_done(&pvmw);
1503 break;
1504 }
1505 }
8346242a 1506
c7ab0d2f 1507 /* Nuke the page table entry. */
785373b4 1508 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
c7ab0d2f
KS
1509 if (should_defer_flush(mm, flags)) {
1510 /*
1511 * We clear the PTE but do not flush so potentially
1512 * a remote CPU could still be writing to the page.
1513 * If the entry was previously clean then the
1514 * architecture must guarantee that a clear->dirty
1515 * transition on a cached TLB entry is written through
1516 * and traps if the PTE is unmapped.
1517 */
785373b4 1518 pteval = ptep_get_and_clear(mm, address, pvmw.pte);
c7ab0d2f
KS
1519
1520 set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
1521 } else {
785373b4 1522 pteval = ptep_clear_flush(vma, address, pvmw.pte);
c7ab0d2f 1523 }
72b252ae 1524
c7ab0d2f
KS
1525 /* Move the dirty bit to the page. Now the pte is gone. */
1526 if (pte_dirty(pteval))
1527 set_page_dirty(page);
1da177e4 1528
c7ab0d2f
KS
1529 /* Update high watermark before we lower rss */
1530 update_hiwater_rss(mm);
1da177e4 1531
c7ab0d2f 1532 if (PageHWPoison(page) && !(flags & TTU_IGNORE_HWPOISON)) {
5fd27b8e 1533 pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
c7ab0d2f 1534 if (PageHuge(page)) {
d8c6546b 1535 hugetlb_count_sub(compound_nr(page), mm);
785373b4 1536 set_huge_swap_pte_at(mm, address,
5fd27b8e
PA
1537 pvmw.pte, pteval,
1538 vma_mmu_pagesize(vma));
c7ab0d2f
KS
1539 } else {
1540 dec_mm_counter(mm, mm_counter(page));
785373b4 1541 set_pte_at(mm, address, pvmw.pte, pteval);
c7ab0d2f 1542 }
365e9c87 1543
bce73e48 1544 } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
c7ab0d2f
KS
1545 /*
1546 * The guest indicated that the page content is of no
1547 * interest anymore. Simply discard the pte, vmscan
1548 * will take care of the rest.
bce73e48
CB
1549 * A future reference will then fault in a new zero
1550 * page. When userfaultfd is active, we must not drop
1551 * this page though, as its main user (postcopy
1552 * migration) will not expect userfaults on already
1553 * copied pages.
c7ab0d2f 1554 */
eca56ff9 1555 dec_mm_counter(mm, mm_counter(page));
0f10851e
JG
1556 /* We have to invalidate as we cleared the pte */
1557 mmu_notifier_invalidate_range(mm, address,
1558 address + PAGE_SIZE);
c7ab0d2f
KS
1559 } else if (PageAnon(page)) {
1560 swp_entry_t entry = { .val = page_private(subpage) };
1561 pte_t swp_pte;
1562 /*
1563 * Store the swap location in the pte.
1564 * See handle_pte_fault() ...
1565 */
eb94a878
MK
1566 if (unlikely(PageSwapBacked(page) != PageSwapCache(page))) {
1567 WARN_ON_ONCE(1);
83612a94 1568 ret = false;
369ea824 1569 /* We have to invalidate as we cleared the pte */
0f10851e
JG
1570 mmu_notifier_invalidate_range(mm, address,
1571 address + PAGE_SIZE);
eb94a878
MK
1572 page_vma_mapped_walk_done(&pvmw);
1573 break;
1574 }
c7ab0d2f 1575
802a3a92
SL
1576 /* MADV_FREE page check */
1577 if (!PageSwapBacked(page)) {
1578 if (!PageDirty(page)) {
0f10851e
JG
1579 /* Invalidate as we cleared the pte */
1580 mmu_notifier_invalidate_range(mm,
1581 address, address + PAGE_SIZE);
802a3a92
SL
1582 dec_mm_counter(mm, MM_ANONPAGES);
1583 goto discard;
1584 }
1585
1586 /*
1587 * If the page was redirtied, it cannot be
1588 * discarded. Remap the page to page table.
1589 */
785373b4 1590 set_pte_at(mm, address, pvmw.pte, pteval);
18863d3a 1591 SetPageSwapBacked(page);
e4b82222 1592 ret = false;
802a3a92
SL
1593 page_vma_mapped_walk_done(&pvmw);
1594 break;
c7ab0d2f 1595 }
854e9ed0 1596
c7ab0d2f 1597 if (swap_duplicate(entry) < 0) {
785373b4 1598 set_pte_at(mm, address, pvmw.pte, pteval);
e4b82222 1599 ret = false;
c7ab0d2f
KS
1600 page_vma_mapped_walk_done(&pvmw);
1601 break;
1602 }
ca827d55
KA
1603 if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1604 set_pte_at(mm, address, pvmw.pte, pteval);
1605 ret = false;
1606 page_vma_mapped_walk_done(&pvmw);
1607 break;
1608 }
c7ab0d2f
KS
1609 if (list_empty(&mm->mmlist)) {
1610 spin_lock(&mmlist_lock);
1611 if (list_empty(&mm->mmlist))
1612 list_add(&mm->mmlist, &init_mm.mmlist);
1613 spin_unlock(&mmlist_lock);
1614 }
854e9ed0 1615 dec_mm_counter(mm, MM_ANONPAGES);
c7ab0d2f
KS
1616 inc_mm_counter(mm, MM_SWAPENTS);
1617 swp_pte = swp_entry_to_pte(entry);
1618 if (pte_soft_dirty(pteval))
1619 swp_pte = pte_swp_mksoft_dirty(swp_pte);
f45ec5ff
PX
1620 if (pte_uffd_wp(pteval))
1621 swp_pte = pte_swp_mkuffd_wp(swp_pte);
785373b4 1622 set_pte_at(mm, address, pvmw.pte, swp_pte);
0f10851e
JG
1623 /* Invalidate as we cleared the pte */
1624 mmu_notifier_invalidate_range(mm, address,
1625 address + PAGE_SIZE);
1626 } else {
1627 /*
906f9cdf
HD
1628 * This is a locked file-backed page, thus it cannot
1629 * be removed from the page cache and replaced by a new
1630 * page before mmu_notifier_invalidate_range_end, so no
0f10851e
JG
1631 * concurrent thread might update its page table to
1632 * point at new page while a device still is using this
1633 * page.
1634 *
ad56b738 1635 * See Documentation/vm/mmu_notifier.rst
0f10851e 1636 */
c7ab0d2f 1637 dec_mm_counter(mm, mm_counter_file(page));
0f10851e 1638 }
854e9ed0 1639discard:
0f10851e
JG
1640 /*
1641 * No need to call mmu_notifier_invalidate_range() it has be
1642 * done above for all cases requiring it to happen under page
1643 * table lock before mmu_notifier_invalidate_range_end()
1644 *
ad56b738 1645 * See Documentation/vm/mmu_notifier.rst
0f10851e 1646 */
cea86fe2 1647 page_remove_rmap(subpage, vma, PageHuge(page));
b7435507
HD
1648 if (vma->vm_flags & VM_LOCKED)
1649 mlock_page_drain(smp_processor_id());
c7ab0d2f 1650 put_page(page);
c7ab0d2f 1651 }
369ea824 1652
ac46d4f3 1653 mmu_notifier_invalidate_range_end(&range);
369ea824 1654
caed0f48 1655 return ret;
1da177e4
LT
1656}
1657
52629506
JK
1658static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
1659{
222100ee 1660 return vma_is_temporary_stack(vma);
52629506
JK
1661}
1662
b7e188ec 1663static int page_not_mapped(struct page *page)
52629506 1664{
b7e188ec 1665 return !page_mapped(page);
2a52bcbc 1666}
52629506 1667
1da177e4
LT
1668/**
1669 * try_to_unmap - try to remove all page table mappings to a page
1670 * @page: the page to get unmapped
14fa31b8 1671 * @flags: action and flags
1da177e4
LT
1672 *
1673 * Tries to remove all the page table entries which are mapping this
1674 * page, used in the pageout path. Caller must hold the page lock.
1da177e4 1675 *
1fb08ac6
YS
1676 * It is the caller's responsibility to check if the page is still
1677 * mapped when needed (use TTU_SYNC to prevent accounting races).
1da177e4 1678 */
1fb08ac6 1679void try_to_unmap(struct page *page, enum ttu_flags flags)
1da177e4 1680{
52629506
JK
1681 struct rmap_walk_control rwc = {
1682 .rmap_one = try_to_unmap_one,
802a3a92 1683 .arg = (void *)flags,
b7e188ec 1684 .done = page_not_mapped,
52629506
JK
1685 .anon_lock = page_lock_anon_vma_read,
1686 };
1da177e4 1687
a98a2f0c
AP
1688 if (flags & TTU_RMAP_LOCKED)
1689 rmap_walk_locked(page, &rwc);
1690 else
1691 rmap_walk(page, &rwc);
1692}
1693
1694/*
1695 * @arg: enum ttu_flags will be passed to this argument.
1696 *
1697 * If TTU_SPLIT_HUGE_PMD is specified any PMD mappings will be split into PTEs
64b586d1 1698 * containing migration entries.
a98a2f0c
AP
1699 */
1700static bool try_to_migrate_one(struct page *page, struct vm_area_struct *vma,
1701 unsigned long address, void *arg)
1702{
1703 struct mm_struct *mm = vma->vm_mm;
eed05e54 1704 DEFINE_PAGE_VMA_WALK(pvmw, page, vma, address, 0);
a98a2f0c
AP
1705 pte_t pteval;
1706 struct page *subpage;
1707 bool ret = true;
1708 struct mmu_notifier_range range;
1709 enum ttu_flags flags = (enum ttu_flags)(long)arg;
1710
a98a2f0c
AP
1711 /*
1712 * When racing against e.g. zap_pte_range() on another cpu,
1713 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
1714 * try_to_migrate() may return before page_mapped() has become false,
1715 * if page table locking is skipped: use TTU_SYNC to wait for that.
1716 */
1717 if (flags & TTU_SYNC)
1718 pvmw.flags = PVMW_SYNC;
1719
1720 /*
1721 * unmap_page() in mm/huge_memory.c is the only user of migration with
1722 * TTU_SPLIT_HUGE_PMD and it wants to freeze.
1723 */
1724 if (flags & TTU_SPLIT_HUGE_PMD)
1725 split_huge_pmd_address(vma, address, true, page);
1726
1727 /*
1728 * For THP, we have to assume the worse case ie pmd for invalidation.
1729 * For hugetlb, it could be much worse if we need to do pud
1730 * invalidation in the case of pmd sharing.
1731 *
1732 * Note that the page can not be free in this function as call of
1733 * try_to_unmap() must hold a reference on the page.
1734 */
2aff7a47 1735 range.end = vma_address_end(&pvmw);
a98a2f0c
AP
1736 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1737 address, range.end);
1738 if (PageHuge(page)) {
1739 /*
1740 * If sharing is possible, start and end will be adjusted
1741 * accordingly.
1742 */
1743 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1744 &range.end);
1745 }
1746 mmu_notifier_invalidate_range_start(&range);
1747
1748 while (page_vma_mapped_walk(&pvmw)) {
1749#ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1750 /* PMD-mapped THP migration entry */
1751 if (!pvmw.pte) {
1752 VM_BUG_ON_PAGE(PageHuge(page) ||
1753 !PageTransCompound(page), page);
1754
1755 set_pmd_migration_entry(&pvmw, page);
1756 continue;
1757 }
1758#endif
1759
1760 /* Unexpected PMD-mapped THP? */
1761 VM_BUG_ON_PAGE(!pvmw.pte, page);
1762
1763 subpage = page - page_to_pfn(page) + pte_pfn(*pvmw.pte);
1764 address = pvmw.address;
1765
1766 if (PageHuge(page) && !PageAnon(page)) {
1767 /*
1768 * To call huge_pmd_unshare, i_mmap_rwsem must be
1769 * held in write mode. Caller needs to explicitly
1770 * do this outside rmap routines.
1771 */
1772 VM_BUG_ON(!(flags & TTU_RMAP_LOCKED));
1773 if (huge_pmd_unshare(mm, vma, &address, pvmw.pte)) {
1774 /*
1775 * huge_pmd_unshare unmapped an entire PMD
1776 * page. There is no way of knowing exactly
1777 * which PMDs may be cached for this mm, so
1778 * we must flush them all. start/end were
1779 * already adjusted above to cover this range.
1780 */
1781 flush_cache_range(vma, range.start, range.end);
1782 flush_tlb_range(vma, range.start, range.end);
1783 mmu_notifier_invalidate_range(mm, range.start,
1784 range.end);
1785
1786 /*
1787 * The ref count of the PMD page was dropped
1788 * which is part of the way map counting
1789 * is done for shared PMDs. Return 'true'
1790 * here. When there is no other sharing,
1791 * huge_pmd_unshare returns false and we will
1792 * unmap the actual page and drop map count
1793 * to zero.
1794 */
1795 page_vma_mapped_walk_done(&pvmw);
1796 break;
1797 }
1798 }
1799
1800 /* Nuke the page table entry. */
1801 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
1802 pteval = ptep_clear_flush(vma, address, pvmw.pte);
1803
1804 /* Move the dirty bit to the page. Now the pte is gone. */
1805 if (pte_dirty(pteval))
1806 set_page_dirty(page);
1807
1808 /* Update high watermark before we lower rss */
1809 update_hiwater_rss(mm);
1810
1811 if (is_zone_device_page(page)) {
3d88705c 1812 unsigned long pfn = page_to_pfn(page);
a98a2f0c
AP
1813 swp_entry_t entry;
1814 pte_t swp_pte;
1815
1816 /*
1817 * Store the pfn of the page in a special migration
1818 * pte. do_swap_page() will wait until the migration
1819 * pte is removed and then restart fault handling.
1820 */
3d88705c
AP
1821 entry = pte_to_swp_entry(pteval);
1822 if (is_writable_device_private_entry(entry))
1823 entry = make_writable_migration_entry(pfn);
1824 else
1825 entry = make_readable_migration_entry(pfn);
a98a2f0c
AP
1826 swp_pte = swp_entry_to_pte(entry);
1827
1828 /*
1829 * pteval maps a zone device page and is therefore
1830 * a swap pte.
1831 */
1832 if (pte_swp_soft_dirty(pteval))
1833 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1834 if (pte_swp_uffd_wp(pteval))
1835 swp_pte = pte_swp_mkuffd_wp(swp_pte);
1836 set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
1837 /*
1838 * No need to invalidate here it will synchronize on
1839 * against the special swap migration pte.
1840 *
1841 * The assignment to subpage above was computed from a
1842 * swap PTE which results in an invalid pointer.
1843 * Since only PAGE_SIZE pages can currently be
1844 * migrated, just set it to page. This will need to be
1845 * changed when hugepage migrations to device private
1846 * memory are supported.
1847 */
1848 subpage = page;
1849 } else if (PageHWPoison(page)) {
1850 pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
1851 if (PageHuge(page)) {
1852 hugetlb_count_sub(compound_nr(page), mm);
1853 set_huge_swap_pte_at(mm, address,
1854 pvmw.pte, pteval,
1855 vma_mmu_pagesize(vma));
1856 } else {
1857 dec_mm_counter(mm, mm_counter(page));
1858 set_pte_at(mm, address, pvmw.pte, pteval);
1859 }
1860
1861 } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
1862 /*
1863 * The guest indicated that the page content is of no
1864 * interest anymore. Simply discard the pte, vmscan
1865 * will take care of the rest.
1866 * A future reference will then fault in a new zero
1867 * page. When userfaultfd is active, we must not drop
1868 * this page though, as its main user (postcopy
1869 * migration) will not expect userfaults on already
1870 * copied pages.
1871 */
1872 dec_mm_counter(mm, mm_counter(page));
1873 /* We have to invalidate as we cleared the pte */
1874 mmu_notifier_invalidate_range(mm, address,
1875 address + PAGE_SIZE);
1876 } else {
1877 swp_entry_t entry;
1878 pte_t swp_pte;
1879
1880 if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1881 set_pte_at(mm, address, pvmw.pte, pteval);
1882 ret = false;
1883 page_vma_mapped_walk_done(&pvmw);
1884 break;
1885 }
1886
1887 /*
1888 * Store the pfn of the page in a special migration
1889 * pte. do_swap_page() will wait until the migration
1890 * pte is removed and then restart fault handling.
1891 */
1892 if (pte_write(pteval))
1893 entry = make_writable_migration_entry(
1894 page_to_pfn(subpage));
1895 else
1896 entry = make_readable_migration_entry(
1897 page_to_pfn(subpage));
1898
1899 swp_pte = swp_entry_to_pte(entry);
1900 if (pte_soft_dirty(pteval))
1901 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1902 if (pte_uffd_wp(pteval))
1903 swp_pte = pte_swp_mkuffd_wp(swp_pte);
1904 set_pte_at(mm, address, pvmw.pte, swp_pte);
1905 /*
1906 * No need to invalidate here it will synchronize on
1907 * against the special swap migration pte.
1908 */
1909 }
1910
1911 /*
1912 * No need to call mmu_notifier_invalidate_range() it has be
1913 * done above for all cases requiring it to happen under page
1914 * table lock before mmu_notifier_invalidate_range_end()
1915 *
1916 * See Documentation/vm/mmu_notifier.rst
1917 */
cea86fe2 1918 page_remove_rmap(subpage, vma, PageHuge(page));
b7435507
HD
1919 if (vma->vm_flags & VM_LOCKED)
1920 mlock_page_drain(smp_processor_id());
a98a2f0c
AP
1921 put_page(page);
1922 }
1923
1924 mmu_notifier_invalidate_range_end(&range);
1925
1926 return ret;
1927}
1928
1929/**
1930 * try_to_migrate - try to replace all page table mappings with swap entries
1931 * @page: the page to replace page table entries for
1932 * @flags: action and flags
1933 *
1934 * Tries to remove all the page table entries which are mapping this page and
1935 * replace them with special swap entries. Caller must hold the page lock.
a98a2f0c
AP
1936 */
1937void try_to_migrate(struct page *page, enum ttu_flags flags)
1938{
1939 struct rmap_walk_control rwc = {
1940 .rmap_one = try_to_migrate_one,
1941 .arg = (void *)flags,
1942 .done = page_not_mapped,
1943 .anon_lock = page_lock_anon_vma_read,
1944 };
1945
1946 /*
1947 * Migration always ignores mlock and only supports TTU_RMAP_LOCKED and
1948 * TTU_SPLIT_HUGE_PMD and TTU_SYNC flags.
1949 */
1950 if (WARN_ON_ONCE(flags & ~(TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
1951 TTU_SYNC)))
1952 return;
1953
6c855fce
HD
1954 if (is_zone_device_page(page) && !is_device_private_page(page))
1955 return;
1956
52629506
JK
1957 /*
1958 * During exec, a temporary VMA is setup and later moved.
1959 * The VMA is moved under the anon_vma lock but not the
1960 * page tables leading to a race where migration cannot
1961 * find the migration ptes. Rather than increasing the
1962 * locking requirements of exec(), migration skips
1963 * temporary VMAs until after exec() completes.
1964 */
a98a2f0c 1965 if (!PageKsm(page) && PageAnon(page))
52629506
JK
1966 rwc.invalid_vma = invalid_migration_vma;
1967
2a52bcbc 1968 if (flags & TTU_RMAP_LOCKED)
33fc80e2 1969 rmap_walk_locked(page, &rwc);
2a52bcbc 1970 else
33fc80e2 1971 rmap_walk(page, &rwc);
1da177e4 1972}
81b4082d 1973
b756a3b5
AP
1974#ifdef CONFIG_DEVICE_PRIVATE
1975struct make_exclusive_args {
1976 struct mm_struct *mm;
1977 unsigned long address;
1978 void *owner;
1979 bool valid;
1980};
1981
1982static bool page_make_device_exclusive_one(struct page *page,
1983 struct vm_area_struct *vma, unsigned long address, void *priv)
1984{
1985 struct mm_struct *mm = vma->vm_mm;
eed05e54 1986 DEFINE_PAGE_VMA_WALK(pvmw, page, vma, address, 0);
b756a3b5
AP
1987 struct make_exclusive_args *args = priv;
1988 pte_t pteval;
1989 struct page *subpage;
1990 bool ret = true;
1991 struct mmu_notifier_range range;
1992 swp_entry_t entry;
1993 pte_t swp_pte;
1994
1995 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma,
1996 vma->vm_mm, address, min(vma->vm_end,
1997 address + page_size(page)), args->owner);
1998 mmu_notifier_invalidate_range_start(&range);
1999
2000 while (page_vma_mapped_walk(&pvmw)) {
2001 /* Unexpected PMD-mapped THP? */
2002 VM_BUG_ON_PAGE(!pvmw.pte, page);
2003
2004 if (!pte_present(*pvmw.pte)) {
2005 ret = false;
2006 page_vma_mapped_walk_done(&pvmw);
2007 break;
2008 }
2009
2010 subpage = page - page_to_pfn(page) + pte_pfn(*pvmw.pte);
2011 address = pvmw.address;
2012
2013 /* Nuke the page table entry. */
2014 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
2015 pteval = ptep_clear_flush(vma, address, pvmw.pte);
2016
2017 /* Move the dirty bit to the page. Now the pte is gone. */
2018 if (pte_dirty(pteval))
2019 set_page_dirty(page);
2020
2021 /*
2022 * Check that our target page is still mapped at the expected
2023 * address.
2024 */
2025 if (args->mm == mm && args->address == address &&
2026 pte_write(pteval))
2027 args->valid = true;
2028
2029 /*
2030 * Store the pfn of the page in a special migration
2031 * pte. do_swap_page() will wait until the migration
2032 * pte is removed and then restart fault handling.
2033 */
2034 if (pte_write(pteval))
2035 entry = make_writable_device_exclusive_entry(
2036 page_to_pfn(subpage));
2037 else
2038 entry = make_readable_device_exclusive_entry(
2039 page_to_pfn(subpage));
2040 swp_pte = swp_entry_to_pte(entry);
2041 if (pte_soft_dirty(pteval))
2042 swp_pte = pte_swp_mksoft_dirty(swp_pte);
2043 if (pte_uffd_wp(pteval))
2044 swp_pte = pte_swp_mkuffd_wp(swp_pte);
2045
2046 set_pte_at(mm, address, pvmw.pte, swp_pte);
2047
2048 /*
2049 * There is a reference on the page for the swap entry which has
2050 * been removed, so shouldn't take another.
2051 */
cea86fe2 2052 page_remove_rmap(subpage, vma, false);
b756a3b5
AP
2053 }
2054
2055 mmu_notifier_invalidate_range_end(&range);
2056
2057 return ret;
2058}
2059
2060/**
2061 * page_make_device_exclusive - mark the page exclusively owned by a device
2062 * @page: the page to replace page table entries for
2063 * @mm: the mm_struct where the page is expected to be mapped
2064 * @address: address where the page is expected to be mapped
2065 * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier callbacks
2066 *
2067 * Tries to remove all the page table entries which are mapping this page and
2068 * replace them with special device exclusive swap entries to grant a device
2069 * exclusive access to the page. Caller must hold the page lock.
2070 *
2071 * Returns false if the page is still mapped, or if it could not be unmapped
2072 * from the expected address. Otherwise returns true (success).
2073 */
2074static bool page_make_device_exclusive(struct page *page, struct mm_struct *mm,
2075 unsigned long address, void *owner)
2076{
2077 struct make_exclusive_args args = {
2078 .mm = mm,
2079 .address = address,
2080 .owner = owner,
2081 .valid = false,
2082 };
2083 struct rmap_walk_control rwc = {
2084 .rmap_one = page_make_device_exclusive_one,
2085 .done = page_not_mapped,
2086 .anon_lock = page_lock_anon_vma_read,
2087 .arg = &args,
2088 };
2089
2090 /*
2091 * Restrict to anonymous pages for now to avoid potential writeback
2092 * issues. Also tail pages shouldn't be passed to rmap_walk so skip
2093 * those.
2094 */
2095 if (!PageAnon(page) || PageTail(page))
2096 return false;
2097
2098 rmap_walk(page, &rwc);
2099
2100 return args.valid && !page_mapcount(page);
2101}
2102
2103/**
2104 * make_device_exclusive_range() - Mark a range for exclusive use by a device
2105 * @mm: mm_struct of assoicated target process
2106 * @start: start of the region to mark for exclusive device access
2107 * @end: end address of region
2108 * @pages: returns the pages which were successfully marked for exclusive access
2109 * @owner: passed to MMU_NOTIFY_EXCLUSIVE range notifier to allow filtering
2110 *
2111 * Returns: number of pages found in the range by GUP. A page is marked for
2112 * exclusive access only if the page pointer is non-NULL.
2113 *
2114 * This function finds ptes mapping page(s) to the given address range, locks
2115 * them and replaces mappings with special swap entries preventing userspace CPU
2116 * access. On fault these entries are replaced with the original mapping after
2117 * calling MMU notifiers.
2118 *
2119 * A driver using this to program access from a device must use a mmu notifier
2120 * critical section to hold a device specific lock during programming. Once
2121 * programming is complete it should drop the page lock and reference after
2122 * which point CPU access to the page will revoke the exclusive access.
2123 */
2124int make_device_exclusive_range(struct mm_struct *mm, unsigned long start,
2125 unsigned long end, struct page **pages,
2126 void *owner)
2127{
2128 long npages = (end - start) >> PAGE_SHIFT;
2129 long i;
2130
2131 npages = get_user_pages_remote(mm, start, npages,
2132 FOLL_GET | FOLL_WRITE | FOLL_SPLIT_PMD,
2133 pages, NULL, NULL);
2134 if (npages < 0)
2135 return npages;
2136
2137 for (i = 0; i < npages; i++, start += PAGE_SIZE) {
2138 if (!trylock_page(pages[i])) {
2139 put_page(pages[i]);
2140 pages[i] = NULL;
2141 continue;
2142 }
2143
2144 if (!page_make_device_exclusive(pages[i], mm, start, owner)) {
2145 unlock_page(pages[i]);
2146 put_page(pages[i]);
2147 pages[i] = NULL;
2148 }
2149 }
2150
2151 return npages;
2152}
2153EXPORT_SYMBOL_GPL(make_device_exclusive_range);
2154#endif
2155
01d8b20d 2156void __put_anon_vma(struct anon_vma *anon_vma)
76545066 2157{
01d8b20d 2158 struct anon_vma *root = anon_vma->root;
76545066 2159
624483f3 2160 anon_vma_free(anon_vma);
01d8b20d
PZ
2161 if (root != anon_vma && atomic_dec_and_test(&root->refcount))
2162 anon_vma_free(root);
76545066 2163}
76545066 2164
0dd1c7bb
JK
2165static struct anon_vma *rmap_walk_anon_lock(struct page *page,
2166 struct rmap_walk_control *rwc)
faecd8dd
JK
2167{
2168 struct anon_vma *anon_vma;
2169
0dd1c7bb
JK
2170 if (rwc->anon_lock)
2171 return rwc->anon_lock(page);
2172
faecd8dd
JK
2173 /*
2174 * Note: remove_migration_ptes() cannot use page_lock_anon_vma_read()
2175 * because that depends on page_mapped(); but not all its usages
c1e8d7c6 2176 * are holding mmap_lock. Users without mmap_lock are required to
faecd8dd
JK
2177 * take a reference count to prevent the anon_vma disappearing
2178 */
2179 anon_vma = page_anon_vma(page);
2180 if (!anon_vma)
2181 return NULL;
2182
2183 anon_vma_lock_read(anon_vma);
2184 return anon_vma;
2185}
2186
e9995ef9 2187/*
e8351ac9
JK
2188 * rmap_walk_anon - do something to anonymous page using the object-based
2189 * rmap method
2190 * @page: the page to be handled
2191 * @rwc: control variable according to each walk type
2192 *
2193 * Find all the mappings of a page using the mapping pointer and the vma chains
2194 * contained in the anon_vma struct it points to.
e9995ef9 2195 */
1df631ae 2196static void rmap_walk_anon(struct page *page, struct rmap_walk_control *rwc,
b9773199 2197 bool locked)
e9995ef9
HD
2198{
2199 struct anon_vma *anon_vma;
a8fa41ad 2200 pgoff_t pgoff_start, pgoff_end;
5beb4930 2201 struct anon_vma_chain *avc;
e9995ef9 2202
b9773199
KS
2203 if (locked) {
2204 anon_vma = page_anon_vma(page);
2205 /* anon_vma disappear under us? */
2206 VM_BUG_ON_PAGE(!anon_vma, page);
2207 } else {
2208 anon_vma = rmap_walk_anon_lock(page, rwc);
2209 }
e9995ef9 2210 if (!anon_vma)
1df631ae 2211 return;
faecd8dd 2212
a8fa41ad 2213 pgoff_start = page_to_pgoff(page);
6c357848 2214 pgoff_end = pgoff_start + thp_nr_pages(page) - 1;
a8fa41ad
KS
2215 anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
2216 pgoff_start, pgoff_end) {
5beb4930 2217 struct vm_area_struct *vma = avc->vma;
e9995ef9 2218 unsigned long address = vma_address(page, vma);
0dd1c7bb 2219
494334e4 2220 VM_BUG_ON_VMA(address == -EFAULT, vma);
ad12695f
AA
2221 cond_resched();
2222
0dd1c7bb
JK
2223 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2224 continue;
2225
e4b82222 2226 if (!rwc->rmap_one(page, vma, address, rwc->arg))
e9995ef9 2227 break;
0dd1c7bb
JK
2228 if (rwc->done && rwc->done(page))
2229 break;
e9995ef9 2230 }
b9773199
KS
2231
2232 if (!locked)
2233 anon_vma_unlock_read(anon_vma);
e9995ef9
HD
2234}
2235
e8351ac9
JK
2236/*
2237 * rmap_walk_file - do something to file page using the object-based rmap method
2238 * @page: the page to be handled
2239 * @rwc: control variable according to each walk type
2240 *
2241 * Find all the mappings of a page using the mapping pointer and the vma chains
2242 * contained in the address_space struct it points to.
e8351ac9 2243 */
1df631ae 2244static void rmap_walk_file(struct page *page, struct rmap_walk_control *rwc,
b9773199 2245 bool locked)
e9995ef9 2246{
b9773199 2247 struct address_space *mapping = page_mapping(page);
a8fa41ad 2248 pgoff_t pgoff_start, pgoff_end;
e9995ef9 2249 struct vm_area_struct *vma;
e9995ef9 2250
9f32624b
JK
2251 /*
2252 * The page lock not only makes sure that page->mapping cannot
2253 * suddenly be NULLified by truncation, it makes sure that the
2254 * structure at mapping cannot be freed and reused yet,
c8c06efa 2255 * so we can safely take mapping->i_mmap_rwsem.
9f32624b 2256 */
81d1b09c 2257 VM_BUG_ON_PAGE(!PageLocked(page), page);
9f32624b 2258
e9995ef9 2259 if (!mapping)
1df631ae 2260 return;
3dec0ba0 2261
a8fa41ad 2262 pgoff_start = page_to_pgoff(page);
6c357848 2263 pgoff_end = pgoff_start + thp_nr_pages(page) - 1;
b9773199
KS
2264 if (!locked)
2265 i_mmap_lock_read(mapping);
a8fa41ad
KS
2266 vma_interval_tree_foreach(vma, &mapping->i_mmap,
2267 pgoff_start, pgoff_end) {
e9995ef9 2268 unsigned long address = vma_address(page, vma);
0dd1c7bb 2269
494334e4 2270 VM_BUG_ON_VMA(address == -EFAULT, vma);
ad12695f
AA
2271 cond_resched();
2272
0dd1c7bb
JK
2273 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
2274 continue;
2275
e4b82222 2276 if (!rwc->rmap_one(page, vma, address, rwc->arg))
0dd1c7bb
JK
2277 goto done;
2278 if (rwc->done && rwc->done(page))
2279 goto done;
e9995ef9 2280 }
0dd1c7bb 2281
0dd1c7bb 2282done:
b9773199
KS
2283 if (!locked)
2284 i_mmap_unlock_read(mapping);
e9995ef9
HD
2285}
2286
1df631ae 2287void rmap_walk(struct page *page, struct rmap_walk_control *rwc)
e9995ef9 2288{
e9995ef9 2289 if (unlikely(PageKsm(page)))
1df631ae 2290 rmap_walk_ksm(page, rwc);
e9995ef9 2291 else if (PageAnon(page))
1df631ae 2292 rmap_walk_anon(page, rwc, false);
b9773199 2293 else
1df631ae 2294 rmap_walk_file(page, rwc, false);
b9773199
KS
2295}
2296
2297/* Like rmap_walk, but caller holds relevant rmap lock */
1df631ae 2298void rmap_walk_locked(struct page *page, struct rmap_walk_control *rwc)
b9773199
KS
2299{
2300 /* no ksm support for now */
2301 VM_BUG_ON_PAGE(PageKsm(page), page);
2302 if (PageAnon(page))
1df631ae 2303 rmap_walk_anon(page, rwc, true);
e9995ef9 2304 else
1df631ae 2305 rmap_walk_file(page, rwc, true);
e9995ef9 2306}
0fe6e20b 2307
e3390f67 2308#ifdef CONFIG_HUGETLB_PAGE
0fe6e20b 2309/*
451b9514 2310 * The following two functions are for anonymous (private mapped) hugepages.
0fe6e20b
NH
2311 * Unlike common anonymous pages, anonymous hugepages have no accounting code
2312 * and no lru code, because we handle hugepages differently from common pages.
2313 */
0fe6e20b
NH
2314void hugepage_add_anon_rmap(struct page *page,
2315 struct vm_area_struct *vma, unsigned long address)
2316{
2317 struct anon_vma *anon_vma = vma->anon_vma;
2318 int first;
a850ea30
NH
2319
2320 BUG_ON(!PageLocked(page));
0fe6e20b 2321 BUG_ON(!anon_vma);
5dbe0af4 2322 /* address might be in next vma when migration races vma_adjust */
53f9263b 2323 first = atomic_inc_and_test(compound_mapcount_ptr(page));
0fe6e20b 2324 if (first)
451b9514 2325 __page_set_anon_rmap(page, vma, address, 0);
0fe6e20b
NH
2326}
2327
2328void hugepage_add_new_anon_rmap(struct page *page,
2329 struct vm_area_struct *vma, unsigned long address)
2330{
2331 BUG_ON(address < vma->vm_start || address >= vma->vm_end);
53f9263b 2332 atomic_set(compound_mapcount_ptr(page), 0);
5232c63f 2333 atomic_set(compound_pincount_ptr(page), 0);
47e29d32 2334
451b9514 2335 __page_set_anon_rmap(page, vma, address, 1);
0fe6e20b 2336}
e3390f67 2337#endif /* CONFIG_HUGETLB_PAGE */