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