1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
9 * demand-loading started 01.12.91 - seems it is high on the list of
10 * things wanted, and it should be easy to implement. - Linus
14 * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
15 * pages started 02.12.91, seems to work. - Linus.
17 * Tested sharing by executing about 30 /bin/sh: under the old kernel it
18 * would have taken more than the 6M I have free, but it worked well as
21 * Also corrected some "invalidate()"s - I wasn't doing enough of them.
25 * Real VM (paging to/from disk) started 18.12.91. Much more work and
26 * thought has to go into this. Oh, well..
27 * 19.12.91 - works, somewhat. Sometimes I get faults, don't know why.
28 * Found it. Everything seems to work now.
29 * 20.12.91 - Ok, making the swap-device changeable like the root.
33 * 05.04.94 - Multi-page memory management added for v1.1.
34 * Idea by Alex Bligh (alex@cconcepts.co.uk)
36 * 16.07.99 - Support of BIGMEM added by Gerhard Wichert, Siemens AG
37 * (Gerhard.Wichert@pdb.siemens.de)
39 * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
42 #include <linux/kernel_stat.h>
44 #include <linux/sched/mm.h>
45 #include <linux/sched/coredump.h>
46 #include <linux/sched/numa_balancing.h>
47 #include <linux/sched/task.h>
48 #include <linux/hugetlb.h>
49 #include <linux/mman.h>
50 #include <linux/swap.h>
51 #include <linux/highmem.h>
52 #include <linux/pagemap.h>
53 #include <linux/memremap.h>
54 #include <linux/ksm.h>
55 #include <linux/rmap.h>
56 #include <linux/export.h>
57 #include <linux/delayacct.h>
58 #include <linux/init.h>
59 #include <linux/pfn_t.h>
60 #include <linux/writeback.h>
61 #include <linux/memcontrol.h>
62 #include <linux/mmu_notifier.h>
63 #include <linux/swapops.h>
64 #include <linux/elf.h>
65 #include <linux/gfp.h>
66 #include <linux/migrate.h>
67 #include <linux/string.h>
68 #include <linux/debugfs.h>
69 #include <linux/userfaultfd_k.h>
70 #include <linux/dax.h>
71 #include <linux/oom.h>
72 #include <linux/numa.h>
73 #include <linux/perf_event.h>
74 #include <linux/ptrace.h>
75 #include <linux/vmalloc.h>
77 #include <trace/events/kmem.h>
80 #include <asm/mmu_context.h>
81 #include <asm/pgalloc.h>
82 #include <linux/uaccess.h>
84 #include <asm/tlbflush.h>
85 #ifdef CONFIG_FINEGRAINED_THP
86 #include <asm/huge_mm.h>
87 #include <asm/finegrained_thp.h>
89 #include <asm-generic/huge_mm.h>
90 #include <asm-generic/finegrained_thp.h>
93 #include "pgalloc-track.h"
96 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
97 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
100 #ifndef CONFIG_NEED_MULTIPLE_NODES
101 /* use the per-pgdat data instead for discontigmem - mbligh */
102 unsigned long max_mapnr;
103 EXPORT_SYMBOL(max_mapnr);
105 struct page *mem_map;
106 EXPORT_SYMBOL(mem_map);
110 * A number of key systems in x86 including ioremap() rely on the assumption
111 * that high_memory defines the upper bound on direct map memory, then end
112 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and
113 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
117 EXPORT_SYMBOL(high_memory);
120 * Randomize the address space (stacks, mmaps, brk, etc.).
122 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
123 * as ancient (libc5 based) binaries can segfault. )
125 int randomize_va_space __read_mostly =
126 #ifdef CONFIG_COMPAT_BRK
132 #ifndef arch_faults_on_old_pte
133 static inline bool arch_faults_on_old_pte(void)
136 * Those arches which don't have hw access flag feature need to
137 * implement their own helper. By default, "true" means pagefault
138 * will be hit on old pte.
144 static int __init disable_randmaps(char *s)
146 randomize_va_space = 0;
149 __setup("norandmaps", disable_randmaps);
151 unsigned long zero_pfn __read_mostly;
152 EXPORT_SYMBOL(zero_pfn);
154 unsigned long highest_memmap_pfn __read_mostly;
156 atomic_long_t nr_phys_cont_pte_pages;
157 atomic_long_t nr_phys_huge_pmd_pages;
159 unsigned long phys_cont_pte_pages(void)
161 return atomic_long_read(&nr_phys_cont_pte_pages);
164 unsigned long phys_huge_pmd_pages(void)
166 return atomic_long_read(&nr_phys_huge_pmd_pages);
170 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
172 static int __init init_zero_pfn(void)
174 zero_pfn = page_to_pfn(ZERO_PAGE(0));
177 core_initcall(init_zero_pfn);
179 void mm_trace_rss_stat(struct mm_struct *mm, int member, long count)
181 trace_rss_stat(mm, member, count);
184 #if defined(SPLIT_RSS_COUNTING)
186 void sync_mm_rss(struct mm_struct *mm)
190 for (i = 0; i < NR_MM_COUNTERS; i++) {
191 if (current->rss_stat.count[i]) {
192 add_mm_counter(mm, i, current->rss_stat.count[i]);
193 current->rss_stat.count[i] = 0;
196 current->rss_stat.events = 0;
199 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
201 struct task_struct *task = current;
203 if (likely(task->mm == mm))
204 task->rss_stat.count[member] += val;
206 add_mm_counter(mm, member, val);
208 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
209 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
211 /* sync counter once per 64 page faults */
212 #define TASK_RSS_EVENTS_THRESH (64)
213 static void check_sync_rss_stat(struct task_struct *task)
215 if (unlikely(task != current))
217 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
218 sync_mm_rss(task->mm);
220 #else /* SPLIT_RSS_COUNTING */
222 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
223 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
225 static void check_sync_rss_stat(struct task_struct *task)
229 #endif /* SPLIT_RSS_COUNTING */
231 #ifdef CONFIG_FINEGRAINED_THP
232 void thp_print_cont_pte_table(struct mm_struct *mm,
233 unsigned long addr, pte_t *ptep, unsigned long line);
234 #endif /* CONFIG_FINEGRAINED_THP */
237 * Note: this doesn't free the actual pages themselves. That
238 * has been handled earlier when unmapping all the memory regions.
240 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
243 pgtable_t token = pmd_pgtable(*pmd);
245 pte_free_tlb(tlb, token, addr);
246 mm_dec_nr_ptes(tlb->mm);
249 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
250 unsigned long addr, unsigned long end,
251 unsigned long floor, unsigned long ceiling)
258 pmd = pmd_offset(pud, addr);
260 next = pmd_addr_end(addr, end);
261 if (pmd_none_or_clear_bad(pmd))
263 free_pte_range(tlb, pmd, addr);
264 } while (pmd++, addr = next, addr != end);
274 if (end - 1 > ceiling - 1)
277 pmd = pmd_offset(pud, start);
279 pmd_free_tlb(tlb, pmd, start);
280 mm_dec_nr_pmds(tlb->mm);
283 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
284 unsigned long addr, unsigned long end,
285 unsigned long floor, unsigned long ceiling)
292 pud = pud_offset(p4d, addr);
294 next = pud_addr_end(addr, end);
295 if (pud_none_or_clear_bad(pud))
297 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
298 } while (pud++, addr = next, addr != end);
308 if (end - 1 > ceiling - 1)
311 pud = pud_offset(p4d, start);
313 pud_free_tlb(tlb, pud, start);
314 mm_dec_nr_puds(tlb->mm);
317 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
318 unsigned long addr, unsigned long end,
319 unsigned long floor, unsigned long ceiling)
326 p4d = p4d_offset(pgd, addr);
328 next = p4d_addr_end(addr, end);
329 if (p4d_none_or_clear_bad(p4d))
331 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
332 } while (p4d++, addr = next, addr != end);
338 ceiling &= PGDIR_MASK;
342 if (end - 1 > ceiling - 1)
345 p4d = p4d_offset(pgd, start);
347 p4d_free_tlb(tlb, p4d, start);
351 * This function frees user-level page tables of a process.
353 void free_pgd_range(struct mmu_gather *tlb,
354 unsigned long addr, unsigned long end,
355 unsigned long floor, unsigned long ceiling)
361 * The next few lines have given us lots of grief...
363 * Why are we testing PMD* at this top level? Because often
364 * there will be no work to do at all, and we'd prefer not to
365 * go all the way down to the bottom just to discover that.
367 * Why all these "- 1"s? Because 0 represents both the bottom
368 * of the address space and the top of it (using -1 for the
369 * top wouldn't help much: the masks would do the wrong thing).
370 * The rule is that addr 0 and floor 0 refer to the bottom of
371 * the address space, but end 0 and ceiling 0 refer to the top
372 * Comparisons need to use "end - 1" and "ceiling - 1" (though
373 * that end 0 case should be mythical).
375 * Wherever addr is brought up or ceiling brought down, we must
376 * be careful to reject "the opposite 0" before it confuses the
377 * subsequent tests. But what about where end is brought down
378 * by PMD_SIZE below? no, end can't go down to 0 there.
380 * Whereas we round start (addr) and ceiling down, by different
381 * masks at different levels, in order to test whether a table
382 * now has no other vmas using it, so can be freed, we don't
383 * bother to round floor or end up - the tests don't need that.
397 if (end - 1 > ceiling - 1)
402 * We add page table cache pages with PAGE_SIZE,
403 * (see pte_free_tlb()), flush the tlb if we need
405 tlb_change_page_size(tlb, PAGE_SIZE);
406 pgd = pgd_offset(tlb->mm, addr);
408 next = pgd_addr_end(addr, end);
409 if (pgd_none_or_clear_bad(pgd))
411 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
412 } while (pgd++, addr = next, addr != end);
415 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
416 unsigned long floor, unsigned long ceiling)
419 struct vm_area_struct *next = vma->vm_next;
420 unsigned long addr = vma->vm_start;
423 * Hide vma from rmap and truncate_pagecache before freeing
426 unlink_anon_vmas(vma);
427 unlink_file_vma(vma);
429 if (is_vm_hugetlb_page(vma)) {
430 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
431 floor, next ? next->vm_start : ceiling);
434 * Optimization: gather nearby vmas into one call down
436 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
437 && !is_vm_hugetlb_page(next)) {
440 unlink_anon_vmas(vma);
441 unlink_file_vma(vma);
443 free_pgd_range(tlb, addr, vma->vm_end,
444 floor, next ? next->vm_start : ceiling);
450 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
453 pgtable_t new = pte_alloc_one(mm);
458 * Ensure all pte setup (eg. pte page lock and page clearing) are
459 * visible before the pte is made visible to other CPUs by being
460 * put into page tables.
462 * The other side of the story is the pointer chasing in the page
463 * table walking code (when walking the page table without locking;
464 * ie. most of the time). Fortunately, these data accesses consist
465 * of a chain of data-dependent loads, meaning most CPUs (alpha
466 * being the notable exception) will already guarantee loads are
467 * seen in-order. See the alpha page table accessors for the
468 * smp_rmb() barriers in page table walking code.
470 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
472 ptl = pmd_lock(mm, pmd);
473 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
475 pmd_populate(mm, pmd, new);
484 int __pte_alloc_kernel(pmd_t *pmd)
486 pte_t *new = pte_alloc_one_kernel(&init_mm);
490 smp_wmb(); /* See comment in __pte_alloc */
492 spin_lock(&init_mm.page_table_lock);
493 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
494 pmd_populate_kernel(&init_mm, pmd, new);
497 spin_unlock(&init_mm.page_table_lock);
499 pte_free_kernel(&init_mm, new);
503 static inline void init_rss_vec(int *rss)
505 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
508 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
512 if (current->mm == mm)
514 for (i = 0; i < NR_MM_COUNTERS; i++)
516 add_mm_counter(mm, i, rss[i]);
520 * This function is called to print an error when a bad pte
521 * is found. For example, we might have a PFN-mapped pte in
522 * a region that doesn't allow it.
524 * The calling function must still handle the error.
526 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
527 pte_t pte, struct page *page)
529 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
530 p4d_t *p4d = p4d_offset(pgd, addr);
531 pud_t *pud = pud_offset(p4d, addr);
532 pmd_t *pmd = pmd_offset(pud, addr);
533 struct address_space *mapping;
535 static unsigned long resume;
536 static unsigned long nr_shown;
537 static unsigned long nr_unshown;
540 * Allow a burst of 60 reports, then keep quiet for that minute;
541 * or allow a steady drip of one report per second.
543 if (nr_shown == 60) {
544 if (time_before(jiffies, resume)) {
549 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
556 resume = jiffies + 60 * HZ;
558 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
559 index = linear_page_index(vma, addr);
561 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
563 (long long)pte_val(pte), (long long)pmd_val(*pmd));
565 dump_page(page, "bad pte");
566 pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n",
567 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
568 pr_alert("file:%pD fault:%ps mmap:%ps readpage:%ps\n",
570 vma->vm_ops ? vma->vm_ops->fault : NULL,
571 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
572 mapping ? mapping->a_ops->readpage : NULL);
574 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
578 * vm_normal_page -- This function gets the "struct page" associated with a pte.
580 * "Special" mappings do not wish to be associated with a "struct page" (either
581 * it doesn't exist, or it exists but they don't want to touch it). In this
582 * case, NULL is returned here. "Normal" mappings do have a struct page.
584 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
585 * pte bit, in which case this function is trivial. Secondly, an architecture
586 * may not have a spare pte bit, which requires a more complicated scheme,
589 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
590 * special mapping (even if there are underlying and valid "struct pages").
591 * COWed pages of a VM_PFNMAP are always normal.
593 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
594 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
595 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
596 * mapping will always honor the rule
598 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
600 * And for normal mappings this is false.
602 * This restricts such mappings to be a linear translation from virtual address
603 * to pfn. To get around this restriction, we allow arbitrary mappings so long
604 * as the vma is not a COW mapping; in that case, we know that all ptes are
605 * special (because none can have been COWed).
608 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
610 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
611 * page" backing, however the difference is that _all_ pages with a struct
612 * page (that is, those where pfn_valid is true) are refcounted and considered
613 * normal pages by the VM. The disadvantage is that pages are refcounted
614 * (which can be slower and simply not an option for some PFNMAP users). The
615 * advantage is that we don't have to follow the strict linearity rule of
616 * PFNMAP mappings in order to support COWable mappings.
619 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
622 unsigned long pfn = pte_pfn(pte);
624 if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
625 if (likely(!pte_special(pte)))
627 if (vma->vm_ops && vma->vm_ops->find_special_page)
628 return vma->vm_ops->find_special_page(vma, addr);
629 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
631 if (is_zero_pfn(pfn))
636 print_bad_pte(vma, addr, pte, NULL);
640 /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
642 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
643 if (vma->vm_flags & VM_MIXEDMAP) {
649 off = (addr - vma->vm_start) >> PAGE_SHIFT;
650 if (pfn == vma->vm_pgoff + off)
652 if (!is_cow_mapping(vma->vm_flags))
657 if (is_zero_pfn(pfn))
661 if (unlikely(pfn > highest_memmap_pfn)) {
662 print_bad_pte(vma, addr, pte, NULL);
667 * NOTE! We still have PageReserved() pages in the page tables.
668 * eg. VDSO mappings can cause them to exist.
671 return pfn_to_page(pfn);
674 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
675 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
678 unsigned long pfn = pmd_pfn(pmd);
681 * There is no pmd_special() but there may be special pmds, e.g.
682 * in a direct-access (dax) mapping, so let's just replicate the
683 * !CONFIG_ARCH_HAS_PTE_SPECIAL case from vm_normal_page() here.
685 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
686 if (vma->vm_flags & VM_MIXEDMAP) {
692 off = (addr - vma->vm_start) >> PAGE_SHIFT;
693 if (pfn == vma->vm_pgoff + off)
695 if (!is_cow_mapping(vma->vm_flags))
702 if (is_huge_zero_pmd(pmd))
704 if (unlikely(pfn > highest_memmap_pfn))
708 * NOTE! We still have PageReserved() pages in the page tables.
709 * eg. VDSO mappings can cause them to exist.
712 return pfn_to_page(pfn);
717 * copy one vm_area from one task to the other. Assumes the page tables
718 * already present in the new task to be cleared in the whole range
719 * covered by this vma.
723 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
724 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
725 unsigned long addr, int *rss)
727 unsigned long vm_flags = vma->vm_flags;
728 pte_t pte = *src_pte;
730 swp_entry_t entry = pte_to_swp_entry(pte);
732 if (likely(!non_swap_entry(entry))) {
733 if (swap_duplicate(entry) < 0)
736 /* make sure dst_mm is on swapoff's mmlist. */
737 if (unlikely(list_empty(&dst_mm->mmlist))) {
738 spin_lock(&mmlist_lock);
739 if (list_empty(&dst_mm->mmlist))
740 list_add(&dst_mm->mmlist,
742 spin_unlock(&mmlist_lock);
745 } else if (is_migration_entry(entry)) {
746 page = migration_entry_to_page(entry);
748 rss[mm_counter(page)]++;
750 if (is_write_migration_entry(entry) &&
751 is_cow_mapping(vm_flags)) {
753 * COW mappings require pages in both
754 * parent and child to be set to read.
756 make_migration_entry_read(&entry);
757 pte = swp_entry_to_pte(entry);
758 pte = arch_pte_clearhuge(pte);
759 if (pte_swp_soft_dirty(*src_pte))
760 pte = pte_swp_mksoft_dirty(pte);
761 if (pte_swp_uffd_wp(*src_pte))
762 pte = pte_swp_mkuffd_wp(pte);
763 set_pte_at(src_mm, addr, src_pte, pte);
765 } else if (is_device_private_entry(entry)) {
766 page = device_private_entry_to_page(entry);
769 * Update rss count even for unaddressable pages, as
770 * they should treated just like normal pages in this
773 * We will likely want to have some new rss counters
774 * for unaddressable pages, at some point. But for now
775 * keep things as they are.
778 rss[mm_counter(page)]++;
779 page_dup_rmap(page, false);
782 * We do not preserve soft-dirty information, because so
783 * far, checkpoint/restore is the only feature that
784 * requires that. And checkpoint/restore does not work
785 * when a device driver is involved (you cannot easily
786 * save and restore device driver state).
788 if (is_write_device_private_entry(entry) &&
789 is_cow_mapping(vm_flags)) {
790 make_device_private_entry_read(&entry);
791 pte = swp_entry_to_pte(entry);
792 pte = arch_pte_clearhuge(pte);
793 if (pte_swp_uffd_wp(*src_pte))
794 pte = pte_swp_mkuffd_wp(pte);
795 set_pte_at(src_mm, addr, src_pte, pte);
798 pte = arch_pte_clearhuge(pte);
799 set_pte_at(dst_mm, addr, dst_pte, pte);
804 * Copy a present and normal page if necessary.
806 * NOTE! The usual case is that this doesn't need to do
807 * anything, and can just return a positive value. That
808 * will let the caller know that it can just increase
809 * the page refcount and re-use the pte the traditional
812 * But _if_ we need to copy it because it needs to be
813 * pinned in the parent (and the child should get its own
814 * copy rather than just a reference to the same page),
815 * we'll do that here and return zero to let the caller
818 * And if we need a pre-allocated page but don't yet have
819 * one, return a negative error to let the preallocation
820 * code know so that it can do so outside the page table
824 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
825 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
826 struct page **prealloc, pte_t pte, struct page *page)
828 struct mm_struct *src_mm = src_vma->vm_mm;
829 struct page *new_page;
831 if (!is_cow_mapping(src_vma->vm_flags))
835 * What we want to do is to check whether this page may
836 * have been pinned by the parent process. If so,
837 * instead of wrprotect the pte on both sides, we copy
838 * the page immediately so that we'll always guarantee
839 * the pinned page won't be randomly replaced in the
842 * The page pinning checks are just "has this mm ever
843 * seen pinning", along with the (inexact) check of
844 * the page count. That might give false positives for
845 * for pinning, but it will work correctly.
847 if (likely(!atomic_read(&src_mm->has_pinned)))
849 if (likely(!page_maybe_dma_pinned(page)))
852 new_page = *prealloc;
857 * We have a prealloc page, all good! Take it
858 * over and copy the page & arm it.
861 copy_user_highpage(new_page, page, addr, src_vma);
862 __SetPageUptodate(new_page);
863 page_add_new_anon_rmap(new_page, dst_vma, addr, false);
864 lru_cache_add_inactive_or_unevictable(new_page, dst_vma);
865 rss[mm_counter(new_page)]++;
867 /* All done, just insert the new page copy in the child */
868 pte = mk_pte(new_page, dst_vma->vm_page_prot);
869 pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
870 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
875 * Copy one pte. Returns 0 if succeeded, or -EAGAIN if one preallocated page
876 * is required to copy this pte.
879 copy_present_pte(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
880 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
881 struct page **prealloc)
883 struct mm_struct *src_mm = src_vma->vm_mm;
884 unsigned long vm_flags = src_vma->vm_flags;
885 pte_t pte = *src_pte;
888 page = vm_normal_page(src_vma, addr, pte);
892 * when 64KB hugepage map is copied,
893 * clear contiguous bit
895 pte = arch_pte_clearhuge(pte);
897 retval = copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
898 addr, rss, prealloc, pte, page);
903 page_dup_rmap(page, false);
904 rss[mm_counter(page)]++;
908 * If it's a COW mapping, write protect it both
909 * in the parent and the child
911 if (is_cow_mapping(vm_flags) && pte_write(pte)) {
912 ptep_set_wrprotect(src_mm, addr, src_pte);
913 pte = pte_wrprotect(pte);
917 * If it's a shared mapping, mark it clean in
920 if (vm_flags & VM_SHARED)
921 pte = pte_mkclean(pte);
922 pte = pte_mkold(pte);
923 pte = arch_pte_clearhuge(pte);
925 * Make sure the _PAGE_UFFD_WP bit is cleared if the new VMA
926 * does not have the VM_UFFD_WP, which means that the uffd
927 * fork event is not enabled.
929 if (!(vm_flags & VM_UFFD_WP))
930 pte = pte_clear_uffd_wp(pte);
932 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
936 static inline struct page *
937 page_copy_prealloc(struct mm_struct *src_mm, struct vm_area_struct *vma,
940 struct page *new_page;
942 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, addr);
946 if (mem_cgroup_charge(new_page, src_mm, GFP_KERNEL)) {
950 cgroup_throttle_swaprate(new_page, GFP_KERNEL);
956 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
957 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
960 struct mm_struct *dst_mm = dst_vma->vm_mm;
961 struct mm_struct *src_mm = src_vma->vm_mm;
962 pte_t *orig_src_pte, *orig_dst_pte;
963 pte_t *src_pte, *dst_pte;
964 spinlock_t *src_ptl, *dst_ptl;
965 int progress, ret = 0;
966 int rss[NR_MM_COUNTERS];
967 swp_entry_t entry = (swp_entry_t){0};
968 struct page *prealloc = NULL;
974 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
979 src_pte = pte_offset_map(src_pmd, addr);
980 src_ptl = pte_lockptr(src_mm, src_pmd);
981 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
982 orig_src_pte = src_pte;
983 orig_dst_pte = dst_pte;
984 arch_enter_lazy_mmu_mode();
988 * We are holding two locks at this point - either of them
989 * could generate latencies in another task on another CPU.
991 if (progress >= 32) {
993 if (need_resched() ||
994 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
997 if (pte_none(*src_pte)) {
1002 if (unlikely(!pte_present(*src_pte))) {
1003 entry.val = copy_nonpresent_pte(dst_mm, src_mm,
1005 src_vma, addr, rss);
1012 /* copy_present_pte() will clear `*prealloc' if consumed */
1013 ret = copy_present_pte(dst_vma, src_vma, dst_pte, src_pte,
1014 addr, rss, &prealloc);
1016 * If we need a pre-allocated page for this pte, drop the
1017 * locks, allocate, and try again.
1019 if (unlikely(ret == -EAGAIN))
1021 if (unlikely(prealloc)) {
1023 * pre-alloc page cannot be reused by next time so as
1024 * to strictly follow mempolicy (e.g., alloc_page_vma()
1025 * will allocate page according to address). This
1026 * could only happen if one pinned pte changed.
1032 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
1034 arch_leave_lazy_mmu_mode();
1035 spin_unlock(src_ptl);
1036 pte_unmap(orig_src_pte);
1037 add_mm_rss_vec(dst_mm, rss);
1038 pte_unmap_unlock(orig_dst_pte, dst_ptl);
1042 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
1048 WARN_ON_ONCE(ret != -EAGAIN);
1049 prealloc = page_copy_prealloc(src_mm, src_vma, addr);
1052 /* We've captured and resolved the error. Reset, try again. */
1058 if (unlikely(prealloc))
1064 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1065 pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1068 struct mm_struct *dst_mm = dst_vma->vm_mm;
1069 struct mm_struct *src_mm = src_vma->vm_mm;
1070 pmd_t *src_pmd, *dst_pmd;
1073 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1076 src_pmd = pmd_offset(src_pud, addr);
1078 next = pmd_addr_end(addr, end);
1079 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1080 || pmd_devmap(*src_pmd)) {
1082 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
1083 err = copy_huge_pmd(dst_mm, src_mm,
1084 dst_pmd, src_pmd, addr, src_vma);
1091 if (pmd_none_or_clear_bad(src_pmd))
1093 if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
1096 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1101 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1102 p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
1105 struct mm_struct *dst_mm = dst_vma->vm_mm;
1106 struct mm_struct *src_mm = src_vma->vm_mm;
1107 pud_t *src_pud, *dst_pud;
1110 dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1113 src_pud = pud_offset(src_p4d, addr);
1115 next = pud_addr_end(addr, end);
1116 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1119 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
1120 err = copy_huge_pud(dst_mm, src_mm,
1121 dst_pud, src_pud, addr, src_vma);
1128 if (pud_none_or_clear_bad(src_pud))
1130 if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
1133 } while (dst_pud++, src_pud++, addr = next, addr != end);
1138 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1139 pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
1142 struct mm_struct *dst_mm = dst_vma->vm_mm;
1143 p4d_t *src_p4d, *dst_p4d;
1146 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1149 src_p4d = p4d_offset(src_pgd, addr);
1151 next = p4d_addr_end(addr, end);
1152 if (p4d_none_or_clear_bad(src_p4d))
1154 if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
1157 } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1161 #ifdef CONFIG_FINEGRAINED_THP
1162 bool zap_cont_pte_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
1163 pmd_t *pmd, pte_t **ptep, unsigned long *addr,
1164 unsigned long end, struct page *page,
1165 int *rss, spinlock_t *ptl);
1166 #else /* CONFIG_FINEGRAINED_THP */
1167 bool zap_cont_pte_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
1168 pmd_t *pmd, pte_t **ptep, unsigned long *addr,
1169 unsigned long end, struct page *page,
1170 int *rss, spinlock_t *ptl)
1174 #endif /* CONFIG_FINEGRAINED_THP */
1177 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1179 pgd_t *src_pgd, *dst_pgd;
1181 unsigned long addr = src_vma->vm_start;
1182 unsigned long end = src_vma->vm_end;
1183 struct mm_struct *dst_mm = dst_vma->vm_mm;
1184 struct mm_struct *src_mm = src_vma->vm_mm;
1185 struct mmu_notifier_range range;
1190 * Don't copy ptes where a page fault will fill them correctly.
1191 * Fork becomes much lighter when there are big shared or private
1192 * readonly mappings. The tradeoff is that copy_page_range is more
1193 * efficient than faulting.
1195 if (!(src_vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1199 if (is_vm_hugetlb_page(src_vma))
1200 return copy_hugetlb_page_range(dst_mm, src_mm, src_vma);
1202 if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
1204 * We do not free on error cases below as remove_vma
1205 * gets called on error from higher level routine
1207 ret = track_pfn_copy(src_vma);
1213 * We need to invalidate the secondary MMU mappings only when
1214 * there could be a permission downgrade on the ptes of the
1215 * parent mm. And a permission downgrade will only happen if
1216 * is_cow_mapping() returns true.
1218 is_cow = is_cow_mapping(src_vma->vm_flags);
1221 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
1222 0, src_vma, src_mm, addr, end);
1223 mmu_notifier_invalidate_range_start(&range);
1225 * Disabling preemption is not needed for the write side, as
1226 * the read side doesn't spin, but goes to the mmap_lock.
1228 * Use the raw variant of the seqcount_t write API to avoid
1229 * lockdep complaining about preemptibility.
1231 mmap_assert_write_locked(src_mm);
1232 raw_write_seqcount_begin(&src_mm->write_protect_seq);
1236 dst_pgd = pgd_offset(dst_mm, addr);
1237 src_pgd = pgd_offset(src_mm, addr);
1239 next = pgd_addr_end(addr, end);
1240 if (pgd_none_or_clear_bad(src_pgd))
1242 if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
1247 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1250 raw_write_seqcount_end(&src_mm->write_protect_seq);
1251 mmu_notifier_invalidate_range_end(&range);
1256 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1257 struct vm_area_struct *vma, pmd_t *pmd,
1258 unsigned long addr, unsigned long end,
1259 struct zap_details *details)
1261 struct mm_struct *mm = tlb->mm;
1262 int force_flush = 0;
1263 int rss[NR_MM_COUNTERS];
1269 tlb_change_page_size(tlb, PAGE_SIZE);
1272 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1274 flush_tlb_batched_pending(mm);
1275 arch_enter_lazy_mmu_mode();
1278 if (pte_none(ptent))
1284 if (pte_present(ptent)) {
1287 page = vm_normal_page(vma, addr, ptent);
1288 if (unlikely(details) && page) {
1290 * unmap_shared_mapping_pages() wants to
1291 * invalidate cache without truncating:
1292 * unmap shared but keep private pages.
1294 if (details->check_mapping &&
1295 details->check_mapping != page_rmapping(page))
1298 #ifdef CONFIG_FINEGRAINED_THP
1299 if (page && pte_cont(ptent) && PageTransHuge(compound_head(page))) {
1300 if (zap_cont_pte_range(tlb, vma, pmd, &pte,
1301 &addr, end, page, rss, ptl)) {
1305 } else if (pte_cont(ptent))
1306 atomic_long_dec(&nr_phys_cont_pte_pages);
1307 #endif /* CONFIG_FINEGRAINED_THP */
1308 ptent = ptep_get_and_clear_full(mm, addr, pte,
1310 tlb_remove_tlb_entry(tlb, pte, addr);
1311 if (unlikely(!page))
1314 if (!PageAnon(page)) {
1315 if (pte_dirty(ptent)) {
1317 set_page_dirty(page);
1319 if (pte_young(ptent) &&
1320 likely(!(vma->vm_flags & VM_SEQ_READ)))
1321 mark_page_accessed(page);
1323 rss[mm_counter(page)]--;
1324 page_remove_rmap(page, false);
1325 if (unlikely(page_mapcount(page) < 0))
1326 print_bad_pte(vma, addr, ptent, page);
1327 if (unlikely(__tlb_remove_page(tlb, page))) {
1335 entry = pte_to_swp_entry(ptent);
1336 if (is_device_private_entry(entry)) {
1337 struct page *page = device_private_entry_to_page(entry);
1339 if (unlikely(details && details->check_mapping)) {
1341 * unmap_shared_mapping_pages() wants to
1342 * invalidate cache without truncating:
1343 * unmap shared but keep private pages.
1345 if (details->check_mapping !=
1346 page_rmapping(page))
1350 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1351 rss[mm_counter(page)]--;
1352 page_remove_rmap(page, false);
1357 /* If details->check_mapping, we leave swap entries. */
1358 if (unlikely(details))
1361 if (!non_swap_entry(entry))
1363 else if (is_migration_entry(entry)) {
1366 page = migration_entry_to_page(entry);
1367 rss[mm_counter(page)]--;
1369 if (unlikely(!free_swap_and_cache(entry)))
1370 print_bad_pte(vma, addr, ptent, NULL);
1371 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1372 } while (pte++, addr += PAGE_SIZE, addr != end);
1374 add_mm_rss_vec(mm, rss);
1375 arch_leave_lazy_mmu_mode();
1377 /* Do the actual TLB flush before dropping ptl */
1379 tlb_flush_mmu_tlbonly(tlb);
1380 pte_unmap_unlock(start_pte, ptl);
1383 * If we forced a TLB flush (either due to running out of
1384 * batch buffers or because we needed to flush dirty TLB
1385 * entries before releasing the ptl), free the batched
1386 * memory too. Restart if we didn't do everything.
1401 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1402 struct vm_area_struct *vma, pud_t *pud,
1403 unsigned long addr, unsigned long end,
1404 struct zap_details *details)
1409 pmd = pmd_offset(pud, addr);
1411 next = pmd_addr_end(addr, end);
1412 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1413 if (next - addr != HPAGE_PMD_SIZE)
1414 __split_huge_pmd(vma, pmd, addr, false, NULL);
1415 else if (zap_huge_pmd(tlb, vma, pmd, addr))
1420 * Here there can be other concurrent MADV_DONTNEED or
1421 * trans huge page faults running, and if the pmd is
1422 * none or trans huge it can change under us. This is
1423 * because MADV_DONTNEED holds the mmap_lock in read
1426 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1428 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1431 } while (pmd++, addr = next, addr != end);
1436 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1437 struct vm_area_struct *vma, p4d_t *p4d,
1438 unsigned long addr, unsigned long end,
1439 struct zap_details *details)
1444 pud = pud_offset(p4d, addr);
1446 next = pud_addr_end(addr, end);
1447 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1448 if (next - addr != HPAGE_PUD_SIZE) {
1449 mmap_assert_locked(tlb->mm);
1450 split_huge_pud(vma, pud, addr);
1451 } else if (zap_huge_pud(tlb, vma, pud, addr))
1455 if (pud_none_or_clear_bad(pud))
1457 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1460 } while (pud++, addr = next, addr != end);
1465 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1466 struct vm_area_struct *vma, pgd_t *pgd,
1467 unsigned long addr, unsigned long end,
1468 struct zap_details *details)
1473 p4d = p4d_offset(pgd, addr);
1475 next = p4d_addr_end(addr, end);
1476 if (p4d_none_or_clear_bad(p4d))
1478 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1479 } while (p4d++, addr = next, addr != end);
1484 void unmap_page_range(struct mmu_gather *tlb,
1485 struct vm_area_struct *vma,
1486 unsigned long addr, unsigned long end,
1487 struct zap_details *details)
1492 BUG_ON(addr >= end);
1493 tlb_start_vma(tlb, vma);
1494 pgd = pgd_offset(vma->vm_mm, addr);
1496 next = pgd_addr_end(addr, end);
1497 if (pgd_none_or_clear_bad(pgd))
1499 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1500 } while (pgd++, addr = next, addr != end);
1501 tlb_end_vma(tlb, vma);
1505 static void unmap_single_vma(struct mmu_gather *tlb,
1506 struct vm_area_struct *vma, unsigned long start_addr,
1507 unsigned long end_addr,
1508 struct zap_details *details)
1510 unsigned long start = max(vma->vm_start, start_addr);
1513 if (start >= vma->vm_end)
1515 end = min(vma->vm_end, end_addr);
1516 if (end <= vma->vm_start)
1520 uprobe_munmap(vma, start, end);
1522 if (unlikely(vma->vm_flags & VM_PFNMAP))
1523 untrack_pfn(vma, 0, 0);
1526 if (unlikely(is_vm_hugetlb_page(vma))) {
1528 * It is undesirable to test vma->vm_file as it
1529 * should be non-null for valid hugetlb area.
1530 * However, vm_file will be NULL in the error
1531 * cleanup path of mmap_region. When
1532 * hugetlbfs ->mmap method fails,
1533 * mmap_region() nullifies vma->vm_file
1534 * before calling this function to clean up.
1535 * Since no pte has actually been setup, it is
1536 * safe to do nothing in this case.
1539 i_mmap_lock_write(vma->vm_file->f_mapping);
1540 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1541 i_mmap_unlock_write(vma->vm_file->f_mapping);
1544 unmap_page_range(tlb, vma, start, end, details);
1549 * unmap_vmas - unmap a range of memory covered by a list of vma's
1550 * @tlb: address of the caller's struct mmu_gather
1551 * @vma: the starting vma
1552 * @start_addr: virtual address at which to start unmapping
1553 * @end_addr: virtual address at which to end unmapping
1555 * Unmap all pages in the vma list.
1557 * Only addresses between `start' and `end' will be unmapped.
1559 * The VMA list must be sorted in ascending virtual address order.
1561 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1562 * range after unmap_vmas() returns. So the only responsibility here is to
1563 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1564 * drops the lock and schedules.
1566 void unmap_vmas(struct mmu_gather *tlb,
1567 struct vm_area_struct *vma, unsigned long start_addr,
1568 unsigned long end_addr)
1570 struct mmu_notifier_range range;
1572 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
1573 start_addr, end_addr);
1574 mmu_notifier_invalidate_range_start(&range);
1575 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1576 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1577 mmu_notifier_invalidate_range_end(&range);
1581 * zap_page_range - remove user pages in a given range
1582 * @vma: vm_area_struct holding the applicable pages
1583 * @start: starting address of pages to zap
1584 * @size: number of bytes to zap
1586 * Caller must protect the VMA list
1588 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1591 struct mmu_notifier_range range;
1592 struct mmu_gather tlb;
1595 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1596 start, start + size);
1597 tlb_gather_mmu(&tlb, vma->vm_mm, start, range.end);
1598 update_hiwater_rss(vma->vm_mm);
1599 mmu_notifier_invalidate_range_start(&range);
1600 for ( ; vma && vma->vm_start < range.end; vma = vma->vm_next)
1601 unmap_single_vma(&tlb, vma, start, range.end, NULL);
1602 mmu_notifier_invalidate_range_end(&range);
1603 tlb_finish_mmu(&tlb, start, range.end);
1607 * zap_page_range_single - remove user pages in a given range
1608 * @vma: vm_area_struct holding the applicable pages
1609 * @address: starting address of pages to zap
1610 * @size: number of bytes to zap
1611 * @details: details of shared cache invalidation
1613 * The range must fit into one VMA.
1615 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1616 unsigned long size, struct zap_details *details)
1618 struct mmu_notifier_range range;
1619 struct mmu_gather tlb;
1622 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1623 address, address + size);
1624 tlb_gather_mmu(&tlb, vma->vm_mm, address, range.end);
1625 update_hiwater_rss(vma->vm_mm);
1626 mmu_notifier_invalidate_range_start(&range);
1627 unmap_single_vma(&tlb, vma, address, range.end, details);
1628 mmu_notifier_invalidate_range_end(&range);
1629 tlb_finish_mmu(&tlb, address, range.end);
1633 * zap_vma_ptes - remove ptes mapping the vma
1634 * @vma: vm_area_struct holding ptes to be zapped
1635 * @address: starting address of pages to zap
1636 * @size: number of bytes to zap
1638 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1640 * The entire address range must be fully contained within the vma.
1643 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1646 if (address < vma->vm_start || address + size > vma->vm_end ||
1647 !(vma->vm_flags & VM_PFNMAP))
1650 zap_page_range_single(vma, address, size, NULL);
1652 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1654 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
1661 pgd = pgd_offset(mm, addr);
1662 p4d = p4d_alloc(mm, pgd, addr);
1665 pud = pud_alloc(mm, p4d, addr);
1668 pmd = pmd_alloc(mm, pud, addr);
1672 VM_BUG_ON(pmd_trans_huge(*pmd));
1676 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1679 pmd_t *pmd = walk_to_pmd(mm, addr);
1683 return pte_alloc_map_lock(mm, pmd, addr, ptl);
1686 static int validate_page_before_insert(struct page *page)
1688 if (PageAnon(page) || PageSlab(page) || page_has_type(page))
1690 flush_dcache_page(page);
1694 static int insert_page_into_pte_locked(struct mm_struct *mm, pte_t *pte,
1695 unsigned long addr, struct page *page, pgprot_t prot)
1697 if (!pte_none(*pte))
1699 /* Ok, finally just insert the thing.. */
1701 inc_mm_counter_fast(mm, mm_counter_file(page));
1702 page_add_file_rmap(page, false);
1703 set_pte_at(mm, addr, pte, mk_pte(page, prot));
1708 * This is the old fallback for page remapping.
1710 * For historical reasons, it only allows reserved pages. Only
1711 * old drivers should use this, and they needed to mark their
1712 * pages reserved for the old functions anyway.
1714 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1715 struct page *page, pgprot_t prot)
1717 struct mm_struct *mm = vma->vm_mm;
1722 retval = validate_page_before_insert(page);
1726 pte = get_locked_pte(mm, addr, &ptl);
1729 retval = insert_page_into_pte_locked(mm, pte, addr, page, prot);
1730 pte_unmap_unlock(pte, ptl);
1736 static int insert_page_in_batch_locked(struct mm_struct *mm, pte_t *pte,
1737 unsigned long addr, struct page *page, pgprot_t prot)
1741 if (!page_count(page))
1743 err = validate_page_before_insert(page);
1746 return insert_page_into_pte_locked(mm, pte, addr, page, prot);
1749 /* insert_pages() amortizes the cost of spinlock operations
1750 * when inserting pages in a loop. Arch *must* define pte_index.
1752 static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
1753 struct page **pages, unsigned long *num, pgprot_t prot)
1756 pte_t *start_pte, *pte;
1757 spinlock_t *pte_lock;
1758 struct mm_struct *const mm = vma->vm_mm;
1759 unsigned long curr_page_idx = 0;
1760 unsigned long remaining_pages_total = *num;
1761 unsigned long pages_to_write_in_pmd;
1765 pmd = walk_to_pmd(mm, addr);
1769 pages_to_write_in_pmd = min_t(unsigned long,
1770 remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
1772 /* Allocate the PTE if necessary; takes PMD lock once only. */
1774 if (pte_alloc(mm, pmd))
1777 while (pages_to_write_in_pmd) {
1779 const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
1781 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
1782 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
1783 int err = insert_page_in_batch_locked(mm, pte,
1784 addr, pages[curr_page_idx], prot);
1785 if (unlikely(err)) {
1786 pte_unmap_unlock(start_pte, pte_lock);
1788 remaining_pages_total -= pte_idx;
1794 pte_unmap_unlock(start_pte, pte_lock);
1795 pages_to_write_in_pmd -= batch_size;
1796 remaining_pages_total -= batch_size;
1798 if (remaining_pages_total)
1802 *num = remaining_pages_total;
1805 #endif /* ifdef pte_index */
1808 * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
1809 * @vma: user vma to map to
1810 * @addr: target start user address of these pages
1811 * @pages: source kernel pages
1812 * @num: in: number of pages to map. out: number of pages that were *not*
1813 * mapped. (0 means all pages were successfully mapped).
1815 * Preferred over vm_insert_page() when inserting multiple pages.
1817 * In case of error, we may have mapped a subset of the provided
1818 * pages. It is the caller's responsibility to account for this case.
1820 * The same restrictions apply as in vm_insert_page().
1822 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
1823 struct page **pages, unsigned long *num)
1826 const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
1828 if (addr < vma->vm_start || end_addr >= vma->vm_end)
1830 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1831 BUG_ON(mmap_read_trylock(vma->vm_mm));
1832 BUG_ON(vma->vm_flags & VM_PFNMAP);
1833 vma->vm_flags |= VM_MIXEDMAP;
1835 /* Defer page refcount checking till we're about to map that page. */
1836 return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
1838 unsigned long idx = 0, pgcount = *num;
1841 for (; idx < pgcount; ++idx) {
1842 err = vm_insert_page(vma, addr + (PAGE_SIZE * idx), pages[idx]);
1846 *num = pgcount - idx;
1848 #endif /* ifdef pte_index */
1850 EXPORT_SYMBOL(vm_insert_pages);
1853 * vm_insert_page - insert single page into user vma
1854 * @vma: user vma to map to
1855 * @addr: target user address of this page
1856 * @page: source kernel page
1858 * This allows drivers to insert individual pages they've allocated
1861 * The page has to be a nice clean _individual_ kernel allocation.
1862 * If you allocate a compound page, you need to have marked it as
1863 * such (__GFP_COMP), or manually just split the page up yourself
1864 * (see split_page()).
1866 * NOTE! Traditionally this was done with "remap_pfn_range()" which
1867 * took an arbitrary page protection parameter. This doesn't allow
1868 * that. Your vma protection will have to be set up correctly, which
1869 * means that if you want a shared writable mapping, you'd better
1870 * ask for a shared writable mapping!
1872 * The page does not need to be reserved.
1874 * Usually this function is called from f_op->mmap() handler
1875 * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
1876 * Caller must set VM_MIXEDMAP on vma if it wants to call this
1877 * function from other places, for example from page-fault handler.
1879 * Return: %0 on success, negative error code otherwise.
1881 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1884 if (addr < vma->vm_start || addr >= vma->vm_end)
1886 if (!page_count(page))
1888 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1889 BUG_ON(mmap_read_trylock(vma->vm_mm));
1890 BUG_ON(vma->vm_flags & VM_PFNMAP);
1891 vma->vm_flags |= VM_MIXEDMAP;
1893 return insert_page(vma, addr, page, vma->vm_page_prot);
1895 EXPORT_SYMBOL(vm_insert_page);
1898 * __vm_map_pages - maps range of kernel pages into user vma
1899 * @vma: user vma to map to
1900 * @pages: pointer to array of source kernel pages
1901 * @num: number of pages in page array
1902 * @offset: user's requested vm_pgoff
1904 * This allows drivers to map range of kernel pages into a user vma.
1906 * Return: 0 on success and error code otherwise.
1908 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
1909 unsigned long num, unsigned long offset)
1911 unsigned long count = vma_pages(vma);
1912 unsigned long uaddr = vma->vm_start;
1915 /* Fail if the user requested offset is beyond the end of the object */
1919 /* Fail if the user requested size exceeds available object size */
1920 if (count > num - offset)
1923 for (i = 0; i < count; i++) {
1924 ret = vm_insert_page(vma, uaddr, pages[offset + i]);
1934 * vm_map_pages - maps range of kernel pages starts with non zero offset
1935 * @vma: user vma to map to
1936 * @pages: pointer to array of source kernel pages
1937 * @num: number of pages in page array
1939 * Maps an object consisting of @num pages, catering for the user's
1940 * requested vm_pgoff
1942 * If we fail to insert any page into the vma, the function will return
1943 * immediately leaving any previously inserted pages present. Callers
1944 * from the mmap handler may immediately return the error as their caller
1945 * will destroy the vma, removing any successfully inserted pages. Other
1946 * callers should make their own arrangements for calling unmap_region().
1948 * Context: Process context. Called by mmap handlers.
1949 * Return: 0 on success and error code otherwise.
1951 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
1954 return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
1956 EXPORT_SYMBOL(vm_map_pages);
1959 * vm_map_pages_zero - map range of kernel pages starts with zero offset
1960 * @vma: user vma to map to
1961 * @pages: pointer to array of source kernel pages
1962 * @num: number of pages in page array
1964 * Similar to vm_map_pages(), except that it explicitly sets the offset
1965 * to 0. This function is intended for the drivers that did not consider
1968 * Context: Process context. Called by mmap handlers.
1969 * Return: 0 on success and error code otherwise.
1971 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
1974 return __vm_map_pages(vma, pages, num, 0);
1976 EXPORT_SYMBOL(vm_map_pages_zero);
1978 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1979 pfn_t pfn, pgprot_t prot, bool mkwrite)
1981 struct mm_struct *mm = vma->vm_mm;
1985 pte = get_locked_pte(mm, addr, &ptl);
1987 return VM_FAULT_OOM;
1988 if (!pte_none(*pte)) {
1991 * For read faults on private mappings the PFN passed
1992 * in may not match the PFN we have mapped if the
1993 * mapped PFN is a writeable COW page. In the mkwrite
1994 * case we are creating a writable PTE for a shared
1995 * mapping and we expect the PFNs to match. If they
1996 * don't match, we are likely racing with block
1997 * allocation and mapping invalidation so just skip the
2000 if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
2001 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
2004 entry = pte_mkyoung(*pte);
2005 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2006 if (ptep_set_access_flags(vma, addr, pte, entry, 1))
2007 update_mmu_cache(vma, addr, pte);
2012 /* Ok, finally just insert the thing.. */
2013 if (pfn_t_devmap(pfn))
2014 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
2016 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
2019 entry = pte_mkyoung(entry);
2020 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2023 set_pte_at(mm, addr, pte, entry);
2024 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2027 pte_unmap_unlock(pte, ptl);
2028 return VM_FAULT_NOPAGE;
2032 * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
2033 * @vma: user vma to map to
2034 * @addr: target user address of this page
2035 * @pfn: source kernel pfn
2036 * @pgprot: pgprot flags for the inserted page
2038 * This is exactly like vmf_insert_pfn(), except that it allows drivers
2039 * to override pgprot on a per-page basis.
2041 * This only makes sense for IO mappings, and it makes no sense for
2042 * COW mappings. In general, using multiple vmas is preferable;
2043 * vmf_insert_pfn_prot should only be used if using multiple VMAs is
2046 * See vmf_insert_mixed_prot() for a discussion of the implication of using
2047 * a value of @pgprot different from that of @vma->vm_page_prot.
2049 * Context: Process context. May allocate using %GFP_KERNEL.
2050 * Return: vm_fault_t value.
2052 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
2053 unsigned long pfn, pgprot_t pgprot)
2056 * Technically, architectures with pte_special can avoid all these
2057 * restrictions (same for remap_pfn_range). However we would like
2058 * consistency in testing and feature parity among all, so we should
2059 * try to keep these invariants in place for everybody.
2061 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2062 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2063 (VM_PFNMAP|VM_MIXEDMAP));
2064 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2065 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2067 if (addr < vma->vm_start || addr >= vma->vm_end)
2068 return VM_FAULT_SIGBUS;
2070 if (!pfn_modify_allowed(pfn, pgprot))
2071 return VM_FAULT_SIGBUS;
2073 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
2075 return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
2078 EXPORT_SYMBOL(vmf_insert_pfn_prot);
2081 * vmf_insert_pfn - insert single pfn into user vma
2082 * @vma: user vma to map to
2083 * @addr: target user address of this page
2084 * @pfn: source kernel pfn
2086 * Similar to vm_insert_page, this allows drivers to insert individual pages
2087 * they've allocated into a user vma. Same comments apply.
2089 * This function should only be called from a vm_ops->fault handler, and
2090 * in that case the handler should return the result of this function.
2092 * vma cannot be a COW mapping.
2094 * As this is called only for pages that do not currently exist, we
2095 * do not need to flush old virtual caches or the TLB.
2097 * Context: Process context. May allocate using %GFP_KERNEL.
2098 * Return: vm_fault_t value.
2100 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2103 return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
2105 EXPORT_SYMBOL(vmf_insert_pfn);
2107 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn)
2109 /* these checks mirror the abort conditions in vm_normal_page */
2110 if (vma->vm_flags & VM_MIXEDMAP)
2112 if (pfn_t_devmap(pfn))
2114 if (pfn_t_special(pfn))
2116 if (is_zero_pfn(pfn_t_to_pfn(pfn)))
2121 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
2122 unsigned long addr, pfn_t pfn, pgprot_t pgprot,
2127 BUG_ON(!vm_mixed_ok(vma, pfn));
2129 if (addr < vma->vm_start || addr >= vma->vm_end)
2130 return VM_FAULT_SIGBUS;
2132 track_pfn_insert(vma, &pgprot, pfn);
2134 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
2135 return VM_FAULT_SIGBUS;
2138 * If we don't have pte special, then we have to use the pfn_valid()
2139 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2140 * refcount the page if pfn_valid is true (hence insert_page rather
2141 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
2142 * without pte special, it would there be refcounted as a normal page.
2144 if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
2145 !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
2149 * At this point we are committed to insert_page()
2150 * regardless of whether the caller specified flags that
2151 * result in pfn_t_has_page() == false.
2153 page = pfn_to_page(pfn_t_to_pfn(pfn));
2154 err = insert_page(vma, addr, page, pgprot);
2156 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2160 return VM_FAULT_OOM;
2161 if (err < 0 && err != -EBUSY)
2162 return VM_FAULT_SIGBUS;
2164 return VM_FAULT_NOPAGE;
2168 * vmf_insert_mixed_prot - insert single pfn into user vma with specified pgprot
2169 * @vma: user vma to map to
2170 * @addr: target user address of this page
2171 * @pfn: source kernel pfn
2172 * @pgprot: pgprot flags for the inserted page
2174 * This is exactly like vmf_insert_mixed(), except that it allows drivers
2175 * to override pgprot on a per-page basis.
2177 * Typically this function should be used by drivers to set caching- and
2178 * encryption bits different than those of @vma->vm_page_prot, because
2179 * the caching- or encryption mode may not be known at mmap() time.
2180 * This is ok as long as @vma->vm_page_prot is not used by the core vm
2181 * to set caching and encryption bits for those vmas (except for COW pages).
2182 * This is ensured by core vm only modifying these page table entries using
2183 * functions that don't touch caching- or encryption bits, using pte_modify()
2184 * if needed. (See for example mprotect()).
2185 * Also when new page-table entries are created, this is only done using the
2186 * fault() callback, and never using the value of vma->vm_page_prot,
2187 * except for page-table entries that point to anonymous pages as the result
2190 * Context: Process context. May allocate using %GFP_KERNEL.
2191 * Return: vm_fault_t value.
2193 vm_fault_t vmf_insert_mixed_prot(struct vm_area_struct *vma, unsigned long addr,
2194 pfn_t pfn, pgprot_t pgprot)
2196 return __vm_insert_mixed(vma, addr, pfn, pgprot, false);
2198 EXPORT_SYMBOL(vmf_insert_mixed_prot);
2200 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2203 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, false);
2205 EXPORT_SYMBOL(vmf_insert_mixed);
2208 * If the insertion of PTE failed because someone else already added a
2209 * different entry in the mean time, we treat that as success as we assume
2210 * the same entry was actually inserted.
2212 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2213 unsigned long addr, pfn_t pfn)
2215 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, true);
2217 EXPORT_SYMBOL(vmf_insert_mixed_mkwrite);
2221 * maps a range of physical memory into the requested pages. the old
2222 * mappings are removed. any references to nonexistent pages results
2223 * in null mappings (currently treated as "copy-on-access")
2225 #ifdef CONFIG_FINEGRAINED_THP
2226 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2227 unsigned long addr, unsigned long end,
2228 unsigned long pfn, pgprot_t prot)
2230 return arch_remap_pte_range(mm, pmd, addr, end, pfn, prot);
2232 #else /* CONFIG_FINEGRAINED_THP */
2233 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2234 unsigned long addr, unsigned long end,
2235 unsigned long pfn, pgprot_t prot)
2237 pte_t *pte, *mapped_pte;
2241 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2244 arch_enter_lazy_mmu_mode();
2246 BUG_ON(!pte_none(*pte));
2247 if (!pfn_modify_allowed(pfn, prot)) {
2252 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2256 } while (addr != end);
2257 arch_leave_lazy_mmu_mode();
2258 pte_unmap_unlock(mapped_pte, ptl);
2261 #endif /* CONFIG_FINEGRAINED_THP */
2263 static int remap_try_huge_pmd(struct mm_struct *mm, pmd_t *pmd, unsigned long addr,
2264 unsigned long end, unsigned long pfn,
2267 phys_addr_t phys_addr = __pfn_to_phys(pfn);
2271 if ((end - addr) != PMD_SIZE)
2274 if (!IS_ALIGNED(addr, PMD_SIZE))
2277 if (!IS_ALIGNED(phys_addr, PMD_SIZE))
2280 /* fixme - is this correct? */
2281 if (pmd_present(*pmd) && !pmd_free_pte_page(pmd, addr)) {
2282 pr_info("%s %d - freed pmd page??\n", __func__, __LINE__);
2286 ptl = pmd_lock(mm, pmd);
2287 ret = pmd_set_huge(pmd, phys_addr, prot);
2290 atomic_long_inc(&nr_phys_huge_pmd_pages);
2295 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2296 unsigned long addr, unsigned long end,
2297 unsigned long pfn, pgprot_t prot)
2303 pfn -= addr >> PAGE_SHIFT;
2304 pmd = pmd_alloc(mm, pud, addr);
2307 VM_BUG_ON(pmd_trans_huge(*pmd));
2309 next = pmd_addr_end(addr, end);
2311 if (remap_try_huge_pmd(mm, pmd, addr, next,
2312 pfn + (addr >> PAGE_SHIFT), prot))
2315 err = remap_pte_range(mm, pmd, addr, next,
2316 pfn + (addr >> PAGE_SHIFT), prot);
2319 } while (pmd++, addr = next, addr != end);
2323 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2324 unsigned long addr, unsigned long end,
2325 unsigned long pfn, pgprot_t prot)
2331 pfn -= addr >> PAGE_SHIFT;
2332 pud = pud_alloc(mm, p4d, addr);
2336 next = pud_addr_end(addr, end);
2337 err = remap_pmd_range(mm, pud, addr, next,
2338 pfn + (addr >> PAGE_SHIFT), prot);
2341 } while (pud++, addr = next, addr != end);
2345 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2346 unsigned long addr, unsigned long end,
2347 unsigned long pfn, pgprot_t prot)
2353 pfn -= addr >> PAGE_SHIFT;
2354 p4d = p4d_alloc(mm, pgd, addr);
2358 next = p4d_addr_end(addr, end);
2359 err = remap_pud_range(mm, p4d, addr, next,
2360 pfn + (addr >> PAGE_SHIFT), prot);
2363 } while (p4d++, addr = next, addr != end);
2368 * remap_pfn_range - remap kernel memory to userspace
2369 * @vma: user vma to map to
2370 * @addr: target page aligned user address to start at
2371 * @pfn: page frame number of kernel physical memory address
2372 * @size: size of mapping area
2373 * @prot: page protection flags for this mapping
2375 * Note: this is only safe if the mm semaphore is held when called.
2377 * Return: %0 on success, negative error code otherwise.
2379 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2380 unsigned long pfn, unsigned long size, pgprot_t prot)
2384 unsigned long end = addr + PAGE_ALIGN(size);
2385 struct mm_struct *mm = vma->vm_mm;
2386 unsigned long remap_pfn = pfn;
2389 if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
2393 * Physically remapped pages are special. Tell the
2394 * rest of the world about it:
2395 * VM_IO tells people not to look at these pages
2396 * (accesses can have side effects).
2397 * VM_PFNMAP tells the core MM that the base pages are just
2398 * raw PFN mappings, and do not have a "struct page" associated
2401 * Disable vma merging and expanding with mremap().
2403 * Omit vma from core dump, even when VM_IO turned off.
2405 * There's a horrible special case to handle copy-on-write
2406 * behaviour that some programs depend on. We mark the "original"
2407 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2408 * See vm_normal_page() for details.
2410 if (is_cow_mapping(vma->vm_flags)) {
2411 if (addr != vma->vm_start || end != vma->vm_end)
2413 vma->vm_pgoff = pfn;
2416 err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
2420 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2422 BUG_ON(addr >= end);
2423 pfn -= addr >> PAGE_SHIFT;
2424 pgd = pgd_offset(mm, addr);
2425 flush_cache_range(vma, addr, end);
2427 next = pgd_addr_end(addr, end);
2428 err = remap_p4d_range(mm, pgd, addr, next,
2429 pfn + (addr >> PAGE_SHIFT), prot);
2432 } while (pgd++, addr = next, addr != end);
2435 untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
2439 EXPORT_SYMBOL(remap_pfn_range);
2442 * vm_iomap_memory - remap memory to userspace
2443 * @vma: user vma to map to
2444 * @start: start of the physical memory to be mapped
2445 * @len: size of area
2447 * This is a simplified io_remap_pfn_range() for common driver use. The
2448 * driver just needs to give us the physical memory range to be mapped,
2449 * we'll figure out the rest from the vma information.
2451 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2452 * whatever write-combining details or similar.
2454 * Return: %0 on success, negative error code otherwise.
2456 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2458 unsigned long vm_len, pfn, pages;
2460 /* Check that the physical memory area passed in looks valid */
2461 if (start + len < start)
2464 * You *really* shouldn't map things that aren't page-aligned,
2465 * but we've historically allowed it because IO memory might
2466 * just have smaller alignment.
2468 len += start & ~PAGE_MASK;
2469 pfn = start >> PAGE_SHIFT;
2470 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2471 if (pfn + pages < pfn)
2474 /* We start the mapping 'vm_pgoff' pages into the area */
2475 if (vma->vm_pgoff > pages)
2477 pfn += vma->vm_pgoff;
2478 pages -= vma->vm_pgoff;
2480 /* Can we fit all of the mapping? */
2481 vm_len = vma->vm_end - vma->vm_start;
2482 if (vm_len >> PAGE_SHIFT > pages)
2485 /* Ok, let it rip */
2486 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2488 EXPORT_SYMBOL(vm_iomap_memory);
2490 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2491 unsigned long addr, unsigned long end,
2492 pte_fn_t fn, void *data, bool create,
2493 pgtbl_mod_mask *mask)
2500 pte = (mm == &init_mm) ?
2501 pte_alloc_kernel_track(pmd, addr, mask) :
2502 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2506 pte = (mm == &init_mm) ?
2507 pte_offset_kernel(pmd, addr) :
2508 pte_offset_map_lock(mm, pmd, addr, &ptl);
2511 BUG_ON(pmd_huge(*pmd));
2513 arch_enter_lazy_mmu_mode();
2517 if (create || !pte_none(*pte)) {
2518 err = fn(pte++, addr, data);
2522 } while (addr += PAGE_SIZE, addr != end);
2524 *mask |= PGTBL_PTE_MODIFIED;
2526 arch_leave_lazy_mmu_mode();
2529 pte_unmap_unlock(pte-1, ptl);
2533 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2534 unsigned long addr, unsigned long end,
2535 pte_fn_t fn, void *data, bool create,
2536 pgtbl_mod_mask *mask)
2542 BUG_ON(pud_huge(*pud));
2545 pmd = pmd_alloc_track(mm, pud, addr, mask);
2549 pmd = pmd_offset(pud, addr);
2552 next = pmd_addr_end(addr, end);
2553 if (create || !pmd_none_or_clear_bad(pmd)) {
2554 err = apply_to_pte_range(mm, pmd, addr, next, fn, data,
2559 } while (pmd++, addr = next, addr != end);
2563 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2564 unsigned long addr, unsigned long end,
2565 pte_fn_t fn, void *data, bool create,
2566 pgtbl_mod_mask *mask)
2573 pud = pud_alloc_track(mm, p4d, addr, mask);
2577 pud = pud_offset(p4d, addr);
2580 next = pud_addr_end(addr, end);
2581 if (create || !pud_none_or_clear_bad(pud)) {
2582 err = apply_to_pmd_range(mm, pud, addr, next, fn, data,
2587 } while (pud++, addr = next, addr != end);
2591 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2592 unsigned long addr, unsigned long end,
2593 pte_fn_t fn, void *data, bool create,
2594 pgtbl_mod_mask *mask)
2601 p4d = p4d_alloc_track(mm, pgd, addr, mask);
2605 p4d = p4d_offset(pgd, addr);
2608 next = p4d_addr_end(addr, end);
2609 if (create || !p4d_none_or_clear_bad(p4d)) {
2610 err = apply_to_pud_range(mm, p4d, addr, next, fn, data,
2615 } while (p4d++, addr = next, addr != end);
2619 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2620 unsigned long size, pte_fn_t fn,
2621 void *data, bool create)
2624 unsigned long start = addr, next;
2625 unsigned long end = addr + size;
2626 pgtbl_mod_mask mask = 0;
2629 if (WARN_ON(addr >= end))
2632 pgd = pgd_offset(mm, addr);
2634 next = pgd_addr_end(addr, end);
2635 if (!create && pgd_none_or_clear_bad(pgd))
2637 err = apply_to_p4d_range(mm, pgd, addr, next, fn, data, create, &mask);
2640 } while (pgd++, addr = next, addr != end);
2642 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
2643 arch_sync_kernel_mappings(start, start + size);
2649 * Scan a region of virtual memory, filling in page tables as necessary
2650 * and calling a provided function on each leaf page table.
2652 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2653 unsigned long size, pte_fn_t fn, void *data)
2655 return __apply_to_page_range(mm, addr, size, fn, data, true);
2657 EXPORT_SYMBOL_GPL(apply_to_page_range);
2660 * Scan a region of virtual memory, calling a provided function on
2661 * each leaf page table where it exists.
2663 * Unlike apply_to_page_range, this does _not_ fill in page tables
2664 * where they are absent.
2666 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
2667 unsigned long size, pte_fn_t fn, void *data)
2669 return __apply_to_page_range(mm, addr, size, fn, data, false);
2671 EXPORT_SYMBOL_GPL(apply_to_existing_page_range);
2674 * handle_pte_fault chooses page fault handler according to an entry which was
2675 * read non-atomically. Before making any commitment, on those architectures
2676 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2677 * parts, do_swap_page must check under lock before unmapping the pte and
2678 * proceeding (but do_wp_page is only called after already making such a check;
2679 * and do_anonymous_page can safely check later on).
2681 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2682 pte_t *page_table, pte_t orig_pte)
2685 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
2686 if (sizeof(pte_t) > sizeof(unsigned long)) {
2687 spinlock_t *ptl = pte_lockptr(mm, pmd);
2689 same = pte_same(*page_table, orig_pte);
2693 pte_unmap(page_table);
2697 static inline bool cow_user_page(struct page *dst, struct page *src,
2698 struct vm_fault *vmf)
2703 bool locked = false;
2704 struct vm_area_struct *vma = vmf->vma;
2705 struct mm_struct *mm = vma->vm_mm;
2706 unsigned long addr = vmf->address;
2709 copy_user_highpage(dst, src, addr, vma);
2714 * If the source page was a PFN mapping, we don't have
2715 * a "struct page" for it. We do a best-effort copy by
2716 * just copying from the original user address. If that
2717 * fails, we just zero-fill it. Live with it.
2719 kaddr = kmap_atomic(dst);
2720 uaddr = (void __user *)(addr & PAGE_MASK);
2723 * On architectures with software "accessed" bits, we would
2724 * take a double page fault, so mark it accessed here.
2726 if (arch_faults_on_old_pte() && !pte_young(vmf->orig_pte)) {
2729 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2731 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2733 * Other thread has already handled the fault
2734 * and update local tlb only
2736 update_mmu_tlb(vma, addr, vmf->pte);
2741 entry = pte_mkyoung(vmf->orig_pte);
2742 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2743 update_mmu_cache(vma, addr, vmf->pte);
2747 * This really shouldn't fail, because the page is there
2748 * in the page tables. But it might just be unreadable,
2749 * in which case we just give up and fill the result with
2752 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2756 /* Re-validate under PTL if the page is still mapped */
2757 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2759 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2760 /* The PTE changed under us, update local tlb */
2761 update_mmu_tlb(vma, addr, vmf->pte);
2767 * The same page can be mapped back since last copy attempt.
2768 * Try to copy again under PTL.
2770 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2772 * Give a warn in case there can be some obscure
2785 pte_unmap_unlock(vmf->pte, vmf->ptl);
2786 kunmap_atomic(kaddr);
2787 flush_dcache_page(dst);
2792 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2794 struct file *vm_file = vma->vm_file;
2797 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2800 * Special mappings (e.g. VDSO) do not have any file so fake
2801 * a default GFP_KERNEL for them.
2807 * Notify the address space that the page is about to become writable so that
2808 * it can prohibit this or wait for the page to get into an appropriate state.
2810 * We do this without the lock held, so that it can sleep if it needs to.
2812 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf)
2815 struct page *page = vmf->page;
2816 unsigned int old_flags = vmf->flags;
2818 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2820 if (vmf->vma->vm_file &&
2821 IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
2822 return VM_FAULT_SIGBUS;
2824 ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2825 /* Restore original flags so that caller is not surprised */
2826 vmf->flags = old_flags;
2827 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2829 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2831 if (!page->mapping) {
2833 return 0; /* retry */
2835 ret |= VM_FAULT_LOCKED;
2837 VM_BUG_ON_PAGE(!PageLocked(page), page);
2842 * Handle dirtying of a page in shared file mapping on a write fault.
2844 * The function expects the page to be locked and unlocks it.
2846 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
2848 struct vm_area_struct *vma = vmf->vma;
2849 struct address_space *mapping;
2850 struct page *page = vmf->page;
2852 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2854 dirtied = set_page_dirty(page);
2855 VM_BUG_ON_PAGE(PageAnon(page), page);
2857 * Take a local copy of the address_space - page.mapping may be zeroed
2858 * by truncate after unlock_page(). The address_space itself remains
2859 * pinned by vma->vm_file's reference. We rely on unlock_page()'s
2860 * release semantics to prevent the compiler from undoing this copying.
2862 mapping = page_rmapping(page);
2866 file_update_time(vma->vm_file);
2869 * Throttle page dirtying rate down to writeback speed.
2871 * mapping may be NULL here because some device drivers do not
2872 * set page.mapping but still dirty their pages
2874 * Drop the mmap_lock before waiting on IO, if we can. The file
2875 * is pinning the mapping, as per above.
2877 if ((dirtied || page_mkwrite) && mapping) {
2880 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
2881 balance_dirty_pages_ratelimited(mapping);
2884 return VM_FAULT_RETRY;
2892 * Handle write page faults for pages that can be reused in the current vma
2894 * This can happen either due to the mapping being with the VM_SHARED flag,
2895 * or due to us being the last reference standing to the page. In either
2896 * case, all we need to do here is to mark the page as writable and update
2897 * any related book-keeping.
2899 static inline void wp_page_reuse(struct vm_fault *vmf)
2900 __releases(vmf->ptl)
2902 struct vm_area_struct *vma = vmf->vma;
2903 struct page *page = vmf->page;
2906 * Clear the pages cpupid information as the existing
2907 * information potentially belongs to a now completely
2908 * unrelated process.
2911 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2913 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2914 entry = pte_mkyoung(vmf->orig_pte);
2915 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2916 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
2917 update_mmu_cache(vma, vmf->address, vmf->pte);
2918 pte_unmap_unlock(vmf->pte, vmf->ptl);
2919 count_vm_event(PGREUSE);
2923 * Handle the case of a page which we actually need to copy to a new page.
2925 * Called with mmap_lock locked and the old page referenced, but
2926 * without the ptl held.
2928 * High level logic flow:
2930 * - Allocate a page, copy the content of the old page to the new one.
2931 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2932 * - Take the PTL. If the pte changed, bail out and release the allocated page
2933 * - If the pte is still the way we remember it, update the page table and all
2934 * relevant references. This includes dropping the reference the page-table
2935 * held to the old page, as well as updating the rmap.
2936 * - In any case, unlock the PTL and drop the reference we took to the old page.
2938 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
2940 struct vm_area_struct *vma = vmf->vma;
2941 struct mm_struct *mm = vma->vm_mm;
2942 struct page *old_page = vmf->page;
2943 struct page *new_page = NULL;
2945 int page_copied = 0;
2946 struct mmu_notifier_range range;
2948 if (unlikely(anon_vma_prepare(vma)))
2951 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
2952 new_page = alloc_zeroed_user_highpage_movable(vma,
2957 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2962 if (!cow_user_page(new_page, old_page, vmf)) {
2964 * COW failed, if the fault was solved by other,
2965 * it's fine. If not, userspace would re-fault on
2966 * the same address and we will handle the fault
2967 * from the second attempt.
2976 if (mem_cgroup_charge(new_page, mm, GFP_KERNEL))
2978 cgroup_throttle_swaprate(new_page, GFP_KERNEL);
2980 __SetPageUptodate(new_page);
2982 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
2983 vmf->address & PAGE_MASK,
2984 (vmf->address & PAGE_MASK) + PAGE_SIZE);
2985 mmu_notifier_invalidate_range_start(&range);
2988 * Re-check the pte - we dropped the lock
2990 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
2991 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2993 if (!PageAnon(old_page)) {
2994 dec_mm_counter_fast(mm,
2995 mm_counter_file(old_page));
2996 inc_mm_counter_fast(mm, MM_ANONPAGES);
2999 inc_mm_counter_fast(mm, MM_ANONPAGES);
3001 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3002 entry = mk_pte(new_page, vma->vm_page_prot);
3003 entry = pte_sw_mkyoung(entry);
3004 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3006 * Clear the pte entry and flush it first, before updating the
3007 * pte with the new entry. This will avoid a race condition
3008 * seen in the presence of one thread doing SMC and another
3011 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
3012 page_add_new_anon_rmap(new_page, vma, vmf->address, false);
3013 lru_cache_add_inactive_or_unevictable(new_page, vma);
3015 * We call the notify macro here because, when using secondary
3016 * mmu page tables (such as kvm shadow page tables), we want the
3017 * new page to be mapped directly into the secondary page table.
3019 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
3020 update_mmu_cache(vma, vmf->address, vmf->pte);
3023 * Only after switching the pte to the new page may
3024 * we remove the mapcount here. Otherwise another
3025 * process may come and find the rmap count decremented
3026 * before the pte is switched to the new page, and
3027 * "reuse" the old page writing into it while our pte
3028 * here still points into it and can be read by other
3031 * The critical issue is to order this
3032 * page_remove_rmap with the ptp_clear_flush above.
3033 * Those stores are ordered by (if nothing else,)
3034 * the barrier present in the atomic_add_negative
3035 * in page_remove_rmap.
3037 * Then the TLB flush in ptep_clear_flush ensures that
3038 * no process can access the old page before the
3039 * decremented mapcount is visible. And the old page
3040 * cannot be reused until after the decremented
3041 * mapcount is visible. So transitively, TLBs to
3042 * old page will be flushed before it can be reused.
3044 page_remove_rmap(old_page, false);
3047 /* Free the old page.. */
3048 new_page = old_page;
3051 update_mmu_tlb(vma, vmf->address, vmf->pte);
3057 pte_unmap_unlock(vmf->pte, vmf->ptl);
3059 * No need to double call mmu_notifier->invalidate_range() callback as
3060 * the above ptep_clear_flush_notify() did already call it.
3062 mmu_notifier_invalidate_range_only_end(&range);
3065 * Don't let another task, with possibly unlocked vma,
3066 * keep the mlocked page.
3068 if (page_copied && (vma->vm_flags & VM_LOCKED)) {
3069 lock_page(old_page); /* LRU manipulation */
3070 if (PageMlocked(old_page))
3071 munlock_vma_page(old_page);
3072 unlock_page(old_page);
3076 return page_copied ? VM_FAULT_WRITE : 0;
3082 return VM_FAULT_OOM;
3086 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
3087 * writeable once the page is prepared
3089 * @vmf: structure describing the fault
3091 * This function handles all that is needed to finish a write page fault in a
3092 * shared mapping due to PTE being read-only once the mapped page is prepared.
3093 * It handles locking of PTE and modifying it.
3095 * The function expects the page to be locked or other protection against
3096 * concurrent faults / writeback (such as DAX radix tree locks).
3098 * Return: %VM_FAULT_WRITE on success, %0 when PTE got changed before
3099 * we acquired PTE lock.
3101 vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf)
3103 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
3104 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
3107 * We might have raced with another page fault while we released the
3108 * pte_offset_map_lock.
3110 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
3111 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
3112 pte_unmap_unlock(vmf->pte, vmf->ptl);
3113 return VM_FAULT_NOPAGE;
3120 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
3123 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
3125 struct vm_area_struct *vma = vmf->vma;
3127 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
3130 pte_unmap_unlock(vmf->pte, vmf->ptl);
3131 vmf->flags |= FAULT_FLAG_MKWRITE;
3132 ret = vma->vm_ops->pfn_mkwrite(vmf);
3133 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
3135 return finish_mkwrite_fault(vmf);
3138 return VM_FAULT_WRITE;
3141 static vm_fault_t wp_page_shared(struct vm_fault *vmf)
3142 __releases(vmf->ptl)
3144 struct vm_area_struct *vma = vmf->vma;
3145 vm_fault_t ret = VM_FAULT_WRITE;
3147 get_page(vmf->page);
3149 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
3152 pte_unmap_unlock(vmf->pte, vmf->ptl);
3153 tmp = do_page_mkwrite(vmf);
3154 if (unlikely(!tmp || (tmp &
3155 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3156 put_page(vmf->page);
3159 tmp = finish_mkwrite_fault(vmf);
3160 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3161 unlock_page(vmf->page);
3162 put_page(vmf->page);
3167 lock_page(vmf->page);
3169 ret |= fault_dirty_shared_page(vmf);
3170 put_page(vmf->page);
3176 * This routine handles present pages, when users try to write
3177 * to a shared page. It is done by copying the page to a new address
3178 * and decrementing the shared-page counter for the old page.
3180 * Note that this routine assumes that the protection checks have been
3181 * done by the caller (the low-level page fault routine in most cases).
3182 * Thus we can safely just mark it writable once we've done any necessary
3185 * We also mark the page dirty at this point even though the page will
3186 * change only once the write actually happens. This avoids a few races,
3187 * and potentially makes it more efficient.
3189 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3190 * but allow concurrent faults), with pte both mapped and locked.
3191 * We return with mmap_lock still held, but pte unmapped and unlocked.
3193 static vm_fault_t do_wp_page(struct vm_fault *vmf)
3194 __releases(vmf->ptl)
3196 struct vm_area_struct *vma = vmf->vma;
3198 if (userfaultfd_pte_wp(vma, *vmf->pte)) {
3199 pte_unmap_unlock(vmf->pte, vmf->ptl);
3200 return handle_userfault(vmf, VM_UFFD_WP);
3204 * Userfaultfd write-protect can defer flushes. Ensure the TLB
3205 * is flushed in this case before copying.
3207 if (unlikely(userfaultfd_wp(vmf->vma) &&
3208 mm_tlb_flush_pending(vmf->vma->vm_mm)))
3209 flush_tlb_page(vmf->vma, vmf->address);
3211 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
3214 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
3217 * We should not cow pages in a shared writeable mapping.
3218 * Just mark the pages writable and/or call ops->pfn_mkwrite.
3220 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3221 (VM_WRITE|VM_SHARED))
3222 return wp_pfn_shared(vmf);
3224 pte_unmap_unlock(vmf->pte, vmf->ptl);
3225 return wp_page_copy(vmf);
3229 * Take out anonymous pages first, anonymous shared vmas are
3230 * not dirty accountable.
3232 if (PageAnon(vmf->page)) {
3233 struct page *page = vmf->page;
3235 /* PageKsm() doesn't necessarily raise the page refcount */
3236 if (PageKsm(page) || page_count(page) != 1)
3238 if (!trylock_page(page))
3240 if (PageKsm(page) || page_mapcount(page) != 1 || page_count(page) != 1) {
3245 * Ok, we've got the only map reference, and the only
3246 * page count reference, and the page is locked,
3247 * it's dark out, and we're wearing sunglasses. Hit it.
3251 return VM_FAULT_WRITE;
3252 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3253 (VM_WRITE|VM_SHARED))) {
3254 return wp_page_shared(vmf);
3258 * Ok, we need to copy. Oh, well..
3260 get_page(vmf->page);
3262 pte_unmap_unlock(vmf->pte, vmf->ptl);
3263 return wp_page_copy(vmf);
3266 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
3267 unsigned long start_addr, unsigned long end_addr,
3268 struct zap_details *details)
3270 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
3273 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
3274 struct zap_details *details)
3276 struct vm_area_struct *vma;
3277 pgoff_t vba, vea, zba, zea;
3279 vma_interval_tree_foreach(vma, root,
3280 details->first_index, details->last_index) {
3282 vba = vma->vm_pgoff;
3283 vea = vba + vma_pages(vma) - 1;
3284 zba = details->first_index;
3287 zea = details->last_index;
3291 unmap_mapping_range_vma(vma,
3292 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
3293 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3299 * unmap_mapping_pages() - Unmap pages from processes.
3300 * @mapping: The address space containing pages to be unmapped.
3301 * @start: Index of first page to be unmapped.
3302 * @nr: Number of pages to be unmapped. 0 to unmap to end of file.
3303 * @even_cows: Whether to unmap even private COWed pages.
3305 * Unmap the pages in this address space from any userspace process which
3306 * has them mmaped. Generally, you want to remove COWed pages as well when
3307 * a file is being truncated, but not when invalidating pages from the page
3310 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
3311 pgoff_t nr, bool even_cows)
3313 struct zap_details details = { };
3315 details.check_mapping = even_cows ? NULL : mapping;
3316 details.first_index = start;
3317 details.last_index = start + nr - 1;
3318 if (details.last_index < details.first_index)
3319 details.last_index = ULONG_MAX;
3321 i_mmap_lock_write(mapping);
3322 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3323 unmap_mapping_range_tree(&mapping->i_mmap, &details);
3324 i_mmap_unlock_write(mapping);
3328 * unmap_mapping_range - unmap the portion of all mmaps in the specified
3329 * address_space corresponding to the specified byte range in the underlying
3332 * @mapping: the address space containing mmaps to be unmapped.
3333 * @holebegin: byte in first page to unmap, relative to the start of
3334 * the underlying file. This will be rounded down to a PAGE_SIZE
3335 * boundary. Note that this is different from truncate_pagecache(), which
3336 * must keep the partial page. In contrast, we must get rid of
3338 * @holelen: size of prospective hole in bytes. This will be rounded
3339 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
3341 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3342 * but 0 when invalidating pagecache, don't throw away private data.
3344 void unmap_mapping_range(struct address_space *mapping,
3345 loff_t const holebegin, loff_t const holelen, int even_cows)
3347 pgoff_t hba = holebegin >> PAGE_SHIFT;
3348 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3350 /* Check for overflow. */
3351 if (sizeof(holelen) > sizeof(hlen)) {
3353 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3354 if (holeend & ~(long long)ULONG_MAX)
3355 hlen = ULONG_MAX - hba + 1;
3358 unmap_mapping_pages(mapping, hba, hlen, even_cows);
3360 EXPORT_SYMBOL(unmap_mapping_range);
3363 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3364 * but allow concurrent faults), and pte mapped but not yet locked.
3365 * We return with pte unmapped and unlocked.
3367 * We return with the mmap_lock locked or unlocked in the same cases
3368 * as does filemap_fault().
3370 vm_fault_t do_swap_page(struct vm_fault *vmf)
3372 struct vm_area_struct *vma = vmf->vma;
3373 struct page *page = NULL, *swapcache;
3379 void *shadow = NULL;
3381 if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte))
3384 entry = pte_to_swp_entry(vmf->orig_pte);
3385 if (unlikely(non_swap_entry(entry))) {
3386 if (is_migration_entry(entry)) {
3387 migration_entry_wait(vma->vm_mm, vmf->pmd,
3389 } else if (is_device_private_entry(entry)) {
3390 vmf->page = device_private_entry_to_page(entry);
3391 ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
3392 } else if (is_hwpoison_entry(entry)) {
3393 ret = VM_FAULT_HWPOISON;
3395 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3396 ret = VM_FAULT_SIGBUS;
3402 delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3403 page = lookup_swap_cache(entry, vma, vmf->address);
3407 struct swap_info_struct *si = swp_swap_info(entry);
3409 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
3410 __swap_count(entry) == 1) {
3411 /* skip swapcache */
3412 page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3417 __SetPageLocked(page);
3418 __SetPageSwapBacked(page);
3419 set_page_private(page, entry.val);
3421 /* Tell memcg to use swap ownership records */
3422 SetPageSwapCache(page);
3423 err = mem_cgroup_charge(page, vma->vm_mm,
3425 ClearPageSwapCache(page);
3431 shadow = get_shadow_from_swap_cache(entry);
3433 workingset_refault(page, shadow);
3435 lru_cache_add(page);
3436 swap_readpage(page, true);
3439 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3446 * Back out if somebody else faulted in this pte
3447 * while we released the pte lock.
3449 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3450 vmf->address, &vmf->ptl);
3451 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3453 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3457 /* Had to read the page from swap area: Major fault */
3458 ret = VM_FAULT_MAJOR;
3459 count_vm_event(PGMAJFAULT);
3460 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3461 } else if (PageHWPoison(page)) {
3463 * hwpoisoned dirty swapcache pages are kept for killing
3464 * owner processes (which may be unknown at hwpoison time)
3466 ret = VM_FAULT_HWPOISON;
3467 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3471 locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3473 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3475 ret |= VM_FAULT_RETRY;
3480 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3481 * release the swapcache from under us. The page pin, and pte_same
3482 * test below, are not enough to exclude that. Even if it is still
3483 * swapcache, we need to check that the page's swap has not changed.
3485 if (unlikely((!PageSwapCache(page) ||
3486 page_private(page) != entry.val)) && swapcache)
3489 page = ksm_might_need_to_copy(page, vma, vmf->address);
3490 if (unlikely(!page)) {
3496 cgroup_throttle_swaprate(page, GFP_KERNEL);
3499 * Back out if somebody else already faulted in this pte.
3501 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3503 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3506 if (unlikely(!PageUptodate(page))) {
3507 ret = VM_FAULT_SIGBUS;
3512 * The page isn't present yet, go ahead with the fault.
3514 * Be careful about the sequence of operations here.
3515 * To get its accounting right, reuse_swap_page() must be called
3516 * while the page is counted on swap but not yet in mapcount i.e.
3517 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3518 * must be called after the swap_free(), or it will never succeed.
3521 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3522 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3523 pte = mk_pte(page, vma->vm_page_prot);
3524 if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3525 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3526 vmf->flags &= ~FAULT_FLAG_WRITE;
3527 ret |= VM_FAULT_WRITE;
3528 exclusive = RMAP_EXCLUSIVE;
3530 flush_icache_page(vma, page);
3531 if (pte_swp_soft_dirty(vmf->orig_pte))
3532 pte = pte_mksoft_dirty(pte);
3533 if (pte_swp_uffd_wp(vmf->orig_pte)) {
3534 pte = pte_mkuffd_wp(pte);
3535 pte = pte_wrprotect(pte);
3537 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3538 arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
3539 vmf->orig_pte = pte;
3541 /* ksm created a completely new copy */
3542 if (unlikely(page != swapcache && swapcache)) {
3543 page_add_new_anon_rmap(page, vma, vmf->address, false);
3544 lru_cache_add_inactive_or_unevictable(page, vma);
3546 do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3550 if (mem_cgroup_swap_full(page) ||
3551 (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3552 try_to_free_swap(page);
3554 if (page != swapcache && swapcache) {
3556 * Hold the lock to avoid the swap entry to be reused
3557 * until we take the PT lock for the pte_same() check
3558 * (to avoid false positives from pte_same). For
3559 * further safety release the lock after the swap_free
3560 * so that the swap count won't change under a
3561 * parallel locked swapcache.
3563 unlock_page(swapcache);
3564 put_page(swapcache);
3567 if (vmf->flags & FAULT_FLAG_WRITE) {
3568 ret |= do_wp_page(vmf);
3569 if (ret & VM_FAULT_ERROR)
3570 ret &= VM_FAULT_ERROR;
3574 /* No need to invalidate - it was non-present before */
3575 update_mmu_cache(vma, vmf->address, vmf->pte);
3577 pte_unmap_unlock(vmf->pte, vmf->ptl);
3581 pte_unmap_unlock(vmf->pte, vmf->ptl);
3586 if (page != swapcache && swapcache) {
3587 unlock_page(swapcache);
3588 put_page(swapcache);
3593 extern bool eager_allocation;
3596 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3597 * but allow concurrent faults), and pte mapped but not yet locked.
3598 * We return with mmap_lock still held, but pte unmapped and unlocked.
3600 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
3602 struct vm_area_struct *vma = vmf->vma;
3607 /* File mapping without ->vm_ops ? */
3608 if (vma->vm_flags & VM_SHARED)
3609 return VM_FAULT_SIGBUS;
3612 * Use pte_alloc() instead of pte_alloc_map(). We can't run
3613 * pte_offset_map() on pmds where a huge pmd might be created
3614 * from a different thread.
3616 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
3617 * parallel threads are excluded by other means.
3619 * Here we only have mmap_read_lock(mm).
3621 if (pte_alloc(vma->vm_mm, vmf->pmd))
3622 return VM_FAULT_OOM;
3624 /* See the comment in pte_alloc_one_map() */
3625 if (unlikely(pmd_trans_unstable(vmf->pmd)))
3628 /* Use the zero-page for reads */
3629 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3630 !mm_forbids_zeropage(vma->vm_mm)) {
3631 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3632 vma->vm_page_prot));
3633 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3634 vmf->address, &vmf->ptl);
3635 if (!pte_none(*vmf->pte)) {
3636 update_mmu_tlb(vma, vmf->address, vmf->pte);
3639 ret = check_stable_address_space(vma->vm_mm);
3642 /* Deliver the page fault to userland, check inside PT lock */
3643 if (userfaultfd_missing(vma)) {
3644 pte_unmap_unlock(vmf->pte, vmf->ptl);
3645 return handle_userfault(vmf, VM_UFFD_MISSING);
3650 /* Allocate our own private page. */
3651 if (unlikely(anon_vma_prepare(vma)))
3653 #ifdef CONFIG_FINEGRAINED_THP
3654 #ifndef CONFIG_THP_CONSERVATIVE
3656 * 64KB hugepage creation on page fault is only allowed
3657 * in an aggressive policy or a near-conservative policy
3659 if (__transparent_hugepage_enabled(vma)) {
3660 ret = arch_do_huge_pte_anonymous_page(vmf);
3661 if (!(ret & VM_FAULT_FALLBACK)) {
3666 #endif /* CONFIG_THP_CONSERVATIVE */
3667 #endif /* CONFIG_FINEGRAINED_THP */
3669 page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3673 if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
3675 cgroup_throttle_swaprate(page, GFP_KERNEL);
3678 * The memory barrier inside __SetPageUptodate makes sure that
3679 * preceding stores to the page contents become visible before
3680 * the set_pte_at() write.
3682 __SetPageUptodate(page);
3684 entry = mk_pte(page, vma->vm_page_prot);
3685 entry = pte_sw_mkyoung(entry);
3686 if (vma->vm_flags & VM_WRITE)
3687 entry = pte_mkwrite(pte_mkdirty(entry));
3689 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3691 if (!pte_none(*vmf->pte)) {
3692 update_mmu_cache(vma, vmf->address, vmf->pte);
3696 ret = check_stable_address_space(vma->vm_mm);
3700 /* Deliver the page fault to userland, check inside PT lock */
3701 if (userfaultfd_missing(vma)) {
3702 pte_unmap_unlock(vmf->pte, vmf->ptl);
3704 return handle_userfault(vmf, VM_UFFD_MISSING);
3707 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3708 page_add_new_anon_rmap(page, vma, vmf->address, false);
3709 lru_cache_add_inactive_or_unevictable(page, vma);
3711 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3713 /* No need to invalidate - it was non-present before */
3714 update_mmu_cache(vma, vmf->address, vmf->pte);
3716 pte_unmap_unlock(vmf->pte, vmf->ptl);
3724 return VM_FAULT_OOM;
3728 * The mmap_lock must have been held on entry, and may have been
3729 * released depending on flags and vma->vm_ops->fault() return value.
3730 * See filemap_fault() and __lock_page_retry().
3732 static vm_fault_t __do_fault(struct vm_fault *vmf)
3734 struct vm_area_struct *vma = vmf->vma;
3738 * Preallocate pte before we take page_lock because this might lead to
3739 * deadlocks for memcg reclaim which waits for pages under writeback:
3741 * SetPageWriteback(A)
3747 * wait_on_page_writeback(A)
3748 * SetPageWriteback(B)
3750 * # flush A, B to clear the writeback
3752 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3753 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3754 if (!vmf->prealloc_pte)
3755 return VM_FAULT_OOM;
3756 smp_wmb(); /* See comment in __pte_alloc() */
3759 ret = vma->vm_ops->fault(vmf);
3760 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3761 VM_FAULT_DONE_COW)))
3764 if (unlikely(PageHWPoison(vmf->page))) {
3765 if (ret & VM_FAULT_LOCKED)
3766 unlock_page(vmf->page);
3767 put_page(vmf->page);
3769 return VM_FAULT_HWPOISON;
3772 if (unlikely(!(ret & VM_FAULT_LOCKED)))
3773 lock_page(vmf->page);
3775 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3781 * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3782 * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3783 * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3784 * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3786 static int pmd_devmap_trans_unstable(pmd_t *pmd)
3788 return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3791 static vm_fault_t pte_alloc_one_map(struct vm_fault *vmf)
3793 struct vm_area_struct *vma = vmf->vma;
3795 if (!pmd_none(*vmf->pmd))
3797 if (vmf->prealloc_pte) {
3798 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3799 if (unlikely(!pmd_none(*vmf->pmd))) {
3800 spin_unlock(vmf->ptl);
3804 mm_inc_nr_ptes(vma->vm_mm);
3805 pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3806 spin_unlock(vmf->ptl);
3807 vmf->prealloc_pte = NULL;
3808 } else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd))) {
3809 return VM_FAULT_OOM;
3813 * If a huge pmd materialized under us just retry later. Use
3814 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3815 * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3816 * under us and then back to pmd_none, as a result of MADV_DONTNEED
3817 * running immediately after a huge pmd fault in a different thread of
3818 * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3819 * All we have to ensure is that it is a regular pmd that we can walk
3820 * with pte_offset_map() and we can do that through an atomic read in
3821 * C, which is what pmd_trans_unstable() provides.
3823 if (pmd_devmap_trans_unstable(vmf->pmd))
3824 return VM_FAULT_NOPAGE;
3827 * At this point we know that our vmf->pmd points to a page of ptes
3828 * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3829 * for the duration of the fault. If a racing MADV_DONTNEED runs and
3830 * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3831 * be valid and we will re-check to make sure the vmf->pte isn't
3832 * pte_none() under vmf->ptl protection when we return to
3835 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3840 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3841 static void deposit_prealloc_pte(struct vm_fault *vmf)
3843 struct vm_area_struct *vma = vmf->vma;
3845 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3847 * We are going to consume the prealloc table,
3848 * count that as nr_ptes.
3850 mm_inc_nr_ptes(vma->vm_mm);
3851 vmf->prealloc_pte = NULL;
3854 static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3856 struct vm_area_struct *vma = vmf->vma;
3857 bool write = vmf->flags & FAULT_FLAG_WRITE;
3858 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3861 vm_fault_t ret = VM_FAULT_FALLBACK;
3863 if (!transhuge_vma_suitable(vma, haddr))
3866 page = compound_head(page);
3867 if (compound_order(page) != HPAGE_PMD_ORDER)
3871 * Archs like ppc64 need additonal space to store information
3872 * related to pte entry. Use the preallocated table for that.
3874 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3875 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3876 if (!vmf->prealloc_pte)
3877 return VM_FAULT_OOM;
3878 smp_wmb(); /* See comment in __pte_alloc() */
3881 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3882 if (unlikely(!pmd_none(*vmf->pmd)))
3885 for (i = 0; i < HPAGE_PMD_NR; i++)
3886 flush_icache_page(vma, page + i);
3888 entry = mk_huge_pmd(page, vma->vm_page_prot);
3890 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3892 add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
3893 page_add_file_rmap(page, true);
3895 * deposit and withdraw with pmd lock held
3897 if (arch_needs_pgtable_deposit())
3898 deposit_prealloc_pte(vmf);
3900 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3902 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3904 /* fault is handled */
3906 count_vm_event(THP_FILE_MAPPED);
3908 spin_unlock(vmf->ptl);
3912 static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3918 #ifdef CONFIG_FINEGRAINED_THP
3919 static vm_fault_t arch_do_set_huge_pte(struct vm_fault *vmf, struct page *page)
3928 * alloc_set_pte - setup new PTE entry for given page and add reverse page
3929 * mapping. If needed, the function allocates page table or use pre-allocated.
3931 * @vmf: fault environment
3932 * @page: page to map
3934 * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
3937 * Target users are page handler itself and implementations of
3938 * vm_ops->map_pages.
3940 * Return: %0 on success, %VM_FAULT_ code in case of error.
3942 vm_fault_t alloc_set_pte(struct vm_fault *vmf, struct page *page)
3944 struct vm_area_struct *vma = vmf->vma;
3945 bool write = vmf->flags & FAULT_FLAG_WRITE;
3949 if (pmd_none(*vmf->pmd) && PageTransCompound(page) &&
3950 compound_nr(compound_head(page)) == HPAGE_PMD_NR) {
3951 ret = do_set_pmd(vmf, page);
3952 if (ret != VM_FAULT_FALLBACK)
3956 #ifdef CONFIG_FINEGRAINED_THP
3957 /* PageTransHuge cannot find hugepage if the page is not a head */
3958 if (PageTransCompound(page) &&
3959 compound_nr(compound_head(page)) == HPAGE_CONT_PTE_NR) {
3960 ret = arch_do_set_huge_pte(vmf, page);
3961 if (ret != VM_FAULT_FALLBACK)
3964 #endif /* CONFIG_FINEGRAINED_THP */
3967 ret = pte_alloc_one_map(vmf);
3972 /* Re-check under ptl */
3973 if (unlikely(!pte_none(*vmf->pte))) {
3974 update_mmu_tlb(vma, vmf->address, vmf->pte);
3975 return VM_FAULT_NOPAGE;
3978 if (!strcmp(current->comm, "org.tizen.nlp.s") || !strcmp(current->comm, "memps"))
3979 pr_info("THP-wp: huge fault for addr (%lx) (%s) %s\n",
3980 vmf->address, current->comm, __func__);
3982 flush_icache_page(vma, page);
3983 entry = mk_pte(page, vma->vm_page_prot);
3984 entry = pte_sw_mkyoung(entry);
3986 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3987 /* copy-on-write page */
3988 if (write && !(vma->vm_flags & VM_SHARED)) {
3989 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3990 page_add_new_anon_rmap(page, vma, vmf->address, false);
3991 lru_cache_add_inactive_or_unevictable(page, vma);
3993 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3994 page_add_file_rmap(page, false);
3996 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3998 /* no need to invalidate: a not-present page won't be cached */
3999 update_mmu_cache(vma, vmf->address, vmf->pte);
4006 * finish_fault - finish page fault once we have prepared the page to fault
4008 * @vmf: structure describing the fault
4010 * This function handles all that is needed to finish a page fault once the
4011 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
4012 * given page, adds reverse page mapping, handles memcg charges and LRU
4015 * The function expects the page to be locked and on success it consumes a
4016 * reference of a page being mapped (for the PTE which maps it).
4018 * Return: %0 on success, %VM_FAULT_ code in case of error.
4020 vm_fault_t finish_fault(struct vm_fault *vmf)
4025 /* Did we COW the page? */
4026 if ((vmf->flags & FAULT_FLAG_WRITE) &&
4027 !(vmf->vma->vm_flags & VM_SHARED))
4028 page = vmf->cow_page;
4033 * check even for read faults because we might have lost our CoWed
4036 if (!(vmf->vma->vm_flags & VM_SHARED))
4037 ret = check_stable_address_space(vmf->vma->vm_mm);
4039 ret = alloc_set_pte(vmf, page);
4041 pte_unmap_unlock(vmf->pte, vmf->ptl);
4045 static unsigned long fault_around_bytes __read_mostly =
4046 rounddown_pow_of_two(4096);
4048 #ifdef CONFIG_DEBUG_FS
4049 static int fault_around_bytes_get(void *data, u64 *val)
4051 *val = fault_around_bytes;
4056 * fault_around_bytes must be rounded down to the nearest page order as it's
4057 * what do_fault_around() expects to see.
4059 static int fault_around_bytes_set(void *data, u64 val)
4061 if (val / PAGE_SIZE > PTRS_PER_PTE)
4063 if (val > PAGE_SIZE)
4064 fault_around_bytes = rounddown_pow_of_two(val);
4066 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
4069 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
4070 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
4072 static int __init fault_around_debugfs(void)
4074 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
4075 &fault_around_bytes_fops);
4078 late_initcall(fault_around_debugfs);
4082 * do_fault_around() tries to map few pages around the fault address. The hope
4083 * is that the pages will be needed soon and this will lower the number of
4086 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
4087 * not ready to be mapped: not up-to-date, locked, etc.
4089 * This function is called with the page table lock taken. In the split ptlock
4090 * case the page table lock only protects only those entries which belong to
4091 * the page table corresponding to the fault address.
4093 * This function doesn't cross the VMA boundaries, in order to call map_pages()
4096 * fault_around_bytes defines how many bytes we'll try to map.
4097 * do_fault_around() expects it to be set to a power of two less than or equal
4100 * The virtual address of the area that we map is naturally aligned to
4101 * fault_around_bytes rounded down to the machine page size
4102 * (and therefore to page order). This way it's easier to guarantee
4103 * that we don't cross page table boundaries.
4105 static vm_fault_t do_fault_around(struct vm_fault *vmf)
4107 unsigned long address = vmf->address, nr_pages, mask;
4108 pgoff_t start_pgoff = vmf->pgoff;
4113 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
4114 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
4116 vmf->address = max(address & mask, vmf->vma->vm_start);
4117 off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
4121 * end_pgoff is either the end of the page table, the end of
4122 * the vma or nr_pages from start_pgoff, depending what is nearest.
4124 end_pgoff = start_pgoff -
4125 ((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
4127 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
4128 start_pgoff + nr_pages - 1);
4130 if (pmd_none(*vmf->pmd)) {
4131 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
4132 if (!vmf->prealloc_pte)
4134 smp_wmb(); /* See comment in __pte_alloc() */
4137 vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
4139 /* Huge page is mapped? Page fault is solved */
4140 if (pmd_trans_huge(*vmf->pmd)) {
4141 ret = VM_FAULT_NOPAGE;
4145 /* ->map_pages() haven't done anything useful. Cold page cache? */
4149 /* check if the page fault is solved */
4150 vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
4151 if (!pte_none(*vmf->pte))
4152 ret = VM_FAULT_NOPAGE;
4153 pte_unmap_unlock(vmf->pte, vmf->ptl);
4155 vmf->address = address;
4160 static vm_fault_t do_read_fault(struct vm_fault *vmf)
4162 struct vm_area_struct *vma = vmf->vma;
4166 * Let's call ->map_pages() first and use ->fault() as fallback
4167 * if page by the offset is not ready to be mapped (cold cache or
4170 if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
4171 ret = do_fault_around(vmf);
4176 ret = __do_fault(vmf);
4177 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4180 ret |= finish_fault(vmf);
4181 unlock_page(vmf->page);
4182 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4183 put_page(vmf->page);
4187 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
4189 struct vm_area_struct *vma = vmf->vma;
4192 if (unlikely(anon_vma_prepare(vma)))
4193 return VM_FAULT_OOM;
4195 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
4197 return VM_FAULT_OOM;
4199 if (mem_cgroup_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL)) {
4200 put_page(vmf->cow_page);
4201 return VM_FAULT_OOM;
4203 cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL);
4205 ret = __do_fault(vmf);
4206 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4208 if (ret & VM_FAULT_DONE_COW)
4210 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
4211 __SetPageUptodate(vmf->cow_page);
4213 ret |= finish_fault(vmf);
4214 unlock_page(vmf->page);
4215 put_page(vmf->page);
4216 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4220 put_page(vmf->cow_page);
4224 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
4226 struct vm_area_struct *vma = vmf->vma;
4227 vm_fault_t ret, tmp;
4229 ret = __do_fault(vmf);
4230 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4234 * Check if the backing address space wants to know that the page is
4235 * about to become writable
4237 if (vma->vm_ops->page_mkwrite) {
4238 unlock_page(vmf->page);
4239 tmp = do_page_mkwrite(vmf);
4240 if (unlikely(!tmp ||
4241 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
4242 put_page(vmf->page);
4247 ret |= finish_fault(vmf);
4248 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
4250 unlock_page(vmf->page);
4251 put_page(vmf->page);
4255 ret |= fault_dirty_shared_page(vmf);
4260 * We enter with non-exclusive mmap_lock (to exclude vma changes,
4261 * but allow concurrent faults).
4262 * The mmap_lock may have been released depending on flags and our
4263 * return value. See filemap_fault() and __lock_page_or_retry().
4264 * If mmap_lock is released, vma may become invalid (for example
4265 * by other thread calling munmap()).
4267 static vm_fault_t do_fault(struct vm_fault *vmf)
4269 struct vm_area_struct *vma = vmf->vma;
4270 struct mm_struct *vm_mm = vma->vm_mm;
4274 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
4276 if (!vma->vm_ops->fault) {
4278 * If we find a migration pmd entry or a none pmd entry, which
4279 * should never happen, return SIGBUS
4281 if (unlikely(!pmd_present(*vmf->pmd)))
4282 ret = VM_FAULT_SIGBUS;
4284 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
4289 * Make sure this is not a temporary clearing of pte
4290 * by holding ptl and checking again. A R/M/W update
4291 * of pte involves: take ptl, clearing the pte so that
4292 * we don't have concurrent modification by hardware
4293 * followed by an update.
4295 if (unlikely(pte_none(*vmf->pte)))
4296 ret = VM_FAULT_SIGBUS;
4298 ret = VM_FAULT_NOPAGE;
4300 pte_unmap_unlock(vmf->pte, vmf->ptl);
4302 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
4303 ret = do_read_fault(vmf);
4304 else if (!(vma->vm_flags & VM_SHARED))
4305 ret = do_cow_fault(vmf);
4307 ret = do_shared_fault(vmf);
4309 /* preallocated pagetable is unused: free it */
4310 if (vmf->prealloc_pte) {
4311 pte_free(vm_mm, vmf->prealloc_pte);
4312 vmf->prealloc_pte = NULL;
4317 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
4318 unsigned long addr, int page_nid,
4323 count_vm_numa_event(NUMA_HINT_FAULTS);
4324 if (page_nid == numa_node_id()) {
4325 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
4326 *flags |= TNF_FAULT_LOCAL;
4329 return mpol_misplaced(page, vma, addr);
4332 static vm_fault_t do_numa_page(struct vm_fault *vmf)
4334 struct vm_area_struct *vma = vmf->vma;
4335 struct page *page = NULL;
4336 int page_nid = NUMA_NO_NODE;
4339 bool migrated = false;
4341 bool was_writable = pte_savedwrite(vmf->orig_pte);
4345 * The "pte" at this point cannot be used safely without
4346 * validation through pte_unmap_same(). It's of NUMA type but
4347 * the pfn may be screwed if the read is non atomic.
4349 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
4350 spin_lock(vmf->ptl);
4351 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4352 pte_unmap_unlock(vmf->pte, vmf->ptl);
4357 * Make it present again, Depending on how arch implementes non
4358 * accessible ptes, some can allow access by kernel mode.
4360 old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte);
4361 pte = pte_modify(old_pte, vma->vm_page_prot);
4362 pte = pte_mkyoung(pte);
4364 pte = pte_mkwrite(pte);
4365 ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte);
4366 update_mmu_cache(vma, vmf->address, vmf->pte);
4368 page = vm_normal_page(vma, vmf->address, pte);
4370 pte_unmap_unlock(vmf->pte, vmf->ptl);
4374 /* TODO: handle PTE-mapped THP */
4375 if (PageCompound(page)) {
4376 pte_unmap_unlock(vmf->pte, vmf->ptl);
4381 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
4382 * much anyway since they can be in shared cache state. This misses
4383 * the case where a mapping is writable but the process never writes
4384 * to it but pte_write gets cleared during protection updates and
4385 * pte_dirty has unpredictable behaviour between PTE scan updates,
4386 * background writeback, dirty balancing and application behaviour.
4388 if (!pte_write(pte))
4389 flags |= TNF_NO_GROUP;
4392 * Flag if the page is shared between multiple address spaces. This
4393 * is later used when determining whether to group tasks together
4395 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
4396 flags |= TNF_SHARED;
4398 last_cpupid = page_cpupid_last(page);
4399 page_nid = page_to_nid(page);
4400 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
4402 pte_unmap_unlock(vmf->pte, vmf->ptl);
4403 if (target_nid == NUMA_NO_NODE) {
4408 /* Migrate to the requested node */
4409 migrated = migrate_misplaced_page(page, vma, target_nid);
4411 page_nid = target_nid;
4412 flags |= TNF_MIGRATED;
4414 flags |= TNF_MIGRATE_FAIL;
4417 if (page_nid != NUMA_NO_NODE)
4418 task_numa_fault(last_cpupid, page_nid, 1, flags);
4422 #ifdef CONFIG_FINEGRAINED_THP
4423 static inline vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf)
4425 //struct timespec64 ts, te, diff;
4428 #ifdef CONFIG_FINEGRAINED_THP
4429 return VM_FAULT_FALLBACK;
4432 //ktime_get_ts64(&ts);
4433 ret = do_huge_pmd_anonymous_page(vmf);
4435 ktime_get_ts64(&te);
4436 diff = timespec64_sub(te, ts);
4437 if (!(ret & VM_FAULT_FALLBACK))
4438 pr_info("THP-fault: 2MB hugepage takes %lu nsecs\n",
4439 timespec64_to_ns(&diff));
4443 #endif /* CONFIG_FINEGRAINED_THP */
4445 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4447 if (vma_is_anonymous(vmf->vma))
4448 #ifdef CONFIG_FINEGRAINED_THP
4449 return __do_huge_pmd_anonymous_page(vmf);
4451 return do_huge_pmd_anonymous_page(vmf);
4453 if (vmf->vma->vm_ops->huge_fault)
4454 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4455 return VM_FAULT_FALLBACK;
4458 /* `inline' is required to avoid gcc 4.1.2 build error */
4459 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
4461 if (vma_is_anonymous(vmf->vma)) {
4462 if (userfaultfd_huge_pmd_wp(vmf->vma, orig_pmd))
4463 return handle_userfault(vmf, VM_UFFD_WP);
4464 return do_huge_pmd_wp_page(vmf, orig_pmd);
4466 if (vmf->vma->vm_ops->huge_fault) {
4467 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4469 if (!(ret & VM_FAULT_FALLBACK))
4473 /* COW or write-notify handled on pte level: split pmd. */
4474 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4476 return VM_FAULT_FALLBACK;
4479 #ifdef CONFIG_FINEGRAINED_THP
4480 vm_fault_t wp_huge_pte(struct vm_fault *vmf, pte_t orig_pte);
4481 #endif /* CONFIG_FINEGRAINED_THP */
4483 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4485 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
4486 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4487 /* No support for anonymous transparent PUD pages yet */
4488 if (vma_is_anonymous(vmf->vma))
4490 if (vmf->vma->vm_ops->huge_fault) {
4491 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4493 if (!(ret & VM_FAULT_FALLBACK))
4497 /* COW or write-notify not handled on PUD level: split pud.*/
4498 __split_huge_pud(vmf->vma, vmf->pud, vmf->address);
4499 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4500 return VM_FAULT_FALLBACK;
4503 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4505 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4506 /* No support for anonymous transparent PUD pages yet */
4507 if (vma_is_anonymous(vmf->vma))
4508 return VM_FAULT_FALLBACK;
4509 if (vmf->vma->vm_ops->huge_fault)
4510 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4511 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4512 return VM_FAULT_FALLBACK;
4516 * These routines also need to handle stuff like marking pages dirty
4517 * and/or accessed for architectures that don't do it in hardware (most
4518 * RISC architectures). The early dirtying is also good on the i386.
4520 * There is also a hook called "update_mmu_cache()" that architectures
4521 * with external mmu caches can use to update those (ie the Sparc or
4522 * PowerPC hashed page tables that act as extended TLBs).
4524 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
4525 * concurrent faults).
4527 * The mmap_lock may have been released depending on flags and our return value.
4528 * See filemap_fault() and __lock_page_or_retry().
4530 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4534 if (unlikely(pmd_none(*vmf->pmd))) {
4536 * Leave __pte_alloc() until later: because vm_ops->fault may
4537 * want to allocate huge page, and if we expose page table
4538 * for an instant, it will be difficult to retract from
4539 * concurrent faults and from rmap lookups.
4543 /* See comment in pte_alloc_one_map() */
4544 if (pmd_devmap_trans_unstable(vmf->pmd))
4547 * A regular pmd is established and it can't morph into a huge
4548 * pmd from under us anymore at this point because we hold the
4549 * mmap_lock read mode and khugepaged takes it in write mode.
4550 * So now it's safe to run pte_offset_map().
4552 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4553 vmf->orig_pte = *vmf->pte;
4556 * some architectures can have larger ptes than wordsize,
4557 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4558 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4559 * accesses. The code below just needs a consistent view
4560 * for the ifs and we later double check anyway with the
4561 * ptl lock held. So here a barrier will do.
4564 if (pte_none(vmf->orig_pte)) {
4565 pte_unmap(vmf->pte);
4571 if (vma_is_anonymous(vmf->vma))
4572 return do_anonymous_page(vmf);
4574 return do_fault(vmf);
4577 if (!pte_present(vmf->orig_pte))
4578 return do_swap_page(vmf);
4580 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4581 return do_numa_page(vmf);
4583 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4584 spin_lock(vmf->ptl);
4585 entry = vmf->orig_pte;
4586 if (unlikely(!pte_same(*vmf->pte, entry))) {
4587 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
4590 if (vmf->flags & FAULT_FLAG_WRITE) {
4591 if (!pte_write(entry)) {
4592 int ret = arch_do_wp_page(vmf, entry);
4594 if (!(ret & VM_FAULT_FALLBACK))
4596 return do_wp_page(vmf);
4598 if (arch_huge_pte_set_accessed(vmf, entry))
4600 entry = pte_mkdirty(entry);
4602 entry = pte_mkyoung(entry);
4603 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4604 vmf->flags & FAULT_FLAG_WRITE)) {
4605 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4607 /* Skip spurious TLB flush for retried page fault */
4608 if (vmf->flags & FAULT_FLAG_TRIED)
4611 * This is needed only for protection faults but the arch code
4612 * is not yet telling us if this is a protection fault or not.
4613 * This still avoids useless tlb flushes for .text page faults
4616 if (vmf->flags & FAULT_FLAG_WRITE)
4617 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4620 pte_unmap_unlock(vmf->pte, vmf->ptl);
4625 * By the time we get here, we already hold the mm semaphore
4627 * The mmap_lock may have been released depending on flags and our
4628 * return value. See filemap_fault() and __lock_page_or_retry().
4630 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
4631 unsigned long address, unsigned int flags)
4633 struct vm_fault vmf = {
4635 .address = address & PAGE_MASK,
4637 .pgoff = linear_page_index(vma, address),
4638 .gfp_mask = __get_fault_gfp_mask(vma),
4640 unsigned int dirty = flags & FAULT_FLAG_WRITE;
4641 struct mm_struct *mm = vma->vm_mm;
4646 pgd = pgd_offset(mm, address);
4647 p4d = p4d_alloc(mm, pgd, address);
4649 return VM_FAULT_OOM;
4651 vmf.pud = pud_alloc(mm, p4d, address);
4653 return VM_FAULT_OOM;
4655 if (pud_none(*vmf.pud) && __transparent_hugepage_enabled(vma)) {
4656 ret = create_huge_pud(&vmf);
4657 if (!(ret & VM_FAULT_FALLBACK))
4660 pud_t orig_pud = *vmf.pud;
4663 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4665 /* NUMA case for anonymous PUDs would go here */
4667 if (dirty && !pud_write(orig_pud)) {
4668 ret = wp_huge_pud(&vmf, orig_pud);
4669 if (!(ret & VM_FAULT_FALLBACK))
4672 huge_pud_set_accessed(&vmf, orig_pud);
4678 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4680 return VM_FAULT_OOM;
4682 /* Huge pud page fault raced with pmd_alloc? */
4683 if (pud_trans_unstable(vmf.pud))
4686 if (pmd_none(*vmf.pmd) && __transparent_hugepage_enabled(vma)) {
4687 ret = create_huge_pmd(&vmf);
4688 if (!(ret & VM_FAULT_FALLBACK))
4691 pmd_t orig_pmd = *vmf.pmd;
4694 if (unlikely(is_swap_pmd(orig_pmd))) {
4695 VM_BUG_ON(thp_migration_supported() &&
4696 !is_pmd_migration_entry(orig_pmd));
4697 if (is_pmd_migration_entry(orig_pmd))
4698 pmd_migration_entry_wait(mm, vmf.pmd);
4701 if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
4702 if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
4703 return do_huge_pmd_numa_page(&vmf, orig_pmd);
4705 if (dirty && !pmd_write(orig_pmd)) {
4706 ret = wp_huge_pmd(&vmf, orig_pmd);
4707 if (!(ret & VM_FAULT_FALLBACK))
4710 huge_pmd_set_accessed(&vmf, orig_pmd);
4716 return handle_pte_fault(&vmf);
4720 * mm_account_fault - Do page fault accountings
4722 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting
4723 * of perf event counters, but we'll still do the per-task accounting to
4724 * the task who triggered this page fault.
4725 * @address: the faulted address.
4726 * @flags: the fault flags.
4727 * @ret: the fault retcode.
4729 * This will take care of most of the page fault accountings. Meanwhile, it
4730 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
4731 * updates. However note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
4732 * still be in per-arch page fault handlers at the entry of page fault.
4734 static inline void mm_account_fault(struct pt_regs *regs,
4735 unsigned long address, unsigned int flags,
4741 * We don't do accounting for some specific faults:
4743 * - Unsuccessful faults (e.g. when the address wasn't valid). That
4744 * includes arch_vma_access_permitted() failing before reaching here.
4745 * So this is not a "this many hardware page faults" counter. We
4746 * should use the hw profiling for that.
4748 * - Incomplete faults (VM_FAULT_RETRY). They will only be counted
4749 * once they're completed.
4751 if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY))
4755 * We define the fault as a major fault when the final successful fault
4756 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
4757 * handle it immediately previously).
4759 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
4767 * If the fault is done for GUP, regs will be NULL. We only do the
4768 * accounting for the per thread fault counters who triggered the
4769 * fault, and we skip the perf event updates.
4775 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
4777 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
4781 * By the time we get here, we already hold the mm semaphore
4783 * The mmap_lock may have been released depending on flags and our
4784 * return value. See filemap_fault() and __lock_page_or_retry().
4786 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4787 unsigned int flags, struct pt_regs *regs)
4791 __set_current_state(TASK_RUNNING);
4793 count_vm_event(PGFAULT);
4794 count_memcg_event_mm(vma->vm_mm, PGFAULT);
4796 /* do counter updates before entering really critical section. */
4797 check_sync_rss_stat(current);
4799 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4800 flags & FAULT_FLAG_INSTRUCTION,
4801 flags & FAULT_FLAG_REMOTE))
4802 return VM_FAULT_SIGSEGV;
4805 * Enable the memcg OOM handling for faults triggered in user
4806 * space. Kernel faults are handled more gracefully.
4808 if (flags & FAULT_FLAG_USER)
4809 mem_cgroup_enter_user_fault();
4811 if (unlikely(is_vm_hugetlb_page(vma)))
4812 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4814 ret = __handle_mm_fault(vma, address, flags);
4816 if (flags & FAULT_FLAG_USER) {
4817 mem_cgroup_exit_user_fault();
4819 * The task may have entered a memcg OOM situation but
4820 * if the allocation error was handled gracefully (no
4821 * VM_FAULT_OOM), there is no need to kill anything.
4822 * Just clean up the OOM state peacefully.
4824 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4825 mem_cgroup_oom_synchronize(false);
4828 mm_account_fault(regs, address, flags, ret);
4832 EXPORT_SYMBOL_GPL(handle_mm_fault);
4834 #ifndef __PAGETABLE_P4D_FOLDED
4836 * Allocate p4d page table.
4837 * We've already handled the fast-path in-line.
4839 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4841 p4d_t *new = p4d_alloc_one(mm, address);
4845 smp_wmb(); /* See comment in __pte_alloc */
4847 spin_lock(&mm->page_table_lock);
4848 if (pgd_present(*pgd)) /* Another has populated it */
4851 pgd_populate(mm, pgd, new);
4852 spin_unlock(&mm->page_table_lock);
4855 #endif /* __PAGETABLE_P4D_FOLDED */
4857 #ifndef __PAGETABLE_PUD_FOLDED
4859 * Allocate page upper directory.
4860 * We've already handled the fast-path in-line.
4862 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4864 pud_t *new = pud_alloc_one(mm, address);
4868 smp_wmb(); /* See comment in __pte_alloc */
4870 spin_lock(&mm->page_table_lock);
4871 if (!p4d_present(*p4d)) {
4873 p4d_populate(mm, p4d, new);
4874 } else /* Another has populated it */
4876 spin_unlock(&mm->page_table_lock);
4879 #endif /* __PAGETABLE_PUD_FOLDED */
4881 #ifndef __PAGETABLE_PMD_FOLDED
4883 * Allocate page middle directory.
4884 * We've already handled the fast-path in-line.
4886 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4889 pmd_t *new = pmd_alloc_one(mm, address);
4893 smp_wmb(); /* See comment in __pte_alloc */
4895 ptl = pud_lock(mm, pud);
4896 if (!pud_present(*pud)) {
4898 pud_populate(mm, pud, new);
4899 } else /* Another has populated it */
4904 #endif /* __PAGETABLE_PMD_FOLDED */
4906 int follow_invalidate_pte(struct mm_struct *mm, unsigned long address,
4907 struct mmu_notifier_range *range, pte_t **ptepp,
4908 pmd_t **pmdpp, spinlock_t **ptlp)
4916 pgd = pgd_offset(mm, address);
4917 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4920 p4d = p4d_offset(pgd, address);
4921 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4924 pud = pud_offset(p4d, address);
4925 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4928 pmd = pmd_offset(pud, address);
4929 VM_BUG_ON(pmd_trans_huge(*pmd));
4931 if (pmd_huge(*pmd)) {
4936 mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0,
4937 NULL, mm, address & PMD_MASK,
4938 (address & PMD_MASK) + PMD_SIZE);
4939 mmu_notifier_invalidate_range_start(range);
4941 *ptlp = pmd_lock(mm, pmd);
4942 if (pmd_huge(*pmd)) {
4948 mmu_notifier_invalidate_range_end(range);
4951 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4955 mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
4956 address & PAGE_MASK,
4957 (address & PAGE_MASK) + PAGE_SIZE);
4958 mmu_notifier_invalidate_range_start(range);
4960 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4961 if (!pte_present(*ptep))
4966 pte_unmap_unlock(ptep, *ptlp);
4968 mmu_notifier_invalidate_range_end(range);
4974 * follow_pte - look up PTE at a user virtual address
4975 * @mm: the mm_struct of the target address space
4976 * @address: user virtual address
4977 * @ptepp: location to store found PTE
4978 * @ptlp: location to store the lock for the PTE
4980 * On a successful return, the pointer to the PTE is stored in @ptepp;
4981 * the corresponding lock is taken and its location is stored in @ptlp.
4982 * The contents of the PTE are only stable until @ptlp is released;
4983 * any further use, if any, must be protected against invalidation
4984 * with MMU notifiers.
4986 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore
4987 * should be taken for read.
4989 * KVM uses this function. While it is arguably less bad than ``follow_pfn``,
4990 * it is not a good general-purpose API.
4992 * Return: zero on success, -ve otherwise.
4994 int follow_pte(struct mm_struct *mm, unsigned long address,
4995 pte_t **ptepp, spinlock_t **ptlp)
4997 return follow_invalidate_pte(mm, address, NULL, ptepp, NULL, ptlp);
4999 EXPORT_SYMBOL_GPL(follow_pte);
5002 * follow_pfn - look up PFN at a user virtual address
5003 * @vma: memory mapping
5004 * @address: user virtual address
5005 * @pfn: location to store found PFN
5007 * Only IO mappings and raw PFN mappings are allowed.
5009 * This function does not allow the caller to read the permissions
5010 * of the PTE. Do not use it.
5012 * Return: zero and the pfn at @pfn on success, -ve otherwise.
5014 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
5021 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5024 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
5027 *pfn = pte_pfn(*ptep);
5028 pte_unmap_unlock(ptep, ptl);
5031 EXPORT_SYMBOL(follow_pfn);
5033 #ifdef CONFIG_HAVE_IOREMAP_PROT
5034 int follow_phys(struct vm_area_struct *vma,
5035 unsigned long address, unsigned int flags,
5036 unsigned long *prot, resource_size_t *phys)
5042 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5045 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
5049 if ((flags & FOLL_WRITE) && !pte_write(pte))
5052 *prot = pgprot_val(pte_pgprot(pte));
5053 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5057 pte_unmap_unlock(ptep, ptl);
5062 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
5063 void *buf, int len, int write)
5065 resource_size_t phys_addr;
5066 unsigned long prot = 0;
5067 void __iomem *maddr;
5068 int offset = addr & (PAGE_SIZE-1);
5070 if (follow_phys(vma, addr, write, &prot, &phys_addr))
5073 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
5078 memcpy_toio(maddr + offset, buf, len);
5080 memcpy_fromio(buf, maddr + offset, len);
5085 EXPORT_SYMBOL_GPL(generic_access_phys);
5089 * Access another process' address space as given in mm. If non-NULL, use the
5090 * given task for page fault accounting.
5092 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
5093 unsigned long addr, void *buf, int len, unsigned int gup_flags)
5095 struct vm_area_struct *vma;
5096 void *old_buf = buf;
5097 int write = gup_flags & FOLL_WRITE;
5099 if (mmap_read_lock_killable(mm))
5102 /* ignore errors, just check how much was successfully transferred */
5104 int bytes, ret, offset;
5106 struct page *page = NULL;
5108 ret = get_user_pages_remote(mm, addr, 1,
5109 gup_flags, &page, &vma, NULL);
5111 #ifndef CONFIG_HAVE_IOREMAP_PROT
5115 * Check if this is a VM_IO | VM_PFNMAP VMA, which
5116 * we can access using slightly different code.
5118 vma = find_vma(mm, addr);
5119 if (!vma || vma->vm_start > addr)
5121 if (vma->vm_ops && vma->vm_ops->access)
5122 ret = vma->vm_ops->access(vma, addr, buf,
5130 offset = addr & (PAGE_SIZE-1);
5131 if (bytes > PAGE_SIZE-offset)
5132 bytes = PAGE_SIZE-offset;
5136 copy_to_user_page(vma, page, addr,
5137 maddr + offset, buf, bytes);
5138 set_page_dirty_lock(page);
5140 copy_from_user_page(vma, page, addr,
5141 buf, maddr + offset, bytes);
5150 mmap_read_unlock(mm);
5152 return buf - old_buf;
5156 * access_remote_vm - access another process' address space
5157 * @mm: the mm_struct of the target address space
5158 * @addr: start address to access
5159 * @buf: source or destination buffer
5160 * @len: number of bytes to transfer
5161 * @gup_flags: flags modifying lookup behaviour
5163 * The caller must hold a reference on @mm.
5165 * Return: number of bytes copied from source to destination.
5167 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
5168 void *buf, int len, unsigned int gup_flags)
5170 return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
5174 * Access another process' address space.
5175 * Source/target buffer must be kernel space,
5176 * Do not walk the page table directly, use get_user_pages
5178 int access_process_vm(struct task_struct *tsk, unsigned long addr,
5179 void *buf, int len, unsigned int gup_flags)
5181 struct mm_struct *mm;
5184 mm = get_task_mm(tsk);
5188 ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
5194 EXPORT_SYMBOL_GPL(access_process_vm);
5197 * Print the name of a VMA.
5199 void print_vma_addr(char *prefix, unsigned long ip)
5201 struct mm_struct *mm = current->mm;
5202 struct vm_area_struct *vma;
5205 * we might be running from an atomic context so we cannot sleep
5207 if (!mmap_read_trylock(mm))
5210 vma = find_vma(mm, ip);
5211 if (vma && vma->vm_file) {
5212 struct file *f = vma->vm_file;
5213 char *buf = (char *)__get_free_page(GFP_NOWAIT);
5217 p = file_path(f, buf, PAGE_SIZE);
5220 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
5222 vma->vm_end - vma->vm_start);
5223 free_page((unsigned long)buf);
5226 mmap_read_unlock(mm);
5229 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5230 void __might_fault(const char *file, int line)
5233 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
5234 * holding the mmap_lock, this is safe because kernel memory doesn't
5235 * get paged out, therefore we'll never actually fault, and the
5236 * below annotations will generate false positives.
5238 if (uaccess_kernel())
5240 if (pagefault_disabled())
5242 __might_sleep(file, line, 0);
5243 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5245 might_lock_read(¤t->mm->mmap_lock);
5248 EXPORT_SYMBOL(__might_fault);
5251 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
5253 * Process all subpages of the specified huge page with the specified
5254 * operation. The target subpage will be processed last to keep its
5257 static inline void process_huge_page(
5258 unsigned long addr_hint, unsigned int pages_per_huge_page,
5259 void (*process_subpage)(unsigned long addr, int idx, void *arg),
5263 unsigned long addr = addr_hint &
5264 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5266 /* Process target subpage last to keep its cache lines hot */
5268 n = (addr_hint - addr) / PAGE_SIZE;
5269 if (2 * n <= pages_per_huge_page) {
5270 /* If target subpage in first half of huge page */
5273 /* Process subpages at the end of huge page */
5274 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
5276 process_subpage(addr + i * PAGE_SIZE, i, arg);
5279 /* If target subpage in second half of huge page */
5280 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
5281 l = pages_per_huge_page - n;
5282 /* Process subpages at the begin of huge page */
5283 for (i = 0; i < base; i++) {
5285 process_subpage(addr + i * PAGE_SIZE, i, arg);
5289 * Process remaining subpages in left-right-left-right pattern
5290 * towards the target subpage
5292 for (i = 0; i < l; i++) {
5293 int left_idx = base + i;
5294 int right_idx = base + 2 * l - 1 - i;
5297 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
5299 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
5303 static void clear_gigantic_page(struct page *page,
5305 unsigned int pages_per_huge_page)
5308 struct page *p = page;
5311 for (i = 0; i < pages_per_huge_page;
5312 i++, p = mem_map_next(p, page, i)) {
5314 clear_user_highpage(p, addr + i * PAGE_SIZE);
5318 static void clear_subpage(unsigned long addr, int idx, void *arg)
5320 struct page *page = arg;
5322 clear_user_highpage(page + idx, addr);
5325 void clear_huge_page(struct page *page,
5326 unsigned long addr_hint, unsigned int pages_per_huge_page)
5328 unsigned long addr = addr_hint &
5329 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5331 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5332 clear_gigantic_page(page, addr, pages_per_huge_page);
5336 process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
5339 static void copy_user_gigantic_page(struct page *dst, struct page *src,
5341 struct vm_area_struct *vma,
5342 unsigned int pages_per_huge_page)
5345 struct page *dst_base = dst;
5346 struct page *src_base = src;
5348 for (i = 0; i < pages_per_huge_page; ) {
5350 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
5353 dst = mem_map_next(dst, dst_base, i);
5354 src = mem_map_next(src, src_base, i);
5358 struct copy_subpage_arg {
5361 struct vm_area_struct *vma;
5364 static void copy_subpage(unsigned long addr, int idx, void *arg)
5366 struct copy_subpage_arg *copy_arg = arg;
5368 copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
5369 addr, copy_arg->vma);
5372 void copy_user_huge_page(struct page *dst, struct page *src,
5373 unsigned long addr_hint, struct vm_area_struct *vma,
5374 unsigned int pages_per_huge_page)
5376 unsigned long addr = addr_hint &
5377 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5378 struct copy_subpage_arg arg = {
5384 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5385 copy_user_gigantic_page(dst, src, addr, vma,
5386 pages_per_huge_page);
5390 process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
5393 long copy_huge_page_from_user(struct page *dst_page,
5394 const void __user *usr_src,
5395 unsigned int pages_per_huge_page,
5396 bool allow_pagefault)
5398 void *src = (void *)usr_src;
5400 unsigned long i, rc = 0;
5401 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
5402 struct page *subpage = dst_page;
5404 for (i = 0; i < pages_per_huge_page;
5405 i++, subpage = mem_map_next(subpage, dst_page, i)) {
5406 if (allow_pagefault)
5407 page_kaddr = kmap(subpage);
5409 page_kaddr = kmap_atomic(subpage);
5410 rc = copy_from_user(page_kaddr,
5411 (const void __user *)(src + i * PAGE_SIZE),
5413 if (allow_pagefault)
5416 kunmap_atomic(page_kaddr);
5418 ret_val -= (PAGE_SIZE - rc);
5426 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
5428 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
5430 static struct kmem_cache *page_ptl_cachep;
5432 void __init ptlock_cache_init(void)
5434 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
5438 bool ptlock_alloc(struct page *page)
5442 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
5449 void ptlock_free(struct page *page)
5451 kmem_cache_free(page_ptl_cachep, page->ptl);