BACKPORT: mm: multi-gen LRU: exploit locality in rmap
[platform/kernel/linux-rpi.git] / mm / rmap.c
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_mutex       (while writing or truncating, not reading or faulting)
24  *   mm->mmap_sem
25  *     page->flags PG_locked (lock_page)
26  *       hugetlbfs_i_mmap_rwsem_key (in huge_pmd_share)
27  *         mapping->i_mmap_rwsem
28  *           anon_vma->rwsem
29  *             mm->page_table_lock or pte_lock
30  *               pgdat->lru_lock (in mark_page_accessed, isolate_lru_page)
31  *               swap_lock (in swap_duplicate, swap_info_get)
32  *                 mmlist_lock (in mmput, drain_mmlist and others)
33  *                 mapping->private_lock (in __set_page_dirty_buffers)
34  *                   mem_cgroup_{begin,end}_page_stat (memcg->move_lock)
35  *                     i_pages lock (widely used)
36  *                 inode->i_lock (in set_page_dirty's __mark_inode_dirty)
37  *                 bdi.wb->list_lock (in set_page_dirty's __mark_inode_dirty)
38  *                   sb_lock (within inode_lock in fs/fs-writeback.c)
39  *                   i_pages lock (widely used, in set_page_dirty,
40  *                             in arch-dependent flush_dcache_mmap_lock,
41  *                             within bdi.wb->list_lock in __sync_single_inode)
42  *
43  * anon_vma->rwsem,mapping->i_mutex      (memory_failure, collect_procs_anon)
44  *   ->tasklist_lock
45  *     pte map lock
46  */
47
48 #include <linux/mm.h>
49 #include <linux/sched/mm.h>
50 #include <linux/sched/task.h>
51 #include <linux/pagemap.h>
52 #include <linux/swap.h>
53 #include <linux/swapops.h>
54 #include <linux/slab.h>
55 #include <linux/init.h>
56 #include <linux/ksm.h>
57 #include <linux/rmap.h>
58 #include <linux/rcupdate.h>
59 #include <linux/export.h>
60 #include <linux/memcontrol.h>
61 #include <linux/mmu_notifier.h>
62 #include <linux/migrate.h>
63 #include <linux/hugetlb.h>
64 #include <linux/huge_mm.h>
65 #include <linux/backing-dev.h>
66 #include <linux/page_idle.h>
67 #include <linux/memremap.h>
68 #include <linux/userfaultfd_k.h>
69 #include <linux/mm_inline.h>
70
71 #include <asm/tlbflush.h>
72
73 #include <trace/events/tlb.h>
74
75 #include "internal.h"
76
77 static struct kmem_cache *anon_vma_cachep;
78 static struct kmem_cache *anon_vma_chain_cachep;
79
80 static inline struct anon_vma *anon_vma_alloc(void)
81 {
82         struct anon_vma *anon_vma;
83
84         anon_vma = kmem_cache_alloc(anon_vma_cachep, GFP_KERNEL);
85         if (anon_vma) {
86                 atomic_set(&anon_vma->refcount, 1);
87                 anon_vma->degree = 1;   /* Reference for first vma */
88                 anon_vma->parent = anon_vma;
89                 /*
90                  * Initialise the anon_vma root to point to itself. If called
91                  * from fork, the root will be reset to the parents anon_vma.
92                  */
93                 anon_vma->root = anon_vma;
94         }
95
96         return anon_vma;
97 }
98
99 static inline void anon_vma_free(struct anon_vma *anon_vma)
100 {
101         VM_BUG_ON(atomic_read(&anon_vma->refcount));
102
103         /*
104          * Synchronize against page_lock_anon_vma_read() such that
105          * we can safely hold the lock without the anon_vma getting
106          * freed.
107          *
108          * Relies on the full mb implied by the atomic_dec_and_test() from
109          * put_anon_vma() against the acquire barrier implied by
110          * down_read_trylock() from page_lock_anon_vma_read(). This orders:
111          *
112          * page_lock_anon_vma_read()    VS      put_anon_vma()
113          *   down_read_trylock()                  atomic_dec_and_test()
114          *   LOCK                                 MB
115          *   atomic_read()                        rwsem_is_locked()
116          *
117          * LOCK should suffice since the actual taking of the lock must
118          * happen _before_ what follows.
119          */
120         might_sleep();
121         if (rwsem_is_locked(&anon_vma->root->rwsem)) {
122                 anon_vma_lock_write(anon_vma);
123                 anon_vma_unlock_write(anon_vma);
124         }
125
126         kmem_cache_free(anon_vma_cachep, anon_vma);
127 }
128
129 static inline struct anon_vma_chain *anon_vma_chain_alloc(gfp_t gfp)
130 {
131         return kmem_cache_alloc(anon_vma_chain_cachep, gfp);
132 }
133
134 static void anon_vma_chain_free(struct anon_vma_chain *anon_vma_chain)
135 {
136         kmem_cache_free(anon_vma_chain_cachep, anon_vma_chain);
137 }
138
139 static void anon_vma_chain_link(struct vm_area_struct *vma,
140                                 struct anon_vma_chain *avc,
141                                 struct anon_vma *anon_vma)
142 {
143         avc->vma = vma;
144         avc->anon_vma = anon_vma;
145         list_add(&avc->same_vma, &vma->anon_vma_chain);
146         anon_vma_interval_tree_insert(avc, &anon_vma->rb_root);
147 }
148
149 /**
150  * __anon_vma_prepare - attach an anon_vma to a memory region
151  * @vma: the memory region in question
152  *
153  * This makes sure the memory mapping described by 'vma' has
154  * an 'anon_vma' attached to it, so that we can associate the
155  * anonymous pages mapped into it with that anon_vma.
156  *
157  * The common case will be that we already have one, which
158  * is handled inline by anon_vma_prepare(). But if
159  * not we either need to find an adjacent mapping that we
160  * can re-use the anon_vma from (very common when the only
161  * reason for splitting a vma has been mprotect()), or we
162  * allocate a new one.
163  *
164  * Anon-vma allocations are very subtle, because we may have
165  * optimistically looked up an anon_vma in page_lock_anon_vma_read()
166  * and that may actually touch the spinlock even in the newly
167  * allocated vma (it depends on RCU to make sure that the
168  * anon_vma isn't actually destroyed).
169  *
170  * As a result, we need to do proper anon_vma locking even
171  * for the new allocation. At the same time, we do not want
172  * to do any locking for the common case of already having
173  * an anon_vma.
174  *
175  * This must be called with the mmap_sem held for reading.
176  */
177 int __anon_vma_prepare(struct vm_area_struct *vma)
178 {
179         struct mm_struct *mm = vma->vm_mm;
180         struct anon_vma *anon_vma, *allocated;
181         struct anon_vma_chain *avc;
182
183         might_sleep();
184
185         avc = anon_vma_chain_alloc(GFP_KERNEL);
186         if (!avc)
187                 goto out_enomem;
188
189         anon_vma = find_mergeable_anon_vma(vma);
190         allocated = NULL;
191         if (!anon_vma) {
192                 anon_vma = anon_vma_alloc();
193                 if (unlikely(!anon_vma))
194                         goto out_enomem_free_avc;
195                 allocated = anon_vma;
196         }
197
198         anon_vma_lock_write(anon_vma);
199         /* page_table_lock to protect against threads */
200         spin_lock(&mm->page_table_lock);
201         if (likely(!vma->anon_vma)) {
202                 vma->anon_vma = anon_vma;
203                 anon_vma_chain_link(vma, avc, anon_vma);
204                 /* vma reference or self-parent link for new root */
205                 anon_vma->degree++;
206                 allocated = NULL;
207                 avc = NULL;
208         }
209         spin_unlock(&mm->page_table_lock);
210         anon_vma_unlock_write(anon_vma);
211
212         if (unlikely(allocated))
213                 put_anon_vma(allocated);
214         if (unlikely(avc))
215                 anon_vma_chain_free(avc);
216
217         return 0;
218
219  out_enomem_free_avc:
220         anon_vma_chain_free(avc);
221  out_enomem:
222         return -ENOMEM;
223 }
224
225 /*
226  * This is a useful helper function for locking the anon_vma root as
227  * we traverse the vma->anon_vma_chain, looping over anon_vma's that
228  * have the same vma.
229  *
230  * Such anon_vma's should have the same root, so you'd expect to see
231  * just a single mutex_lock for the whole traversal.
232  */
233 static inline struct anon_vma *lock_anon_vma_root(struct anon_vma *root, struct anon_vma *anon_vma)
234 {
235         struct anon_vma *new_root = anon_vma->root;
236         if (new_root != root) {
237                 if (WARN_ON_ONCE(root))
238                         up_write(&root->rwsem);
239                 root = new_root;
240                 down_write(&root->rwsem);
241         }
242         return root;
243 }
244
245 static inline void unlock_anon_vma_root(struct anon_vma *root)
246 {
247         if (root)
248                 up_write(&root->rwsem);
249 }
250
251 /*
252  * Attach the anon_vmas from src to dst.
253  * Returns 0 on success, -ENOMEM on failure.
254  *
255  * If dst->anon_vma is NULL this function tries to find and reuse existing
256  * anon_vma which has no vmas and only one child anon_vma. This prevents
257  * degradation of anon_vma hierarchy to endless linear chain in case of
258  * constantly forking task. On the other hand, an anon_vma with more than one
259  * child isn't reused even if there was no alive vma, thus rmap walker has a
260  * good chance of avoiding scanning the whole hierarchy when it searches where
261  * page is mapped.
262  */
263 int anon_vma_clone(struct vm_area_struct *dst, struct vm_area_struct *src)
264 {
265         struct anon_vma_chain *avc, *pavc;
266         struct anon_vma *root = NULL;
267
268         list_for_each_entry_reverse(pavc, &src->anon_vma_chain, same_vma) {
269                 struct anon_vma *anon_vma;
270
271                 avc = anon_vma_chain_alloc(GFP_NOWAIT | __GFP_NOWARN);
272                 if (unlikely(!avc)) {
273                         unlock_anon_vma_root(root);
274                         root = NULL;
275                         avc = anon_vma_chain_alloc(GFP_KERNEL);
276                         if (!avc)
277                                 goto enomem_failure;
278                 }
279                 anon_vma = pavc->anon_vma;
280                 root = lock_anon_vma_root(root, anon_vma);
281                 anon_vma_chain_link(dst, avc, anon_vma);
282
283                 /*
284                  * Reuse existing anon_vma if its degree lower than two,
285                  * that means it has no vma and only one anon_vma child.
286                  *
287                  * Do not chose parent anon_vma, otherwise first child
288                  * will always reuse it. Root anon_vma is never reused:
289                  * it has self-parent reference and at least one child.
290                  */
291                 if (!dst->anon_vma && anon_vma != src->anon_vma &&
292                                 anon_vma->degree < 2)
293                         dst->anon_vma = anon_vma;
294         }
295         if (dst->anon_vma)
296                 dst->anon_vma->degree++;
297         unlock_anon_vma_root(root);
298         return 0;
299
300  enomem_failure:
301         /*
302          * dst->anon_vma is dropped here otherwise its degree can be incorrectly
303          * decremented in unlink_anon_vmas().
304          * We can safely do this because callers of anon_vma_clone() don't care
305          * about dst->anon_vma if anon_vma_clone() failed.
306          */
307         dst->anon_vma = NULL;
308         unlink_anon_vmas(dst);
309         return -ENOMEM;
310 }
311
312 /*
313  * Attach vma to its own anon_vma, as well as to the anon_vmas that
314  * the corresponding VMA in the parent process is attached to.
315  * Returns 0 on success, non-zero on failure.
316  */
317 int anon_vma_fork(struct vm_area_struct *vma, struct vm_area_struct *pvma)
318 {
319         struct anon_vma_chain *avc;
320         struct anon_vma *anon_vma;
321         int error;
322
323         /* Don't bother if the parent process has no anon_vma here. */
324         if (!pvma->anon_vma)
325                 return 0;
326
327         /* Drop inherited anon_vma, we'll reuse existing or allocate new. */
328         vma->anon_vma = NULL;
329
330         /*
331          * First, attach the new VMA to the parent VMA's anon_vmas,
332          * so rmap can find non-COWed pages in child processes.
333          */
334         error = anon_vma_clone(vma, pvma);
335         if (error)
336                 return error;
337
338         /* An existing anon_vma has been reused, all done then. */
339         if (vma->anon_vma)
340                 return 0;
341
342         /* Then add our own anon_vma. */
343         anon_vma = anon_vma_alloc();
344         if (!anon_vma)
345                 goto out_error;
346         avc = anon_vma_chain_alloc(GFP_KERNEL);
347         if (!avc)
348                 goto out_error_free_anon_vma;
349
350         /*
351          * The root anon_vma's spinlock is the lock actually used when we
352          * lock any of the anon_vmas in this anon_vma tree.
353          */
354         anon_vma->root = pvma->anon_vma->root;
355         anon_vma->parent = pvma->anon_vma;
356         /*
357          * With refcounts, an anon_vma can stay around longer than the
358          * process it belongs to. The root anon_vma needs to be pinned until
359          * this anon_vma is freed, because the lock lives in the root.
360          */
361         get_anon_vma(anon_vma->root);
362         /* Mark this anon_vma as the one where our new (COWed) pages go. */
363         vma->anon_vma = anon_vma;
364         anon_vma_lock_write(anon_vma);
365         anon_vma_chain_link(vma, avc, anon_vma);
366         anon_vma->parent->degree++;
367         anon_vma_unlock_write(anon_vma);
368
369         return 0;
370
371  out_error_free_anon_vma:
372         put_anon_vma(anon_vma);
373  out_error:
374         unlink_anon_vmas(vma);
375         return -ENOMEM;
376 }
377
378 void unlink_anon_vmas(struct vm_area_struct *vma)
379 {
380         struct anon_vma_chain *avc, *next;
381         struct anon_vma *root = NULL;
382
383         /*
384          * Unlink each anon_vma chained to the VMA.  This list is ordered
385          * from newest to oldest, ensuring the root anon_vma gets freed last.
386          */
387         list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
388                 struct anon_vma *anon_vma = avc->anon_vma;
389
390                 root = lock_anon_vma_root(root, anon_vma);
391                 anon_vma_interval_tree_remove(avc, &anon_vma->rb_root);
392
393                 /*
394                  * Leave empty anon_vmas on the list - we'll need
395                  * to free them outside the lock.
396                  */
397                 if (RB_EMPTY_ROOT(&anon_vma->rb_root.rb_root)) {
398                         anon_vma->parent->degree--;
399                         continue;
400                 }
401
402                 list_del(&avc->same_vma);
403                 anon_vma_chain_free(avc);
404         }
405         if (vma->anon_vma)
406                 vma->anon_vma->degree--;
407         unlock_anon_vma_root(root);
408
409         /*
410          * Iterate the list once more, it now only contains empty and unlinked
411          * anon_vmas, destroy them. Could not do before due to __put_anon_vma()
412          * needing to write-acquire the anon_vma->root->rwsem.
413          */
414         list_for_each_entry_safe(avc, next, &vma->anon_vma_chain, same_vma) {
415                 struct anon_vma *anon_vma = avc->anon_vma;
416
417                 VM_WARN_ON(anon_vma->degree);
418                 put_anon_vma(anon_vma);
419
420                 list_del(&avc->same_vma);
421                 anon_vma_chain_free(avc);
422         }
423 }
424
425 static void anon_vma_ctor(void *data)
426 {
427         struct anon_vma *anon_vma = data;
428
429         init_rwsem(&anon_vma->rwsem);
430         atomic_set(&anon_vma->refcount, 0);
431         anon_vma->rb_root = RB_ROOT_CACHED;
432 }
433
434 void __init anon_vma_init(void)
435 {
436         anon_vma_cachep = kmem_cache_create("anon_vma", sizeof(struct anon_vma),
437                         0, SLAB_TYPESAFE_BY_RCU|SLAB_PANIC|SLAB_ACCOUNT,
438                         anon_vma_ctor);
439         anon_vma_chain_cachep = KMEM_CACHE(anon_vma_chain,
440                         SLAB_PANIC|SLAB_ACCOUNT);
441 }
442
443 /*
444  * Getting a lock on a stable anon_vma from a page off the LRU is tricky!
445  *
446  * Since there is no serialization what so ever against page_remove_rmap()
447  * the best this function can do is return a locked anon_vma that might
448  * have been relevant to this page.
449  *
450  * The page might have been remapped to a different anon_vma or the anon_vma
451  * returned may already be freed (and even reused).
452  *
453  * In case it was remapped to a different anon_vma, the new anon_vma will be a
454  * child of the old anon_vma, and the anon_vma lifetime rules will therefore
455  * ensure that any anon_vma obtained from the page will still be valid for as
456  * long as we observe page_mapped() [ hence all those page_mapped() tests ].
457  *
458  * All users of this function must be very careful when walking the anon_vma
459  * chain and verify that the page in question is indeed mapped in it
460  * [ something equivalent to page_mapped_in_vma() ].
461  *
462  * Since anon_vma's slab is DESTROY_BY_RCU and we know from page_remove_rmap()
463  * that the anon_vma pointer from page->mapping is valid if there is a
464  * mapcount, we can dereference the anon_vma after observing those.
465  */
466 struct anon_vma *page_get_anon_vma(struct page *page)
467 {
468         struct anon_vma *anon_vma = NULL;
469         unsigned long anon_mapping;
470
471         rcu_read_lock();
472         anon_mapping = (unsigned long)READ_ONCE(page->mapping);
473         if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
474                 goto out;
475         if (!page_mapped(page))
476                 goto out;
477
478         anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
479         if (!atomic_inc_not_zero(&anon_vma->refcount)) {
480                 anon_vma = NULL;
481                 goto out;
482         }
483
484         /*
485          * If this page is still mapped, then its anon_vma cannot have been
486          * freed.  But if it has been unmapped, we have no security against the
487          * anon_vma structure being freed and reused (for another anon_vma:
488          * SLAB_TYPESAFE_BY_RCU guarantees that - so the atomic_inc_not_zero()
489          * above cannot corrupt).
490          */
491         if (!page_mapped(page)) {
492                 rcu_read_unlock();
493                 put_anon_vma(anon_vma);
494                 return NULL;
495         }
496 out:
497         rcu_read_unlock();
498
499         return anon_vma;
500 }
501
502 /*
503  * Similar to page_get_anon_vma() except it locks the anon_vma.
504  *
505  * Its a little more complex as it tries to keep the fast path to a single
506  * atomic op -- the trylock. If we fail the trylock, we fall back to getting a
507  * reference like with page_get_anon_vma() and then block on the mutex.
508  */
509 struct anon_vma *page_lock_anon_vma_read(struct page *page)
510 {
511         struct anon_vma *anon_vma = NULL;
512         struct anon_vma *root_anon_vma;
513         unsigned long anon_mapping;
514
515         rcu_read_lock();
516         anon_mapping = (unsigned long)READ_ONCE(page->mapping);
517         if ((anon_mapping & PAGE_MAPPING_FLAGS) != PAGE_MAPPING_ANON)
518                 goto out;
519         if (!page_mapped(page))
520                 goto out;
521
522         anon_vma = (struct anon_vma *) (anon_mapping - PAGE_MAPPING_ANON);
523         root_anon_vma = READ_ONCE(anon_vma->root);
524         if (down_read_trylock(&root_anon_vma->rwsem)) {
525                 /*
526                  * If the page is still mapped, then this anon_vma is still
527                  * its anon_vma, and holding the mutex ensures that it will
528                  * not go away, see anon_vma_free().
529                  */
530                 if (!page_mapped(page)) {
531                         up_read(&root_anon_vma->rwsem);
532                         anon_vma = NULL;
533                 }
534                 goto out;
535         }
536
537         /* trylock failed, we got to sleep */
538         if (!atomic_inc_not_zero(&anon_vma->refcount)) {
539                 anon_vma = NULL;
540                 goto out;
541         }
542
543         if (!page_mapped(page)) {
544                 rcu_read_unlock();
545                 put_anon_vma(anon_vma);
546                 return NULL;
547         }
548
549         /* we pinned the anon_vma, its safe to sleep */
550         rcu_read_unlock();
551         anon_vma_lock_read(anon_vma);
552
553         if (atomic_dec_and_test(&anon_vma->refcount)) {
554                 /*
555                  * Oops, we held the last refcount, release the lock
556                  * and bail -- can't simply use put_anon_vma() because
557                  * we'll deadlock on the anon_vma_lock_write() recursion.
558                  */
559                 anon_vma_unlock_read(anon_vma);
560                 __put_anon_vma(anon_vma);
561                 anon_vma = NULL;
562         }
563
564         return anon_vma;
565
566 out:
567         rcu_read_unlock();
568         return anon_vma;
569 }
570
571 void page_unlock_anon_vma_read(struct anon_vma *anon_vma)
572 {
573         anon_vma_unlock_read(anon_vma);
574 }
575
576 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
577 /*
578  * Flush TLB entries for recently unmapped pages from remote CPUs. It is
579  * important if a PTE was dirty when it was unmapped that it's flushed
580  * before any IO is initiated on the page to prevent lost writes. Similarly,
581  * it must be flushed before freeing to prevent data leakage.
582  */
583 void try_to_unmap_flush(void)
584 {
585         struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
586
587         if (!tlb_ubc->flush_required)
588                 return;
589
590         arch_tlbbatch_flush(&tlb_ubc->arch);
591         tlb_ubc->flush_required = false;
592         tlb_ubc->writable = false;
593 }
594
595 /* Flush iff there are potentially writable TLB entries that can race with IO */
596 void try_to_unmap_flush_dirty(void)
597 {
598         struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
599
600         if (tlb_ubc->writable)
601                 try_to_unmap_flush();
602 }
603
604 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
605 {
606         struct tlbflush_unmap_batch *tlb_ubc = &current->tlb_ubc;
607
608         arch_tlbbatch_add_mm(&tlb_ubc->arch, mm);
609         tlb_ubc->flush_required = true;
610
611         /*
612          * Ensure compiler does not re-order the setting of tlb_flush_batched
613          * before the PTE is cleared.
614          */
615         barrier();
616         mm->tlb_flush_batched = true;
617
618         /*
619          * If the PTE was dirty then it's best to assume it's writable. The
620          * caller must use try_to_unmap_flush_dirty() or try_to_unmap_flush()
621          * before the page is queued for IO.
622          */
623         if (writable)
624                 tlb_ubc->writable = true;
625 }
626
627 /*
628  * Returns true if the TLB flush should be deferred to the end of a batch of
629  * unmap operations to reduce IPIs.
630  */
631 static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
632 {
633         bool should_defer = false;
634
635         if (!(flags & TTU_BATCH_FLUSH))
636                 return false;
637
638         /* If remote CPUs need to be flushed then defer batch the flush */
639         if (cpumask_any_but(mm_cpumask(mm), get_cpu()) < nr_cpu_ids)
640                 should_defer = true;
641         put_cpu();
642
643         return should_defer;
644 }
645
646 /*
647  * Reclaim unmaps pages under the PTL but do not flush the TLB prior to
648  * releasing the PTL if TLB flushes are batched. It's possible for a parallel
649  * operation such as mprotect or munmap to race between reclaim unmapping
650  * the page and flushing the page. If this race occurs, it potentially allows
651  * access to data via a stale TLB entry. Tracking all mm's that have TLB
652  * batching in flight would be expensive during reclaim so instead track
653  * whether TLB batching occurred in the past and if so then do a flush here
654  * if required. This will cost one additional flush per reclaim cycle paid
655  * by the first operation at risk such as mprotect and mumap.
656  *
657  * This must be called under the PTL so that an access to tlb_flush_batched
658  * that is potentially a "reclaim vs mprotect/munmap/etc" race will synchronise
659  * via the PTL.
660  */
661 void flush_tlb_batched_pending(struct mm_struct *mm)
662 {
663         if (mm->tlb_flush_batched) {
664                 flush_tlb_mm(mm);
665
666                 /*
667                  * Do not allow the compiler to re-order the clearing of
668                  * tlb_flush_batched before the tlb is flushed.
669                  */
670                 barrier();
671                 mm->tlb_flush_batched = false;
672         }
673 }
674 #else
675 static void set_tlb_ubc_flush_pending(struct mm_struct *mm, bool writable)
676 {
677 }
678
679 static bool should_defer_flush(struct mm_struct *mm, enum ttu_flags flags)
680 {
681         return false;
682 }
683 #endif /* CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH */
684
685 /*
686  * At what user virtual address is page expected in vma?
687  * Caller should check the page is actually part of the vma.
688  */
689 unsigned long page_address_in_vma(struct page *page, struct vm_area_struct *vma)
690 {
691         unsigned long address;
692         if (PageAnon(page)) {
693                 struct anon_vma *page__anon_vma = page_anon_vma(page);
694                 /*
695                  * Note: swapoff's unuse_vma() is more efficient with this
696                  * check, and needs it to match anon_vma when KSM is active.
697                  */
698                 if (!vma->anon_vma || !page__anon_vma ||
699                     vma->anon_vma->root != page__anon_vma->root)
700                         return -EFAULT;
701         } else if (page->mapping) {
702                 if (!vma->vm_file || vma->vm_file->f_mapping != page->mapping)
703                         return -EFAULT;
704         } else
705                 return -EFAULT;
706         address = __vma_address(page, vma);
707         if (unlikely(address < vma->vm_start || address >= vma->vm_end))
708                 return -EFAULT;
709         return address;
710 }
711
712 pmd_t *mm_find_pmd(struct mm_struct *mm, unsigned long address)
713 {
714         pgd_t *pgd;
715         p4d_t *p4d;
716         pud_t *pud;
717         pmd_t *pmd = NULL;
718         pmd_t pmde;
719
720         pgd = pgd_offset(mm, address);
721         if (!pgd_present(*pgd))
722                 goto out;
723
724         p4d = p4d_offset(pgd, address);
725         if (!p4d_present(*p4d))
726                 goto out;
727
728         pud = pud_offset(p4d, address);
729         if (!pud_present(*pud))
730                 goto out;
731
732         pmd = pmd_offset(pud, address);
733         /*
734          * Some THP functions use the sequence pmdp_huge_clear_flush(), set_pmd_at()
735          * without holding anon_vma lock for write.  So when looking for a
736          * genuine pmde (in which to find pte), test present and !THP together.
737          */
738         pmde = *pmd;
739         barrier();
740         if (!pmd_present(pmde) || pmd_trans_huge(pmde))
741                 pmd = NULL;
742 out:
743         return pmd;
744 }
745
746 struct page_referenced_arg {
747         int mapcount;
748         int referenced;
749         unsigned long vm_flags;
750         struct mem_cgroup *memcg;
751 };
752 /*
753  * arg: page_referenced_arg will be passed
754  */
755 static bool page_referenced_one(struct page *page, struct vm_area_struct *vma,
756                         unsigned long address, void *arg)
757 {
758         struct page_referenced_arg *pra = arg;
759         struct page_vma_mapped_walk pvmw = {
760                 .page = page,
761                 .vma = vma,
762                 .address = address,
763         };
764         int referenced = 0;
765
766         while (page_vma_mapped_walk(&pvmw)) {
767                 address = pvmw.address;
768
769                 if (vma->vm_flags & VM_LOCKED) {
770                         page_vma_mapped_walk_done(&pvmw);
771                         pra->vm_flags |= VM_LOCKED;
772                         return false; /* To break the loop */
773                 }
774
775                 if (pvmw.pte) {
776                         if (lru_gen_enabled() && pte_young(*pvmw.pte) &&
777                             !(vma->vm_flags & (VM_SEQ_READ | VM_RAND_READ))) {
778                                 lru_gen_look_around(&pvmw);
779                                 referenced++;
780                         }
781
782                         if (ptep_clear_flush_young_notify(vma, address,
783                                                 pvmw.pte)) {
784                                 /*
785                                  * Don't treat a reference through
786                                  * a sequentially read mapping as such.
787                                  * If the page has been used in another mapping,
788                                  * we will catch it; if this other mapping is
789                                  * already gone, the unmap path will have set
790                                  * PG_referenced or activated the page.
791                                  */
792                                 if (likely(!(vma->vm_flags & VM_SEQ_READ)))
793                                         referenced++;
794                         }
795                 } else if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
796                         if (pmdp_clear_flush_young_notify(vma, address,
797                                                 pvmw.pmd))
798                                 referenced++;
799                 } else {
800                         /* unexpected pmd-mapped page? */
801                         WARN_ON_ONCE(1);
802                 }
803
804                 pra->mapcount--;
805         }
806
807         if (referenced)
808                 clear_page_idle(page);
809         if (test_and_clear_page_young(page))
810                 referenced++;
811
812         if (referenced) {
813                 pra->referenced++;
814                 pra->vm_flags |= vma->vm_flags;
815         }
816
817         if (!pra->mapcount)
818                 return false; /* To break the loop */
819
820         return true;
821 }
822
823 static bool invalid_page_referenced_vma(struct vm_area_struct *vma, void *arg)
824 {
825         struct page_referenced_arg *pra = arg;
826         struct mem_cgroup *memcg = pra->memcg;
827
828         if (!mm_match_cgroup(vma->vm_mm, memcg))
829                 return true;
830
831         return false;
832 }
833
834 /**
835  * page_referenced - test if the page was referenced
836  * @page: the page to test
837  * @is_locked: caller holds lock on the page
838  * @memcg: target memory cgroup
839  * @vm_flags: collect encountered vma->vm_flags who actually referenced the page
840  *
841  * Quick test_and_clear_referenced for all mappings to a page,
842  * returns the number of ptes which referenced the page.
843  */
844 int page_referenced(struct page *page,
845                     int is_locked,
846                     struct mem_cgroup *memcg,
847                     unsigned long *vm_flags)
848 {
849         int we_locked = 0;
850         struct page_referenced_arg pra = {
851                 .mapcount = total_mapcount(page),
852                 .memcg = memcg,
853         };
854         struct rmap_walk_control rwc = {
855                 .rmap_one = page_referenced_one,
856                 .arg = (void *)&pra,
857                 .anon_lock = page_lock_anon_vma_read,
858         };
859
860         *vm_flags = 0;
861         if (!pra.mapcount)
862                 return 0;
863
864         if (!page_rmapping(page))
865                 return 0;
866
867         if (!is_locked && (!PageAnon(page) || PageKsm(page))) {
868                 we_locked = trylock_page(page);
869                 if (!we_locked)
870                         return 1;
871         }
872
873         /*
874          * If we are reclaiming on behalf of a cgroup, skip
875          * counting on behalf of references from different
876          * cgroups
877          */
878         if (memcg) {
879                 rwc.invalid_vma = invalid_page_referenced_vma;
880         }
881
882         rmap_walk(page, &rwc);
883         *vm_flags = pra.vm_flags;
884
885         if (we_locked)
886                 unlock_page(page);
887
888         return pra.referenced;
889 }
890
891 static bool page_mkclean_one(struct page *page, struct vm_area_struct *vma,
892                             unsigned long address, void *arg)
893 {
894         struct page_vma_mapped_walk pvmw = {
895                 .page = page,
896                 .vma = vma,
897                 .address = address,
898                 .flags = PVMW_SYNC,
899         };
900         struct mmu_notifier_range range;
901         int *cleaned = arg;
902
903         /*
904          * We have to assume the worse case ie pmd for invalidation. Note that
905          * the page can not be free from this function.
906          */
907         mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
908                                 0, vma, vma->vm_mm, address,
909                                 min(vma->vm_end, address + page_size(page)));
910         mmu_notifier_invalidate_range_start(&range);
911
912         while (page_vma_mapped_walk(&pvmw)) {
913                 int ret = 0;
914
915                 address = pvmw.address;
916                 if (pvmw.pte) {
917                         pte_t entry;
918                         pte_t *pte = pvmw.pte;
919
920                         if (!pte_dirty(*pte) && !pte_write(*pte))
921                                 continue;
922
923                         flush_cache_page(vma, address, pte_pfn(*pte));
924                         entry = ptep_clear_flush(vma, address, pte);
925                         entry = pte_wrprotect(entry);
926                         entry = pte_mkclean(entry);
927                         set_pte_at(vma->vm_mm, address, pte, entry);
928                         ret = 1;
929                 } else {
930 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
931                         pmd_t *pmd = pvmw.pmd;
932                         pmd_t entry;
933
934                         if (!pmd_dirty(*pmd) && !pmd_write(*pmd))
935                                 continue;
936
937                         flush_cache_page(vma, address, page_to_pfn(page));
938                         entry = pmdp_invalidate(vma, address, pmd);
939                         entry = pmd_wrprotect(entry);
940                         entry = pmd_mkclean(entry);
941                         set_pmd_at(vma->vm_mm, address, pmd, entry);
942                         ret = 1;
943 #else
944                         /* unexpected pmd-mapped page? */
945                         WARN_ON_ONCE(1);
946 #endif
947                 }
948
949                 /*
950                  * No need to call mmu_notifier_invalidate_range() as we are
951                  * downgrading page table protection not changing it to point
952                  * to a new page.
953                  *
954                  * See Documentation/vm/mmu_notifier.rst
955                  */
956                 if (ret)
957                         (*cleaned)++;
958         }
959
960         mmu_notifier_invalidate_range_end(&range);
961
962         return true;
963 }
964
965 static bool invalid_mkclean_vma(struct vm_area_struct *vma, void *arg)
966 {
967         if (vma->vm_flags & VM_SHARED)
968                 return false;
969
970         return true;
971 }
972
973 int page_mkclean(struct page *page)
974 {
975         int cleaned = 0;
976         struct address_space *mapping;
977         struct rmap_walk_control rwc = {
978                 .arg = (void *)&cleaned,
979                 .rmap_one = page_mkclean_one,
980                 .invalid_vma = invalid_mkclean_vma,
981         };
982
983         BUG_ON(!PageLocked(page));
984
985         if (!page_mapped(page))
986                 return 0;
987
988         mapping = page_mapping(page);
989         if (!mapping)
990                 return 0;
991
992         rmap_walk(page, &rwc);
993
994         return cleaned;
995 }
996 EXPORT_SYMBOL_GPL(page_mkclean);
997
998 /**
999  * page_move_anon_rmap - move a page to our anon_vma
1000  * @page:       the page to move to our anon_vma
1001  * @vma:        the vma the page belongs to
1002  *
1003  * When a page belongs exclusively to one process after a COW event,
1004  * that page can be moved into the anon_vma that belongs to just that
1005  * process, so the rmap code will not search the parent or sibling
1006  * processes.
1007  */
1008 void page_move_anon_rmap(struct page *page, struct vm_area_struct *vma)
1009 {
1010         struct anon_vma *anon_vma = vma->anon_vma;
1011
1012         page = compound_head(page);
1013
1014         VM_BUG_ON_PAGE(!PageLocked(page), page);
1015         VM_BUG_ON_VMA(!anon_vma, vma);
1016
1017         anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
1018         /*
1019          * Ensure that anon_vma and the PAGE_MAPPING_ANON bit are written
1020          * simultaneously, so a concurrent reader (eg page_referenced()'s
1021          * PageAnon()) will not see one without the other.
1022          */
1023         WRITE_ONCE(page->mapping, (struct address_space *) anon_vma);
1024 }
1025
1026 /**
1027  * __page_set_anon_rmap - set up new anonymous rmap
1028  * @page:       Page or Hugepage to add to rmap
1029  * @vma:        VM area to add page to.
1030  * @address:    User virtual address of the mapping     
1031  * @exclusive:  the page is exclusively owned by the current process
1032  */
1033 static void __page_set_anon_rmap(struct page *page,
1034         struct vm_area_struct *vma, unsigned long address, int exclusive)
1035 {
1036         struct anon_vma *anon_vma = vma->anon_vma;
1037
1038         BUG_ON(!anon_vma);
1039
1040         if (PageAnon(page))
1041                 return;
1042
1043         /*
1044          * If the page isn't exclusively mapped into this vma,
1045          * we must use the _oldest_ possible anon_vma for the
1046          * page mapping!
1047          */
1048         if (!exclusive)
1049                 anon_vma = anon_vma->root;
1050
1051         anon_vma = (void *) anon_vma + PAGE_MAPPING_ANON;
1052         page->mapping = (struct address_space *) anon_vma;
1053         page->index = linear_page_index(vma, address);
1054 }
1055
1056 /**
1057  * __page_check_anon_rmap - sanity check anonymous rmap addition
1058  * @page:       the page to add the mapping to
1059  * @vma:        the vm area in which the mapping is added
1060  * @address:    the user virtual address mapped
1061  */
1062 static void __page_check_anon_rmap(struct page *page,
1063         struct vm_area_struct *vma, unsigned long address)
1064 {
1065 #ifdef CONFIG_DEBUG_VM
1066         /*
1067          * The page's anon-rmap details (mapping and index) are guaranteed to
1068          * be set up correctly at this point.
1069          *
1070          * We have exclusion against page_add_anon_rmap because the caller
1071          * always holds the page locked, except if called from page_dup_rmap,
1072          * in which case the page is already known to be setup.
1073          *
1074          * We have exclusion against page_add_new_anon_rmap because those pages
1075          * are initially only visible via the pagetables, and the pte is locked
1076          * over the call to page_add_new_anon_rmap.
1077          */
1078         BUG_ON(page_anon_vma(page)->root != vma->anon_vma->root);
1079         BUG_ON(page_to_pgoff(page) != linear_page_index(vma, address));
1080 #endif
1081 }
1082
1083 /**
1084  * page_add_anon_rmap - add pte mapping to an anonymous page
1085  * @page:       the page to add the mapping to
1086  * @vma:        the vm area in which the mapping is added
1087  * @address:    the user virtual address mapped
1088  * @compound:   charge the page as compound or small page
1089  *
1090  * The caller needs to hold the pte lock, and the page must be locked in
1091  * the anon_vma case: to serialize mapping,index checking after setting,
1092  * and to ensure that PageAnon is not being upgraded racily to PageKsm
1093  * (but PageKsm is never downgraded to PageAnon).
1094  */
1095 void page_add_anon_rmap(struct page *page,
1096         struct vm_area_struct *vma, unsigned long address, bool compound)
1097 {
1098         do_page_add_anon_rmap(page, vma, address, compound ? RMAP_COMPOUND : 0);
1099 }
1100
1101 /*
1102  * Special version of the above for do_swap_page, which often runs
1103  * into pages that are exclusively owned by the current process.
1104  * Everybody else should continue to use page_add_anon_rmap above.
1105  */
1106 void do_page_add_anon_rmap(struct page *page,
1107         struct vm_area_struct *vma, unsigned long address, int flags)
1108 {
1109         bool compound = flags & RMAP_COMPOUND;
1110         bool first;
1111
1112         if (compound) {
1113                 atomic_t *mapcount;
1114                 VM_BUG_ON_PAGE(!PageLocked(page), page);
1115                 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
1116                 mapcount = compound_mapcount_ptr(page);
1117                 first = atomic_inc_and_test(mapcount);
1118         } else {
1119                 first = atomic_inc_and_test(&page->_mapcount);
1120         }
1121
1122         if (first) {
1123                 int nr = compound ? hpage_nr_pages(page) : 1;
1124                 /*
1125                  * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1126                  * these counters are not modified in interrupt context, and
1127                  * pte lock(a spinlock) is held, which implies preemption
1128                  * disabled.
1129                  */
1130                 if (compound)
1131                         __inc_node_page_state(page, NR_ANON_THPS);
1132                 __mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, nr);
1133         }
1134         if (unlikely(PageKsm(page)))
1135                 return;
1136
1137         VM_BUG_ON_PAGE(!PageLocked(page), page);
1138
1139         /* address might be in next vma when migration races vma_adjust */
1140         if (first)
1141                 __page_set_anon_rmap(page, vma, address,
1142                                 flags & RMAP_EXCLUSIVE);
1143         else
1144                 __page_check_anon_rmap(page, vma, address);
1145 }
1146
1147 /**
1148  * page_add_new_anon_rmap - add pte mapping to a new anonymous page
1149  * @page:       the page to add the mapping to
1150  * @vma:        the vm area in which the mapping is added
1151  * @address:    the user virtual address mapped
1152  * @compound:   charge the page as compound or small page
1153  *
1154  * Same as page_add_anon_rmap but must only be called on *new* pages.
1155  * This means the inc-and-test can be bypassed.
1156  * Page does not have to be locked.
1157  */
1158 void page_add_new_anon_rmap(struct page *page,
1159         struct vm_area_struct *vma, unsigned long address, bool compound)
1160 {
1161         int nr = compound ? hpage_nr_pages(page) : 1;
1162
1163         VM_BUG_ON_VMA(address < vma->vm_start || address >= vma->vm_end, vma);
1164         __SetPageSwapBacked(page);
1165         if (compound) {
1166                 VM_BUG_ON_PAGE(!PageTransHuge(page), page);
1167                 /* increment count (starts at -1) */
1168                 atomic_set(compound_mapcount_ptr(page), 0);
1169                 __inc_node_page_state(page, NR_ANON_THPS);
1170         } else {
1171                 /* Anon THP always mapped first with PMD */
1172                 VM_BUG_ON_PAGE(PageTransCompound(page), page);
1173                 /* increment count (starts at -1) */
1174                 atomic_set(&page->_mapcount, 0);
1175         }
1176         __mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, nr);
1177         __page_set_anon_rmap(page, vma, address, 1);
1178 }
1179
1180 /**
1181  * page_add_file_rmap - add pte mapping to a file page
1182  * @page: the page to add the mapping to
1183  * @compound: charge the page as compound or small page
1184  *
1185  * The caller needs to hold the pte lock.
1186  */
1187 void page_add_file_rmap(struct page *page, bool compound)
1188 {
1189         int i, nr = 1;
1190
1191         VM_BUG_ON_PAGE(compound && !PageTransHuge(page), page);
1192         lock_page_memcg(page);
1193         if (compound && PageTransHuge(page)) {
1194                 for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
1195                         if (atomic_inc_and_test(&page[i]._mapcount))
1196                                 nr++;
1197                 }
1198                 if (!atomic_inc_and_test(compound_mapcount_ptr(page)))
1199                         goto out;
1200                 if (PageSwapBacked(page))
1201                         __inc_node_page_state(page, NR_SHMEM_PMDMAPPED);
1202                 else
1203                         __inc_node_page_state(page, NR_FILE_PMDMAPPED);
1204         } else {
1205                 if (PageTransCompound(page) && page_mapping(page)) {
1206                         VM_WARN_ON_ONCE(!PageLocked(page));
1207
1208                         SetPageDoubleMap(compound_head(page));
1209                         if (PageMlocked(page))
1210                                 clear_page_mlock(compound_head(page));
1211                 }
1212                 if (!atomic_inc_and_test(&page->_mapcount))
1213                         goto out;
1214         }
1215         __mod_lruvec_page_state(page, NR_FILE_MAPPED, nr);
1216 out:
1217         unlock_page_memcg(page);
1218 }
1219
1220 static void page_remove_file_rmap(struct page *page, bool compound)
1221 {
1222         int i, nr = 1;
1223
1224         VM_BUG_ON_PAGE(compound && !PageHead(page), page);
1225         lock_page_memcg(page);
1226
1227         /* Hugepages are not counted in NR_FILE_MAPPED for now. */
1228         if (unlikely(PageHuge(page))) {
1229                 /* hugetlb pages are always mapped with pmds */
1230                 atomic_dec(compound_mapcount_ptr(page));
1231                 goto out;
1232         }
1233
1234         /* page still mapped by someone else? */
1235         if (compound && PageTransHuge(page)) {
1236                 for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
1237                         if (atomic_add_negative(-1, &page[i]._mapcount))
1238                                 nr++;
1239                 }
1240                 if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1241                         goto out;
1242                 if (PageSwapBacked(page))
1243                         __dec_node_page_state(page, NR_SHMEM_PMDMAPPED);
1244                 else
1245                         __dec_node_page_state(page, NR_FILE_PMDMAPPED);
1246         } else {
1247                 if (!atomic_add_negative(-1, &page->_mapcount))
1248                         goto out;
1249         }
1250
1251         /*
1252          * We use the irq-unsafe __{inc|mod}_lruvec_page_state because
1253          * these counters are not modified in interrupt context, and
1254          * pte lock(a spinlock) is held, which implies preemption disabled.
1255          */
1256         __mod_lruvec_page_state(page, NR_FILE_MAPPED, -nr);
1257
1258         if (unlikely(PageMlocked(page)))
1259                 clear_page_mlock(page);
1260 out:
1261         unlock_page_memcg(page);
1262 }
1263
1264 static void page_remove_anon_compound_rmap(struct page *page)
1265 {
1266         int i, nr;
1267
1268         if (!atomic_add_negative(-1, compound_mapcount_ptr(page)))
1269                 return;
1270
1271         /* Hugepages are not counted in NR_ANON_PAGES for now. */
1272         if (unlikely(PageHuge(page)))
1273                 return;
1274
1275         if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
1276                 return;
1277
1278         __dec_node_page_state(page, NR_ANON_THPS);
1279
1280         if (TestClearPageDoubleMap(page)) {
1281                 /*
1282                  * Subpages can be mapped with PTEs too. Check how many of
1283                  * themi are still mapped.
1284                  */
1285                 for (i = 0, nr = 0; i < HPAGE_PMD_NR; i++) {
1286                         if (atomic_add_negative(-1, &page[i]._mapcount))
1287                                 nr++;
1288                 }
1289         } else {
1290                 nr = HPAGE_PMD_NR;
1291         }
1292
1293         if (unlikely(PageMlocked(page)))
1294                 clear_page_mlock(page);
1295
1296         if (nr) {
1297                 __mod_node_page_state(page_pgdat(page), NR_ANON_MAPPED, -nr);
1298                 deferred_split_huge_page(page);
1299         }
1300 }
1301
1302 /**
1303  * page_remove_rmap - take down pte mapping from a page
1304  * @page:       page to remove mapping from
1305  * @compound:   uncharge the page as compound or small page
1306  *
1307  * The caller needs to hold the pte lock.
1308  */
1309 void page_remove_rmap(struct page *page, bool compound)
1310 {
1311         if (!PageAnon(page))
1312                 return page_remove_file_rmap(page, compound);
1313
1314         if (compound)
1315                 return page_remove_anon_compound_rmap(page);
1316
1317         /* page still mapped by someone else? */
1318         if (!atomic_add_negative(-1, &page->_mapcount))
1319                 return;
1320
1321         /*
1322          * We use the irq-unsafe __{inc|mod}_zone_page_stat because
1323          * these counters are not modified in interrupt context, and
1324          * pte lock(a spinlock) is held, which implies preemption disabled.
1325          */
1326         __dec_node_page_state(page, NR_ANON_MAPPED);
1327
1328         if (unlikely(PageMlocked(page)))
1329                 clear_page_mlock(page);
1330
1331         if (PageTransCompound(page))
1332                 deferred_split_huge_page(compound_head(page));
1333
1334         /*
1335          * It would be tidy to reset the PageAnon mapping here,
1336          * but that might overwrite a racing page_add_anon_rmap
1337          * which increments mapcount after us but sets mapping
1338          * before us: so leave the reset to free_unref_page,
1339          * and remember that it's only reliable while mapped.
1340          * Leaving it set also helps swapoff to reinstate ptes
1341          * faster for those pages still in swapcache.
1342          */
1343 }
1344
1345 /*
1346  * @arg: enum ttu_flags will be passed to this argument
1347  */
1348 static bool try_to_unmap_one(struct page *page, struct vm_area_struct *vma,
1349                      unsigned long address, void *arg)
1350 {
1351         struct mm_struct *mm = vma->vm_mm;
1352         struct page_vma_mapped_walk pvmw = {
1353                 .page = page,
1354                 .vma = vma,
1355                 .address = address,
1356         };
1357         pte_t pteval;
1358         struct page *subpage;
1359         bool ret = true;
1360         struct mmu_notifier_range range;
1361         enum ttu_flags flags = (enum ttu_flags)arg;
1362
1363         /* munlock has nothing to gain from examining un-locked vmas */
1364         if ((flags & TTU_MUNLOCK) && !(vma->vm_flags & VM_LOCKED))
1365                 return true;
1366
1367         if (IS_ENABLED(CONFIG_MIGRATION) && (flags & TTU_MIGRATION) &&
1368             is_zone_device_page(page) && !is_device_private_page(page))
1369                 return true;
1370
1371         if (flags & TTU_SPLIT_HUGE_PMD) {
1372                 split_huge_pmd_address(vma, address,
1373                                 flags & TTU_SPLIT_FREEZE, page);
1374         }
1375
1376         /*
1377          * For THP, we have to assume the worse case ie pmd for invalidation.
1378          * For hugetlb, it could be much worse if we need to do pud
1379          * invalidation in the case of pmd sharing.
1380          *
1381          * Note that the page can not be free in this function as call of
1382          * try_to_unmap() must hold a reference on the page.
1383          */
1384         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1385                                 address,
1386                                 min(vma->vm_end, address + page_size(page)));
1387         if (PageHuge(page)) {
1388                 /*
1389                  * If sharing is possible, start and end will be adjusted
1390                  * accordingly.
1391                  */
1392                 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1393                                                      &range.end);
1394         }
1395         mmu_notifier_invalidate_range_start(&range);
1396
1397         while (page_vma_mapped_walk(&pvmw)) {
1398 #ifdef CONFIG_ARCH_ENABLE_THP_MIGRATION
1399                 /* PMD-mapped THP migration entry */
1400                 if (!pvmw.pte && (flags & TTU_MIGRATION)) {
1401                         VM_BUG_ON_PAGE(PageHuge(page) || !PageTransCompound(page), page);
1402
1403                         set_pmd_migration_entry(&pvmw, page);
1404                         continue;
1405                 }
1406 #endif
1407
1408                 /*
1409                  * If the page is mlock()d, we cannot swap it out.
1410                  * If it's recently referenced (perhaps page_referenced
1411                  * skipped over this mm) then we should reactivate it.
1412                  */
1413                 if (!(flags & TTU_IGNORE_MLOCK)) {
1414                         if (vma->vm_flags & VM_LOCKED) {
1415                                 /* PTE-mapped THP are never mlocked */
1416                                 if (!PageTransCompound(page)) {
1417                                         /*
1418                                          * Holding pte lock, we do *not* need
1419                                          * mmap_sem here
1420                                          */
1421                                         mlock_vma_page(page);
1422                                 }
1423                                 ret = false;
1424                                 page_vma_mapped_walk_done(&pvmw);
1425                                 break;
1426                         }
1427                         if (flags & TTU_MUNLOCK)
1428                                 continue;
1429                 }
1430
1431                 /* Unexpected PMD-mapped THP? */
1432                 VM_BUG_ON_PAGE(!pvmw.pte, page);
1433
1434                 subpage = page - page_to_pfn(page) + pte_pfn(*pvmw.pte);
1435                 address = pvmw.address;
1436
1437                 if (PageHuge(page)) {
1438                         if (huge_pmd_unshare(mm, &address, pvmw.pte)) {
1439                                 /*
1440                                  * huge_pmd_unshare unmapped an entire PMD
1441                                  * page.  There is no way of knowing exactly
1442                                  * which PMDs may be cached for this mm, so
1443                                  * we must flush them all.  start/end were
1444                                  * already adjusted above to cover this range.
1445                                  */
1446                                 flush_cache_range(vma, range.start, range.end);
1447                                 flush_tlb_range(vma, range.start, range.end);
1448                                 mmu_notifier_invalidate_range(mm, range.start,
1449                                                               range.end);
1450
1451                                 /*
1452                                  * The ref count of the PMD page was dropped
1453                                  * which is part of the way map counting
1454                                  * is done for shared PMDs.  Return 'true'
1455                                  * here.  When there is no other sharing,
1456                                  * huge_pmd_unshare returns false and we will
1457                                  * unmap the actual page and drop map count
1458                                  * to zero.
1459                                  */
1460                                 page_vma_mapped_walk_done(&pvmw);
1461                                 break;
1462                         }
1463                 }
1464
1465                 if (IS_ENABLED(CONFIG_MIGRATION) &&
1466                     (flags & TTU_MIGRATION) &&
1467                     is_zone_device_page(page)) {
1468                         swp_entry_t entry;
1469                         pte_t swp_pte;
1470
1471                         pteval = ptep_get_and_clear(mm, pvmw.address, pvmw.pte);
1472
1473                         /*
1474                          * Store the pfn of the page in a special migration
1475                          * pte. do_swap_page() will wait until the migration
1476                          * pte is removed and then restart fault handling.
1477                          */
1478                         entry = make_migration_entry(page, 0);
1479                         swp_pte = swp_entry_to_pte(entry);
1480                         if (pte_soft_dirty(pteval))
1481                                 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1482                         set_pte_at(mm, pvmw.address, pvmw.pte, swp_pte);
1483                         /*
1484                          * No need to invalidate here it will synchronize on
1485                          * against the special swap migration pte.
1486                          *
1487                          * The assignment to subpage above was computed from a
1488                          * swap PTE which results in an invalid pointer.
1489                          * Since only PAGE_SIZE pages can currently be
1490                          * migrated, just set it to page. This will need to be
1491                          * changed when hugepage migrations to device private
1492                          * memory are supported.
1493                          */
1494                         subpage = page;
1495                         goto discard;
1496                 }
1497
1498                 /* Nuke the page table entry. */
1499                 flush_cache_page(vma, address, pte_pfn(*pvmw.pte));
1500                 if (should_defer_flush(mm, flags)) {
1501                         /*
1502                          * We clear the PTE but do not flush so potentially
1503                          * a remote CPU could still be writing to the page.
1504                          * If the entry was previously clean then the
1505                          * architecture must guarantee that a clear->dirty
1506                          * transition on a cached TLB entry is written through
1507                          * and traps if the PTE is unmapped.
1508                          */
1509                         pteval = ptep_get_and_clear(mm, address, pvmw.pte);
1510
1511                         set_tlb_ubc_flush_pending(mm, pte_dirty(pteval));
1512                 } else {
1513                         pteval = ptep_clear_flush(vma, address, pvmw.pte);
1514                 }
1515
1516                 /* Move the dirty bit to the page. Now the pte is gone. */
1517                 if (pte_dirty(pteval))
1518                         set_page_dirty(page);
1519
1520                 /* Update high watermark before we lower rss */
1521                 update_hiwater_rss(mm);
1522
1523                 if (PageHWPoison(page) && !(flags & TTU_IGNORE_HWPOISON)) {
1524                         pteval = swp_entry_to_pte(make_hwpoison_entry(subpage));
1525                         if (PageHuge(page)) {
1526                                 hugetlb_count_sub(compound_nr(page), mm);
1527                                 set_huge_swap_pte_at(mm, address,
1528                                                      pvmw.pte, pteval,
1529                                                      vma_mmu_pagesize(vma));
1530                         } else {
1531                                 dec_mm_counter(mm, mm_counter(page));
1532                                 set_pte_at(mm, address, pvmw.pte, pteval);
1533                         }
1534
1535                 } else if (pte_unused(pteval) && !userfaultfd_armed(vma)) {
1536                         /*
1537                          * The guest indicated that the page content is of no
1538                          * interest anymore. Simply discard the pte, vmscan
1539                          * will take care of the rest.
1540                          * A future reference will then fault in a new zero
1541                          * page. When userfaultfd is active, we must not drop
1542                          * this page though, as its main user (postcopy
1543                          * migration) will not expect userfaults on already
1544                          * copied pages.
1545                          */
1546                         dec_mm_counter(mm, mm_counter(page));
1547                         /* We have to invalidate as we cleared the pte */
1548                         mmu_notifier_invalidate_range(mm, address,
1549                                                       address + PAGE_SIZE);
1550                 } else if (IS_ENABLED(CONFIG_MIGRATION) &&
1551                                 (flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))) {
1552                         swp_entry_t entry;
1553                         pte_t swp_pte;
1554
1555                         if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1556                                 set_pte_at(mm, address, pvmw.pte, pteval);
1557                                 ret = false;
1558                                 page_vma_mapped_walk_done(&pvmw);
1559                                 break;
1560                         }
1561
1562                         /*
1563                          * Store the pfn of the page in a special migration
1564                          * pte. do_swap_page() will wait until the migration
1565                          * pte is removed and then restart fault handling.
1566                          */
1567                         entry = make_migration_entry(subpage,
1568                                         pte_write(pteval));
1569                         swp_pte = swp_entry_to_pte(entry);
1570                         if (pte_soft_dirty(pteval))
1571                                 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1572                         set_pte_at(mm, address, pvmw.pte, swp_pte);
1573                         /*
1574                          * No need to invalidate here it will synchronize on
1575                          * against the special swap migration pte.
1576                          */
1577                 } else if (PageAnon(page)) {
1578                         swp_entry_t entry = { .val = page_private(subpage) };
1579                         pte_t swp_pte;
1580                         /*
1581                          * Store the swap location in the pte.
1582                          * See handle_pte_fault() ...
1583                          */
1584                         if (unlikely(PageSwapBacked(page) != PageSwapCache(page))) {
1585                                 WARN_ON_ONCE(1);
1586                                 ret = false;
1587                                 /* We have to invalidate as we cleared the pte */
1588                                 mmu_notifier_invalidate_range(mm, address,
1589                                                         address + PAGE_SIZE);
1590                                 page_vma_mapped_walk_done(&pvmw);
1591                                 break;
1592                         }
1593
1594                         /* MADV_FREE page check */
1595                         if (!PageSwapBacked(page)) {
1596                                 if (!PageDirty(page)) {
1597                                         /* Invalidate as we cleared the pte */
1598                                         mmu_notifier_invalidate_range(mm,
1599                                                 address, address + PAGE_SIZE);
1600                                         dec_mm_counter(mm, MM_ANONPAGES);
1601                                         goto discard;
1602                                 }
1603
1604                                 /*
1605                                  * If the page was redirtied, it cannot be
1606                                  * discarded. Remap the page to page table.
1607                                  */
1608                                 set_pte_at(mm, address, pvmw.pte, pteval);
1609                                 SetPageSwapBacked(page);
1610                                 ret = false;
1611                                 page_vma_mapped_walk_done(&pvmw);
1612                                 break;
1613                         }
1614
1615                         if (swap_duplicate(entry) < 0) {
1616                                 set_pte_at(mm, address, pvmw.pte, pteval);
1617                                 ret = false;
1618                                 page_vma_mapped_walk_done(&pvmw);
1619                                 break;
1620                         }
1621                         if (arch_unmap_one(mm, vma, address, pteval) < 0) {
1622                                 set_pte_at(mm, address, pvmw.pte, pteval);
1623                                 ret = false;
1624                                 page_vma_mapped_walk_done(&pvmw);
1625                                 break;
1626                         }
1627                         if (list_empty(&mm->mmlist)) {
1628                                 spin_lock(&mmlist_lock);
1629                                 if (list_empty(&mm->mmlist))
1630                                         list_add(&mm->mmlist, &init_mm.mmlist);
1631                                 spin_unlock(&mmlist_lock);
1632                         }
1633                         dec_mm_counter(mm, MM_ANONPAGES);
1634                         inc_mm_counter(mm, MM_SWAPENTS);
1635                         swp_pte = swp_entry_to_pte(entry);
1636                         if (pte_soft_dirty(pteval))
1637                                 swp_pte = pte_swp_mksoft_dirty(swp_pte);
1638                         set_pte_at(mm, address, pvmw.pte, swp_pte);
1639                         /* Invalidate as we cleared the pte */
1640                         mmu_notifier_invalidate_range(mm, address,
1641                                                       address + PAGE_SIZE);
1642                 } else {
1643                         /*
1644                          * This is a locked file-backed page, thus it cannot
1645                          * be removed from the page cache and replaced by a new
1646                          * page before mmu_notifier_invalidate_range_end, so no
1647                          * concurrent thread might update its page table to
1648                          * point at new page while a device still is using this
1649                          * page.
1650                          *
1651                          * See Documentation/vm/mmu_notifier.rst
1652                          */
1653                         dec_mm_counter(mm, mm_counter_file(page));
1654                 }
1655 discard:
1656                 /*
1657                  * No need to call mmu_notifier_invalidate_range() it has be
1658                  * done above for all cases requiring it to happen under page
1659                  * table lock before mmu_notifier_invalidate_range_end()
1660                  *
1661                  * See Documentation/vm/mmu_notifier.rst
1662                  */
1663                 page_remove_rmap(subpage, PageHuge(page));
1664                 put_page(page);
1665         }
1666
1667         mmu_notifier_invalidate_range_end(&range);
1668
1669         return ret;
1670 }
1671
1672 bool is_vma_temporary_stack(struct vm_area_struct *vma)
1673 {
1674         int maybe_stack = vma->vm_flags & (VM_GROWSDOWN | VM_GROWSUP);
1675
1676         if (!maybe_stack)
1677                 return false;
1678
1679         if ((vma->vm_flags & VM_STACK_INCOMPLETE_SETUP) ==
1680                                                 VM_STACK_INCOMPLETE_SETUP)
1681                 return true;
1682
1683         return false;
1684 }
1685
1686 static bool invalid_migration_vma(struct vm_area_struct *vma, void *arg)
1687 {
1688         return is_vma_temporary_stack(vma);
1689 }
1690
1691 static int page_mapcount_is_zero(struct page *page)
1692 {
1693         return !total_mapcount(page);
1694 }
1695
1696 /**
1697  * try_to_unmap - try to remove all page table mappings to a page
1698  * @page: the page to get unmapped
1699  * @flags: action and flags
1700  *
1701  * Tries to remove all the page table entries which are mapping this
1702  * page, used in the pageout path.  Caller must hold the page lock.
1703  *
1704  * If unmap is successful, return true. Otherwise, false.
1705  */
1706 bool try_to_unmap(struct page *page, enum ttu_flags flags)
1707 {
1708         struct rmap_walk_control rwc = {
1709                 .rmap_one = try_to_unmap_one,
1710                 .arg = (void *)flags,
1711                 .done = page_mapcount_is_zero,
1712                 .anon_lock = page_lock_anon_vma_read,
1713         };
1714
1715         /*
1716          * During exec, a temporary VMA is setup and later moved.
1717          * The VMA is moved under the anon_vma lock but not the
1718          * page tables leading to a race where migration cannot
1719          * find the migration ptes. Rather than increasing the
1720          * locking requirements of exec(), migration skips
1721          * temporary VMAs until after exec() completes.
1722          */
1723         if ((flags & (TTU_MIGRATION|TTU_SPLIT_FREEZE))
1724             && !PageKsm(page) && PageAnon(page))
1725                 rwc.invalid_vma = invalid_migration_vma;
1726
1727         if (flags & TTU_RMAP_LOCKED)
1728                 rmap_walk_locked(page, &rwc);
1729         else
1730                 rmap_walk(page, &rwc);
1731
1732         return !page_mapcount(page) ? true : false;
1733 }
1734
1735 static int page_not_mapped(struct page *page)
1736 {
1737         return !page_mapped(page);
1738 };
1739
1740 /**
1741  * try_to_munlock - try to munlock a page
1742  * @page: the page to be munlocked
1743  *
1744  * Called from munlock code.  Checks all of the VMAs mapping the page
1745  * to make sure nobody else has this page mlocked. The page will be
1746  * returned with PG_mlocked cleared if no other vmas have it mlocked.
1747  */
1748
1749 void try_to_munlock(struct page *page)
1750 {
1751         struct rmap_walk_control rwc = {
1752                 .rmap_one = try_to_unmap_one,
1753                 .arg = (void *)TTU_MUNLOCK,
1754                 .done = page_not_mapped,
1755                 .anon_lock = page_lock_anon_vma_read,
1756
1757         };
1758
1759         VM_BUG_ON_PAGE(!PageLocked(page) || PageLRU(page), page);
1760         VM_BUG_ON_PAGE(PageCompound(page) && PageDoubleMap(page), page);
1761
1762         rmap_walk(page, &rwc);
1763 }
1764
1765 void __put_anon_vma(struct anon_vma *anon_vma)
1766 {
1767         struct anon_vma *root = anon_vma->root;
1768
1769         anon_vma_free(anon_vma);
1770         if (root != anon_vma && atomic_dec_and_test(&root->refcount))
1771                 anon_vma_free(root);
1772 }
1773
1774 static struct anon_vma *rmap_walk_anon_lock(struct page *page,
1775                                         struct rmap_walk_control *rwc)
1776 {
1777         struct anon_vma *anon_vma;
1778
1779         if (rwc->anon_lock)
1780                 return rwc->anon_lock(page);
1781
1782         /*
1783          * Note: remove_migration_ptes() cannot use page_lock_anon_vma_read()
1784          * because that depends on page_mapped(); but not all its usages
1785          * are holding mmap_sem. Users without mmap_sem are required to
1786          * take a reference count to prevent the anon_vma disappearing
1787          */
1788         anon_vma = page_anon_vma(page);
1789         if (!anon_vma)
1790                 return NULL;
1791
1792         anon_vma_lock_read(anon_vma);
1793         return anon_vma;
1794 }
1795
1796 /*
1797  * rmap_walk_anon - do something to anonymous page using the object-based
1798  * rmap method
1799  * @page: the page to be handled
1800  * @rwc: control variable according to each walk type
1801  *
1802  * Find all the mappings of a page using the mapping pointer and the vma chains
1803  * contained in the anon_vma struct it points to.
1804  *
1805  * When called from try_to_munlock(), the mmap_sem of the mm containing the vma
1806  * where the page was found will be held for write.  So, we won't recheck
1807  * vm_flags for that VMA.  That should be OK, because that vma shouldn't be
1808  * LOCKED.
1809  */
1810 static void rmap_walk_anon(struct page *page, struct rmap_walk_control *rwc,
1811                 bool locked)
1812 {
1813         struct anon_vma *anon_vma;
1814         pgoff_t pgoff_start, pgoff_end;
1815         struct anon_vma_chain *avc;
1816
1817         if (locked) {
1818                 anon_vma = page_anon_vma(page);
1819                 /* anon_vma disappear under us? */
1820                 VM_BUG_ON_PAGE(!anon_vma, page);
1821         } else {
1822                 anon_vma = rmap_walk_anon_lock(page, rwc);
1823         }
1824         if (!anon_vma)
1825                 return;
1826
1827         pgoff_start = page_to_pgoff(page);
1828         pgoff_end = pgoff_start + hpage_nr_pages(page) - 1;
1829         anon_vma_interval_tree_foreach(avc, &anon_vma->rb_root,
1830                         pgoff_start, pgoff_end) {
1831                 struct vm_area_struct *vma = avc->vma;
1832                 unsigned long address = vma_address(page, vma);
1833
1834                 cond_resched();
1835
1836                 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
1837                         continue;
1838
1839                 if (!rwc->rmap_one(page, vma, address, rwc->arg))
1840                         break;
1841                 if (rwc->done && rwc->done(page))
1842                         break;
1843         }
1844
1845         if (!locked)
1846                 anon_vma_unlock_read(anon_vma);
1847 }
1848
1849 /*
1850  * rmap_walk_file - do something to file page using the object-based rmap method
1851  * @page: the page to be handled
1852  * @rwc: control variable according to each walk type
1853  *
1854  * Find all the mappings of a page using the mapping pointer and the vma chains
1855  * contained in the address_space struct it points to.
1856  *
1857  * When called from try_to_munlock(), the mmap_sem of the mm containing the vma
1858  * where the page was found will be held for write.  So, we won't recheck
1859  * vm_flags for that VMA.  That should be OK, because that vma shouldn't be
1860  * LOCKED.
1861  */
1862 static void rmap_walk_file(struct page *page, struct rmap_walk_control *rwc,
1863                 bool locked)
1864 {
1865         struct address_space *mapping = page_mapping(page);
1866         pgoff_t pgoff_start, pgoff_end;
1867         struct vm_area_struct *vma;
1868
1869         /*
1870          * The page lock not only makes sure that page->mapping cannot
1871          * suddenly be NULLified by truncation, it makes sure that the
1872          * structure at mapping cannot be freed and reused yet,
1873          * so we can safely take mapping->i_mmap_rwsem.
1874          */
1875         VM_BUG_ON_PAGE(!PageLocked(page), page);
1876
1877         if (!mapping)
1878                 return;
1879
1880         pgoff_start = page_to_pgoff(page);
1881         pgoff_end = pgoff_start + hpage_nr_pages(page) - 1;
1882         if (!locked)
1883                 i_mmap_lock_read(mapping);
1884         vma_interval_tree_foreach(vma, &mapping->i_mmap,
1885                         pgoff_start, pgoff_end) {
1886                 unsigned long address = vma_address(page, vma);
1887
1888                 cond_resched();
1889
1890                 if (rwc->invalid_vma && rwc->invalid_vma(vma, rwc->arg))
1891                         continue;
1892
1893                 if (!rwc->rmap_one(page, vma, address, rwc->arg))
1894                         goto done;
1895                 if (rwc->done && rwc->done(page))
1896                         goto done;
1897         }
1898
1899 done:
1900         if (!locked)
1901                 i_mmap_unlock_read(mapping);
1902 }
1903
1904 void rmap_walk(struct page *page, struct rmap_walk_control *rwc)
1905 {
1906         if (unlikely(PageKsm(page)))
1907                 rmap_walk_ksm(page, rwc);
1908         else if (PageAnon(page))
1909                 rmap_walk_anon(page, rwc, false);
1910         else
1911                 rmap_walk_file(page, rwc, false);
1912 }
1913
1914 /* Like rmap_walk, but caller holds relevant rmap lock */
1915 void rmap_walk_locked(struct page *page, struct rmap_walk_control *rwc)
1916 {
1917         /* no ksm support for now */
1918         VM_BUG_ON_PAGE(PageKsm(page), page);
1919         if (PageAnon(page))
1920                 rmap_walk_anon(page, rwc, true);
1921         else
1922                 rmap_walk_file(page, rwc, true);
1923 }
1924
1925 #ifdef CONFIG_HUGETLB_PAGE
1926 /*
1927  * The following two functions are for anonymous (private mapped) hugepages.
1928  * Unlike common anonymous pages, anonymous hugepages have no accounting code
1929  * and no lru code, because we handle hugepages differently from common pages.
1930  */
1931 void hugepage_add_anon_rmap(struct page *page,
1932                             struct vm_area_struct *vma, unsigned long address)
1933 {
1934         struct anon_vma *anon_vma = vma->anon_vma;
1935         int first;
1936
1937         BUG_ON(!PageLocked(page));
1938         BUG_ON(!anon_vma);
1939         /* address might be in next vma when migration races vma_adjust */
1940         first = atomic_inc_and_test(compound_mapcount_ptr(page));
1941         if (first)
1942                 __page_set_anon_rmap(page, vma, address, 0);
1943 }
1944
1945 void hugepage_add_new_anon_rmap(struct page *page,
1946                         struct vm_area_struct *vma, unsigned long address)
1947 {
1948         BUG_ON(address < vma->vm_start || address >= vma->vm_end);
1949         atomic_set(compound_mapcount_ptr(page), 0);
1950         __page_set_anon_rmap(page, vma, address, 1);
1951 }
1952 #endif /* CONFIG_HUGETLB_PAGE */