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>
86 #include "pgalloc-track.h"
89 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
90 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
94 unsigned long max_mapnr;
95 EXPORT_SYMBOL(max_mapnr);
98 EXPORT_SYMBOL(mem_map);
102 * A number of key systems in x86 including ioremap() rely on the assumption
103 * that high_memory defines the upper bound on direct map memory, then end
104 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and
105 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
109 EXPORT_SYMBOL(high_memory);
112 * Randomize the address space (stacks, mmaps, brk, etc.).
114 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
115 * as ancient (libc5 based) binaries can segfault. )
117 int randomize_va_space __read_mostly =
118 #ifdef CONFIG_COMPAT_BRK
124 #ifndef arch_faults_on_old_pte
125 static inline bool arch_faults_on_old_pte(void)
128 * Those arches which don't have hw access flag feature need to
129 * implement their own helper. By default, "true" means pagefault
130 * will be hit on old pte.
136 #ifndef arch_wants_old_prefaulted_pte
137 static inline bool arch_wants_old_prefaulted_pte(void)
140 * Transitioning a PTE from 'old' to 'young' can be expensive on
141 * some architectures, even if it's performed in hardware. By
142 * default, "false" means prefaulted entries will be 'young'.
148 static int __init disable_randmaps(char *s)
150 randomize_va_space = 0;
153 __setup("norandmaps", disable_randmaps);
155 unsigned long zero_pfn __read_mostly;
156 EXPORT_SYMBOL(zero_pfn);
158 unsigned long highest_memmap_pfn __read_mostly;
161 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
163 static int __init init_zero_pfn(void)
165 zero_pfn = page_to_pfn(ZERO_PAGE(0));
168 early_initcall(init_zero_pfn);
170 void mm_trace_rss_stat(struct mm_struct *mm, int member, long count)
172 trace_rss_stat(mm, member, count);
175 #if defined(SPLIT_RSS_COUNTING)
177 void sync_mm_rss(struct mm_struct *mm)
181 for (i = 0; i < NR_MM_COUNTERS; i++) {
182 if (current->rss_stat.count[i]) {
183 add_mm_counter(mm, i, current->rss_stat.count[i]);
184 current->rss_stat.count[i] = 0;
187 current->rss_stat.events = 0;
190 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
192 struct task_struct *task = current;
194 if (likely(task->mm == mm))
195 task->rss_stat.count[member] += val;
197 add_mm_counter(mm, member, val);
199 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
200 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
202 /* sync counter once per 64 page faults */
203 #define TASK_RSS_EVENTS_THRESH (64)
204 static void check_sync_rss_stat(struct task_struct *task)
206 if (unlikely(task != current))
208 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
209 sync_mm_rss(task->mm);
211 #else /* SPLIT_RSS_COUNTING */
213 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
214 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
216 static void check_sync_rss_stat(struct task_struct *task)
220 #endif /* SPLIT_RSS_COUNTING */
223 * Note: this doesn't free the actual pages themselves. That
224 * has been handled earlier when unmapping all the memory regions.
226 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
229 pgtable_t token = pmd_pgtable(*pmd);
231 pte_free_tlb(tlb, token, addr);
232 mm_dec_nr_ptes(tlb->mm);
235 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
236 unsigned long addr, unsigned long end,
237 unsigned long floor, unsigned long ceiling)
244 pmd = pmd_offset(pud, addr);
246 next = pmd_addr_end(addr, end);
247 if (pmd_none_or_clear_bad(pmd))
249 free_pte_range(tlb, pmd, addr);
250 } while (pmd++, addr = next, addr != end);
260 if (end - 1 > ceiling - 1)
263 pmd = pmd_offset(pud, start);
265 pmd_free_tlb(tlb, pmd, start);
266 mm_dec_nr_pmds(tlb->mm);
269 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
270 unsigned long addr, unsigned long end,
271 unsigned long floor, unsigned long ceiling)
278 pud = pud_offset(p4d, addr);
280 next = pud_addr_end(addr, end);
281 if (pud_none_or_clear_bad(pud))
283 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
284 } while (pud++, addr = next, addr != end);
294 if (end - 1 > ceiling - 1)
297 pud = pud_offset(p4d, start);
299 pud_free_tlb(tlb, pud, start);
300 mm_dec_nr_puds(tlb->mm);
303 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
304 unsigned long addr, unsigned long end,
305 unsigned long floor, unsigned long ceiling)
312 p4d = p4d_offset(pgd, addr);
314 next = p4d_addr_end(addr, end);
315 if (p4d_none_or_clear_bad(p4d))
317 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
318 } while (p4d++, addr = next, addr != end);
324 ceiling &= PGDIR_MASK;
328 if (end - 1 > ceiling - 1)
331 p4d = p4d_offset(pgd, start);
333 p4d_free_tlb(tlb, p4d, start);
337 * This function frees user-level page tables of a process.
339 void free_pgd_range(struct mmu_gather *tlb,
340 unsigned long addr, unsigned long end,
341 unsigned long floor, unsigned long ceiling)
347 * The next few lines have given us lots of grief...
349 * Why are we testing PMD* at this top level? Because often
350 * there will be no work to do at all, and we'd prefer not to
351 * go all the way down to the bottom just to discover that.
353 * Why all these "- 1"s? Because 0 represents both the bottom
354 * of the address space and the top of it (using -1 for the
355 * top wouldn't help much: the masks would do the wrong thing).
356 * The rule is that addr 0 and floor 0 refer to the bottom of
357 * the address space, but end 0 and ceiling 0 refer to the top
358 * Comparisons need to use "end - 1" and "ceiling - 1" (though
359 * that end 0 case should be mythical).
361 * Wherever addr is brought up or ceiling brought down, we must
362 * be careful to reject "the opposite 0" before it confuses the
363 * subsequent tests. But what about where end is brought down
364 * by PMD_SIZE below? no, end can't go down to 0 there.
366 * Whereas we round start (addr) and ceiling down, by different
367 * masks at different levels, in order to test whether a table
368 * now has no other vmas using it, so can be freed, we don't
369 * bother to round floor or end up - the tests don't need that.
383 if (end - 1 > ceiling - 1)
388 * We add page table cache pages with PAGE_SIZE,
389 * (see pte_free_tlb()), flush the tlb if we need
391 tlb_change_page_size(tlb, PAGE_SIZE);
392 pgd = pgd_offset(tlb->mm, addr);
394 next = pgd_addr_end(addr, end);
395 if (pgd_none_or_clear_bad(pgd))
397 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
398 } while (pgd++, addr = next, addr != end);
401 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
402 unsigned long floor, unsigned long ceiling)
405 struct vm_area_struct *next = vma->vm_next;
406 unsigned long addr = vma->vm_start;
409 * Hide vma from rmap and truncate_pagecache before freeing
412 unlink_anon_vmas(vma);
413 unlink_file_vma(vma);
415 if (is_vm_hugetlb_page(vma)) {
416 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
417 floor, next ? next->vm_start : ceiling);
420 * Optimization: gather nearby vmas into one call down
422 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
423 && !is_vm_hugetlb_page(next)) {
426 unlink_anon_vmas(vma);
427 unlink_file_vma(vma);
429 free_pgd_range(tlb, addr, vma->vm_end,
430 floor, next ? next->vm_start : ceiling);
436 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
439 pgtable_t new = pte_alloc_one(mm);
444 * Ensure all pte setup (eg. pte page lock and page clearing) are
445 * visible before the pte is made visible to other CPUs by being
446 * put into page tables.
448 * The other side of the story is the pointer chasing in the page
449 * table walking code (when walking the page table without locking;
450 * ie. most of the time). Fortunately, these data accesses consist
451 * of a chain of data-dependent loads, meaning most CPUs (alpha
452 * being the notable exception) will already guarantee loads are
453 * seen in-order. See the alpha page table accessors for the
454 * smp_rmb() barriers in page table walking code.
456 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
458 ptl = pmd_lock(mm, pmd);
459 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
461 pmd_populate(mm, pmd, new);
470 int __pte_alloc_kernel(pmd_t *pmd)
472 pte_t *new = pte_alloc_one_kernel(&init_mm);
476 smp_wmb(); /* See comment in __pte_alloc */
478 spin_lock(&init_mm.page_table_lock);
479 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
480 pmd_populate_kernel(&init_mm, pmd, new);
483 spin_unlock(&init_mm.page_table_lock);
485 pte_free_kernel(&init_mm, new);
489 static inline void init_rss_vec(int *rss)
491 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
494 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
498 if (current->mm == mm)
500 for (i = 0; i < NR_MM_COUNTERS; i++)
502 add_mm_counter(mm, i, rss[i]);
506 * This function is called to print an error when a bad pte
507 * is found. For example, we might have a PFN-mapped pte in
508 * a region that doesn't allow it.
510 * The calling function must still handle the error.
512 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
513 pte_t pte, struct page *page)
515 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
516 p4d_t *p4d = p4d_offset(pgd, addr);
517 pud_t *pud = pud_offset(p4d, addr);
518 pmd_t *pmd = pmd_offset(pud, addr);
519 struct address_space *mapping;
521 static unsigned long resume;
522 static unsigned long nr_shown;
523 static unsigned long nr_unshown;
526 * Allow a burst of 60 reports, then keep quiet for that minute;
527 * or allow a steady drip of one report per second.
529 if (nr_shown == 60) {
530 if (time_before(jiffies, resume)) {
535 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
542 resume = jiffies + 60 * HZ;
544 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
545 index = linear_page_index(vma, addr);
547 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
549 (long long)pte_val(pte), (long long)pmd_val(*pmd));
551 dump_page(page, "bad pte");
552 pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n",
553 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
554 pr_alert("file:%pD fault:%ps mmap:%ps readpage:%ps\n",
556 vma->vm_ops ? vma->vm_ops->fault : NULL,
557 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
558 mapping ? mapping->a_ops->readpage : NULL);
560 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
564 * vm_normal_page -- This function gets the "struct page" associated with a pte.
566 * "Special" mappings do not wish to be associated with a "struct page" (either
567 * it doesn't exist, or it exists but they don't want to touch it). In this
568 * case, NULL is returned here. "Normal" mappings do have a struct page.
570 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
571 * pte bit, in which case this function is trivial. Secondly, an architecture
572 * may not have a spare pte bit, which requires a more complicated scheme,
575 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
576 * special mapping (even if there are underlying and valid "struct pages").
577 * COWed pages of a VM_PFNMAP are always normal.
579 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
580 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
581 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
582 * mapping will always honor the rule
584 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
586 * And for normal mappings this is false.
588 * This restricts such mappings to be a linear translation from virtual address
589 * to pfn. To get around this restriction, we allow arbitrary mappings so long
590 * as the vma is not a COW mapping; in that case, we know that all ptes are
591 * special (because none can have been COWed).
594 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
596 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
597 * page" backing, however the difference is that _all_ pages with a struct
598 * page (that is, those where pfn_valid is true) are refcounted and considered
599 * normal pages by the VM. The disadvantage is that pages are refcounted
600 * (which can be slower and simply not an option for some PFNMAP users). The
601 * advantage is that we don't have to follow the strict linearity rule of
602 * PFNMAP mappings in order to support COWable mappings.
605 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
608 unsigned long pfn = pte_pfn(pte);
610 if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
611 if (likely(!pte_special(pte)))
613 if (vma->vm_ops && vma->vm_ops->find_special_page)
614 return vma->vm_ops->find_special_page(vma, addr);
615 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
617 if (is_zero_pfn(pfn))
622 print_bad_pte(vma, addr, pte, NULL);
626 /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
628 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
629 if (vma->vm_flags & VM_MIXEDMAP) {
635 off = (addr - vma->vm_start) >> PAGE_SHIFT;
636 if (pfn == vma->vm_pgoff + off)
638 if (!is_cow_mapping(vma->vm_flags))
643 if (is_zero_pfn(pfn))
647 if (unlikely(pfn > highest_memmap_pfn)) {
648 print_bad_pte(vma, addr, pte, NULL);
653 * NOTE! We still have PageReserved() pages in the page tables.
654 * eg. VDSO mappings can cause them to exist.
657 return pfn_to_page(pfn);
660 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
661 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
664 unsigned long pfn = pmd_pfn(pmd);
667 * There is no pmd_special() but there may be special pmds, e.g.
668 * in a direct-access (dax) mapping, so let's just replicate the
669 * !CONFIG_ARCH_HAS_PTE_SPECIAL case from vm_normal_page() here.
671 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
672 if (vma->vm_flags & VM_MIXEDMAP) {
678 off = (addr - vma->vm_start) >> PAGE_SHIFT;
679 if (pfn == vma->vm_pgoff + off)
681 if (!is_cow_mapping(vma->vm_flags))
688 if (is_huge_zero_pmd(pmd))
690 if (unlikely(pfn > highest_memmap_pfn))
694 * NOTE! We still have PageReserved() pages in the page tables.
695 * eg. VDSO mappings can cause them to exist.
698 return pfn_to_page(pfn);
703 * copy one vm_area from one task to the other. Assumes the page tables
704 * already present in the new task to be cleared in the whole range
705 * covered by this vma.
709 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
710 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *dst_vma,
711 struct vm_area_struct *src_vma, unsigned long addr, int *rss)
713 unsigned long vm_flags = dst_vma->vm_flags;
714 pte_t pte = *src_pte;
716 swp_entry_t entry = pte_to_swp_entry(pte);
718 if (likely(!non_swap_entry(entry))) {
719 if (swap_duplicate(entry) < 0)
722 /* make sure dst_mm is on swapoff's mmlist. */
723 if (unlikely(list_empty(&dst_mm->mmlist))) {
724 spin_lock(&mmlist_lock);
725 if (list_empty(&dst_mm->mmlist))
726 list_add(&dst_mm->mmlist,
728 spin_unlock(&mmlist_lock);
731 } else if (is_migration_entry(entry)) {
732 page = pfn_swap_entry_to_page(entry);
734 rss[mm_counter(page)]++;
736 if (is_writable_migration_entry(entry) &&
737 is_cow_mapping(vm_flags)) {
739 * COW mappings require pages in both
740 * parent and child to be set to read.
742 entry = make_readable_migration_entry(
744 pte = swp_entry_to_pte(entry);
745 if (pte_swp_soft_dirty(*src_pte))
746 pte = pte_swp_mksoft_dirty(pte);
747 if (pte_swp_uffd_wp(*src_pte))
748 pte = pte_swp_mkuffd_wp(pte);
749 set_pte_at(src_mm, addr, src_pte, pte);
751 } else if (is_device_private_entry(entry)) {
752 page = pfn_swap_entry_to_page(entry);
755 * Update rss count even for unaddressable pages, as
756 * they should treated just like normal pages in this
759 * We will likely want to have some new rss counters
760 * for unaddressable pages, at some point. But for now
761 * keep things as they are.
764 rss[mm_counter(page)]++;
765 page_dup_rmap(page, false);
768 * We do not preserve soft-dirty information, because so
769 * far, checkpoint/restore is the only feature that
770 * requires that. And checkpoint/restore does not work
771 * when a device driver is involved (you cannot easily
772 * save and restore device driver state).
774 if (is_writable_device_private_entry(entry) &&
775 is_cow_mapping(vm_flags)) {
776 entry = make_readable_device_private_entry(
778 pte = swp_entry_to_pte(entry);
779 if (pte_swp_uffd_wp(*src_pte))
780 pte = pte_swp_mkuffd_wp(pte);
781 set_pte_at(src_mm, addr, src_pte, pte);
784 if (!userfaultfd_wp(dst_vma))
785 pte = pte_swp_clear_uffd_wp(pte);
786 set_pte_at(dst_mm, addr, dst_pte, pte);
791 * Copy a present and normal page if necessary.
793 * NOTE! The usual case is that this doesn't need to do
794 * anything, and can just return a positive value. That
795 * will let the caller know that it can just increase
796 * the page refcount and re-use the pte the traditional
799 * But _if_ we need to copy it because it needs to be
800 * pinned in the parent (and the child should get its own
801 * copy rather than just a reference to the same page),
802 * we'll do that here and return zero to let the caller
805 * And if we need a pre-allocated page but don't yet have
806 * one, return a negative error to let the preallocation
807 * code know so that it can do so outside the page table
811 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
812 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
813 struct page **prealloc, pte_t pte, struct page *page)
815 struct page *new_page;
818 * What we want to do is to check whether this page may
819 * have been pinned by the parent process. If so,
820 * instead of wrprotect the pte on both sides, we copy
821 * the page immediately so that we'll always guarantee
822 * the pinned page won't be randomly replaced in the
825 * The page pinning checks are just "has this mm ever
826 * seen pinning", along with the (inexact) check of
827 * the page count. That might give false positives for
828 * for pinning, but it will work correctly.
830 if (likely(!page_needs_cow_for_dma(src_vma, page)))
833 new_page = *prealloc;
838 * We have a prealloc page, all good! Take it
839 * over and copy the page & arm it.
842 copy_user_highpage(new_page, page, addr, src_vma);
843 __SetPageUptodate(new_page);
844 page_add_new_anon_rmap(new_page, dst_vma, addr, false);
845 lru_cache_add_inactive_or_unevictable(new_page, dst_vma);
846 rss[mm_counter(new_page)]++;
848 /* All done, just insert the new page copy in the child */
849 pte = mk_pte(new_page, dst_vma->vm_page_prot);
850 pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
851 if (userfaultfd_pte_wp(dst_vma, *src_pte))
852 /* Uffd-wp needs to be delivered to dest pte as well */
853 pte = pte_wrprotect(pte_mkuffd_wp(pte));
854 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
859 * Copy one pte. Returns 0 if succeeded, or -EAGAIN if one preallocated page
860 * is required to copy this pte.
863 copy_present_pte(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
864 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
865 struct page **prealloc)
867 struct mm_struct *src_mm = src_vma->vm_mm;
868 unsigned long vm_flags = src_vma->vm_flags;
869 pte_t pte = *src_pte;
872 page = vm_normal_page(src_vma, addr, pte);
876 retval = copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
877 addr, rss, prealloc, pte, page);
882 page_dup_rmap(page, false);
883 rss[mm_counter(page)]++;
887 * If it's a COW mapping, write protect it both
888 * in the parent and the child
890 if (is_cow_mapping(vm_flags) && pte_write(pte)) {
891 ptep_set_wrprotect(src_mm, addr, src_pte);
892 pte = pte_wrprotect(pte);
896 * If it's a shared mapping, mark it clean in
899 if (vm_flags & VM_SHARED)
900 pte = pte_mkclean(pte);
901 pte = pte_mkold(pte);
903 if (!userfaultfd_wp(dst_vma))
904 pte = pte_clear_uffd_wp(pte);
906 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
910 static inline struct page *
911 page_copy_prealloc(struct mm_struct *src_mm, struct vm_area_struct *vma,
914 struct page *new_page;
916 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, addr);
920 if (mem_cgroup_charge(new_page, src_mm, GFP_KERNEL)) {
924 cgroup_throttle_swaprate(new_page, GFP_KERNEL);
930 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
931 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
934 struct mm_struct *dst_mm = dst_vma->vm_mm;
935 struct mm_struct *src_mm = src_vma->vm_mm;
936 pte_t *orig_src_pte, *orig_dst_pte;
937 pte_t *src_pte, *dst_pte;
938 spinlock_t *src_ptl, *dst_ptl;
939 int progress, ret = 0;
940 int rss[NR_MM_COUNTERS];
941 swp_entry_t entry = (swp_entry_t){0};
942 struct page *prealloc = NULL;
948 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
953 src_pte = pte_offset_map(src_pmd, addr);
954 src_ptl = pte_lockptr(src_mm, src_pmd);
955 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
956 orig_src_pte = src_pte;
957 orig_dst_pte = dst_pte;
958 arch_enter_lazy_mmu_mode();
962 * We are holding two locks at this point - either of them
963 * could generate latencies in another task on another CPU.
965 if (progress >= 32) {
967 if (need_resched() ||
968 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
971 if (pte_none(*src_pte)) {
975 if (unlikely(!pte_present(*src_pte))) {
976 entry.val = copy_nonpresent_pte(dst_mm, src_mm,
985 /* copy_present_pte() will clear `*prealloc' if consumed */
986 ret = copy_present_pte(dst_vma, src_vma, dst_pte, src_pte,
987 addr, rss, &prealloc);
989 * If we need a pre-allocated page for this pte, drop the
990 * locks, allocate, and try again.
992 if (unlikely(ret == -EAGAIN))
994 if (unlikely(prealloc)) {
996 * pre-alloc page cannot be reused by next time so as
997 * to strictly follow mempolicy (e.g., alloc_page_vma()
998 * will allocate page according to address). This
999 * could only happen if one pinned pte changed.
1005 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
1007 arch_leave_lazy_mmu_mode();
1008 spin_unlock(src_ptl);
1009 pte_unmap(orig_src_pte);
1010 add_mm_rss_vec(dst_mm, rss);
1011 pte_unmap_unlock(orig_dst_pte, dst_ptl);
1015 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
1021 WARN_ON_ONCE(ret != -EAGAIN);
1022 prealloc = page_copy_prealloc(src_mm, src_vma, addr);
1025 /* We've captured and resolved the error. Reset, try again. */
1031 if (unlikely(prealloc))
1037 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1038 pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1041 struct mm_struct *dst_mm = dst_vma->vm_mm;
1042 struct mm_struct *src_mm = src_vma->vm_mm;
1043 pmd_t *src_pmd, *dst_pmd;
1046 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1049 src_pmd = pmd_offset(src_pud, addr);
1051 next = pmd_addr_end(addr, end);
1052 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1053 || pmd_devmap(*src_pmd)) {
1055 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
1056 err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd,
1057 addr, dst_vma, src_vma);
1064 if (pmd_none_or_clear_bad(src_pmd))
1066 if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
1069 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1074 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1075 p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
1078 struct mm_struct *dst_mm = dst_vma->vm_mm;
1079 struct mm_struct *src_mm = src_vma->vm_mm;
1080 pud_t *src_pud, *dst_pud;
1083 dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1086 src_pud = pud_offset(src_p4d, addr);
1088 next = pud_addr_end(addr, end);
1089 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1092 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
1093 err = copy_huge_pud(dst_mm, src_mm,
1094 dst_pud, src_pud, addr, src_vma);
1101 if (pud_none_or_clear_bad(src_pud))
1103 if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
1106 } while (dst_pud++, src_pud++, addr = next, addr != end);
1111 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1112 pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
1115 struct mm_struct *dst_mm = dst_vma->vm_mm;
1116 p4d_t *src_p4d, *dst_p4d;
1119 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1122 src_p4d = p4d_offset(src_pgd, addr);
1124 next = p4d_addr_end(addr, end);
1125 if (p4d_none_or_clear_bad(src_p4d))
1127 if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
1130 } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1135 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1137 pgd_t *src_pgd, *dst_pgd;
1139 unsigned long addr = src_vma->vm_start;
1140 unsigned long end = src_vma->vm_end;
1141 struct mm_struct *dst_mm = dst_vma->vm_mm;
1142 struct mm_struct *src_mm = src_vma->vm_mm;
1143 struct mmu_notifier_range range;
1148 * Don't copy ptes where a page fault will fill them correctly.
1149 * Fork becomes much lighter when there are big shared or private
1150 * readonly mappings. The tradeoff is that copy_page_range is more
1151 * efficient than faulting.
1153 if (!(src_vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1157 if (is_vm_hugetlb_page(src_vma))
1158 return copy_hugetlb_page_range(dst_mm, src_mm, src_vma);
1160 if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
1162 * We do not free on error cases below as remove_vma
1163 * gets called on error from higher level routine
1165 ret = track_pfn_copy(src_vma);
1171 * We need to invalidate the secondary MMU mappings only when
1172 * there could be a permission downgrade on the ptes of the
1173 * parent mm. And a permission downgrade will only happen if
1174 * is_cow_mapping() returns true.
1176 is_cow = is_cow_mapping(src_vma->vm_flags);
1179 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
1180 0, src_vma, src_mm, addr, end);
1181 mmu_notifier_invalidate_range_start(&range);
1183 * Disabling preemption is not needed for the write side, as
1184 * the read side doesn't spin, but goes to the mmap_lock.
1186 * Use the raw variant of the seqcount_t write API to avoid
1187 * lockdep complaining about preemptibility.
1189 mmap_assert_write_locked(src_mm);
1190 raw_write_seqcount_begin(&src_mm->write_protect_seq);
1194 dst_pgd = pgd_offset(dst_mm, addr);
1195 src_pgd = pgd_offset(src_mm, addr);
1197 next = pgd_addr_end(addr, end);
1198 if (pgd_none_or_clear_bad(src_pgd))
1200 if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
1205 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1208 raw_write_seqcount_end(&src_mm->write_protect_seq);
1209 mmu_notifier_invalidate_range_end(&range);
1214 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1215 struct vm_area_struct *vma, pmd_t *pmd,
1216 unsigned long addr, unsigned long end,
1217 struct zap_details *details)
1219 struct mm_struct *mm = tlb->mm;
1220 int force_flush = 0;
1221 int rss[NR_MM_COUNTERS];
1227 tlb_change_page_size(tlb, PAGE_SIZE);
1230 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1232 flush_tlb_batched_pending(mm);
1233 arch_enter_lazy_mmu_mode();
1236 if (pte_none(ptent))
1242 if (pte_present(ptent)) {
1245 page = vm_normal_page(vma, addr, ptent);
1246 if (unlikely(details) && page) {
1248 * unmap_shared_mapping_pages() wants to
1249 * invalidate cache without truncating:
1250 * unmap shared but keep private pages.
1252 if (details->check_mapping &&
1253 details->check_mapping != page_rmapping(page))
1256 ptent = ptep_get_and_clear_full(mm, addr, pte,
1258 tlb_remove_tlb_entry(tlb, pte, addr);
1259 if (unlikely(!page))
1262 if (!PageAnon(page)) {
1263 if (pte_dirty(ptent)) {
1265 set_page_dirty(page);
1267 if (pte_young(ptent) &&
1268 likely(!(vma->vm_flags & VM_SEQ_READ)))
1269 mark_page_accessed(page);
1271 rss[mm_counter(page)]--;
1272 page_remove_rmap(page, false);
1273 if (unlikely(page_mapcount(page) < 0))
1274 print_bad_pte(vma, addr, ptent, page);
1275 if (unlikely(__tlb_remove_page(tlb, page))) {
1283 entry = pte_to_swp_entry(ptent);
1284 if (is_device_private_entry(entry)) {
1285 struct page *page = pfn_swap_entry_to_page(entry);
1287 if (unlikely(details && details->check_mapping)) {
1289 * unmap_shared_mapping_pages() wants to
1290 * invalidate cache without truncating:
1291 * unmap shared but keep private pages.
1293 if (details->check_mapping !=
1294 page_rmapping(page))
1298 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1299 rss[mm_counter(page)]--;
1300 page_remove_rmap(page, false);
1305 /* If details->check_mapping, we leave swap entries. */
1306 if (unlikely(details))
1309 if (!non_swap_entry(entry))
1311 else if (is_migration_entry(entry)) {
1314 page = pfn_swap_entry_to_page(entry);
1315 rss[mm_counter(page)]--;
1317 if (unlikely(!free_swap_and_cache(entry)))
1318 print_bad_pte(vma, addr, ptent, NULL);
1319 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1320 } while (pte++, addr += PAGE_SIZE, addr != end);
1322 add_mm_rss_vec(mm, rss);
1323 arch_leave_lazy_mmu_mode();
1325 /* Do the actual TLB flush before dropping ptl */
1327 tlb_flush_mmu_tlbonly(tlb);
1328 pte_unmap_unlock(start_pte, ptl);
1331 * If we forced a TLB flush (either due to running out of
1332 * batch buffers or because we needed to flush dirty TLB
1333 * entries before releasing the ptl), free the batched
1334 * memory too. Restart if we didn't do everything.
1349 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1350 struct vm_area_struct *vma, pud_t *pud,
1351 unsigned long addr, unsigned long end,
1352 struct zap_details *details)
1357 pmd = pmd_offset(pud, addr);
1359 next = pmd_addr_end(addr, end);
1360 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1361 if (next - addr != HPAGE_PMD_SIZE)
1362 __split_huge_pmd(vma, pmd, addr, false, NULL);
1363 else if (zap_huge_pmd(tlb, vma, pmd, addr))
1366 } else if (details && details->single_page &&
1367 PageTransCompound(details->single_page) &&
1368 next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) {
1369 spinlock_t *ptl = pmd_lock(tlb->mm, pmd);
1371 * Take and drop THP pmd lock so that we cannot return
1372 * prematurely, while zap_huge_pmd() has cleared *pmd,
1373 * but not yet decremented compound_mapcount().
1379 * Here there can be other concurrent MADV_DONTNEED or
1380 * trans huge page faults running, and if the pmd is
1381 * none or trans huge it can change under us. This is
1382 * because MADV_DONTNEED holds the mmap_lock in read
1385 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1387 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1390 } while (pmd++, addr = next, addr != end);
1395 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1396 struct vm_area_struct *vma, p4d_t *p4d,
1397 unsigned long addr, unsigned long end,
1398 struct zap_details *details)
1403 pud = pud_offset(p4d, addr);
1405 next = pud_addr_end(addr, end);
1406 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1407 if (next - addr != HPAGE_PUD_SIZE) {
1408 mmap_assert_locked(tlb->mm);
1409 split_huge_pud(vma, pud, addr);
1410 } else if (zap_huge_pud(tlb, vma, pud, addr))
1414 if (pud_none_or_clear_bad(pud))
1416 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1419 } while (pud++, addr = next, addr != end);
1424 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1425 struct vm_area_struct *vma, pgd_t *pgd,
1426 unsigned long addr, unsigned long end,
1427 struct zap_details *details)
1432 p4d = p4d_offset(pgd, addr);
1434 next = p4d_addr_end(addr, end);
1435 if (p4d_none_or_clear_bad(p4d))
1437 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1438 } while (p4d++, addr = next, addr != end);
1443 void unmap_page_range(struct mmu_gather *tlb,
1444 struct vm_area_struct *vma,
1445 unsigned long addr, unsigned long end,
1446 struct zap_details *details)
1451 BUG_ON(addr >= end);
1452 tlb_start_vma(tlb, vma);
1453 pgd = pgd_offset(vma->vm_mm, addr);
1455 next = pgd_addr_end(addr, end);
1456 if (pgd_none_or_clear_bad(pgd))
1458 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1459 } while (pgd++, addr = next, addr != end);
1460 tlb_end_vma(tlb, vma);
1464 static void unmap_single_vma(struct mmu_gather *tlb,
1465 struct vm_area_struct *vma, unsigned long start_addr,
1466 unsigned long end_addr,
1467 struct zap_details *details)
1469 unsigned long start = max(vma->vm_start, start_addr);
1472 if (start >= vma->vm_end)
1474 end = min(vma->vm_end, end_addr);
1475 if (end <= vma->vm_start)
1479 uprobe_munmap(vma, start, end);
1481 if (unlikely(vma->vm_flags & VM_PFNMAP))
1482 untrack_pfn(vma, 0, 0);
1485 if (unlikely(is_vm_hugetlb_page(vma))) {
1487 * It is undesirable to test vma->vm_file as it
1488 * should be non-null for valid hugetlb area.
1489 * However, vm_file will be NULL in the error
1490 * cleanup path of mmap_region. When
1491 * hugetlbfs ->mmap method fails,
1492 * mmap_region() nullifies vma->vm_file
1493 * before calling this function to clean up.
1494 * Since no pte has actually been setup, it is
1495 * safe to do nothing in this case.
1498 i_mmap_lock_write(vma->vm_file->f_mapping);
1499 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1500 i_mmap_unlock_write(vma->vm_file->f_mapping);
1503 unmap_page_range(tlb, vma, start, end, details);
1508 * unmap_vmas - unmap a range of memory covered by a list of vma's
1509 * @tlb: address of the caller's struct mmu_gather
1510 * @vma: the starting vma
1511 * @start_addr: virtual address at which to start unmapping
1512 * @end_addr: virtual address at which to end unmapping
1514 * Unmap all pages in the vma list.
1516 * Only addresses between `start' and `end' will be unmapped.
1518 * The VMA list must be sorted in ascending virtual address order.
1520 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1521 * range after unmap_vmas() returns. So the only responsibility here is to
1522 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1523 * drops the lock and schedules.
1525 void unmap_vmas(struct mmu_gather *tlb,
1526 struct vm_area_struct *vma, unsigned long start_addr,
1527 unsigned long end_addr)
1529 struct mmu_notifier_range range;
1531 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
1532 start_addr, end_addr);
1533 mmu_notifier_invalidate_range_start(&range);
1534 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1535 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1536 mmu_notifier_invalidate_range_end(&range);
1540 * zap_page_range - remove user pages in a given range
1541 * @vma: vm_area_struct holding the applicable pages
1542 * @start: starting address of pages to zap
1543 * @size: number of bytes to zap
1545 * Caller must protect the VMA list
1547 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1550 struct mmu_notifier_range range;
1551 struct mmu_gather tlb;
1554 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1555 start, start + size);
1556 tlb_gather_mmu(&tlb, vma->vm_mm);
1557 update_hiwater_rss(vma->vm_mm);
1558 mmu_notifier_invalidate_range_start(&range);
1559 for ( ; vma && vma->vm_start < range.end; vma = vma->vm_next)
1560 unmap_single_vma(&tlb, vma, start, range.end, NULL);
1561 mmu_notifier_invalidate_range_end(&range);
1562 tlb_finish_mmu(&tlb);
1566 * zap_page_range_single - remove user pages in a given range
1567 * @vma: vm_area_struct holding the applicable pages
1568 * @address: starting address of pages to zap
1569 * @size: number of bytes to zap
1570 * @details: details of shared cache invalidation
1572 * The range must fit into one VMA.
1574 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1575 unsigned long size, struct zap_details *details)
1577 struct mmu_notifier_range range;
1578 struct mmu_gather tlb;
1581 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1582 address, address + size);
1583 tlb_gather_mmu(&tlb, vma->vm_mm);
1584 update_hiwater_rss(vma->vm_mm);
1585 mmu_notifier_invalidate_range_start(&range);
1586 unmap_single_vma(&tlb, vma, address, range.end, details);
1587 mmu_notifier_invalidate_range_end(&range);
1588 tlb_finish_mmu(&tlb);
1592 * zap_vma_ptes - remove ptes mapping the vma
1593 * @vma: vm_area_struct holding ptes to be zapped
1594 * @address: starting address of pages to zap
1595 * @size: number of bytes to zap
1597 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1599 * The entire address range must be fully contained within the vma.
1602 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1605 if (address < vma->vm_start || address + size > vma->vm_end ||
1606 !(vma->vm_flags & VM_PFNMAP))
1609 zap_page_range_single(vma, address, size, NULL);
1611 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1613 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
1620 pgd = pgd_offset(mm, addr);
1621 p4d = p4d_alloc(mm, pgd, addr);
1624 pud = pud_alloc(mm, p4d, addr);
1627 pmd = pmd_alloc(mm, pud, addr);
1631 VM_BUG_ON(pmd_trans_huge(*pmd));
1635 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1638 pmd_t *pmd = walk_to_pmd(mm, addr);
1642 return pte_alloc_map_lock(mm, pmd, addr, ptl);
1645 static int validate_page_before_insert(struct page *page)
1647 if (PageAnon(page) || PageSlab(page) || page_has_type(page))
1649 flush_dcache_page(page);
1653 static int insert_page_into_pte_locked(struct mm_struct *mm, pte_t *pte,
1654 unsigned long addr, struct page *page, pgprot_t prot)
1656 if (!pte_none(*pte))
1658 /* Ok, finally just insert the thing.. */
1660 inc_mm_counter_fast(mm, mm_counter_file(page));
1661 page_add_file_rmap(page, false);
1662 set_pte_at(mm, addr, pte, mk_pte(page, prot));
1667 * This is the old fallback for page remapping.
1669 * For historical reasons, it only allows reserved pages. Only
1670 * old drivers should use this, and they needed to mark their
1671 * pages reserved for the old functions anyway.
1673 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1674 struct page *page, pgprot_t prot)
1676 struct mm_struct *mm = vma->vm_mm;
1681 retval = validate_page_before_insert(page);
1685 pte = get_locked_pte(mm, addr, &ptl);
1688 retval = insert_page_into_pte_locked(mm, pte, addr, page, prot);
1689 pte_unmap_unlock(pte, ptl);
1695 static int insert_page_in_batch_locked(struct mm_struct *mm, pte_t *pte,
1696 unsigned long addr, struct page *page, pgprot_t prot)
1700 if (!page_count(page))
1702 err = validate_page_before_insert(page);
1705 return insert_page_into_pte_locked(mm, pte, addr, page, prot);
1708 /* insert_pages() amortizes the cost of spinlock operations
1709 * when inserting pages in a loop. Arch *must* define pte_index.
1711 static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
1712 struct page **pages, unsigned long *num, pgprot_t prot)
1715 pte_t *start_pte, *pte;
1716 spinlock_t *pte_lock;
1717 struct mm_struct *const mm = vma->vm_mm;
1718 unsigned long curr_page_idx = 0;
1719 unsigned long remaining_pages_total = *num;
1720 unsigned long pages_to_write_in_pmd;
1724 pmd = walk_to_pmd(mm, addr);
1728 pages_to_write_in_pmd = min_t(unsigned long,
1729 remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
1731 /* Allocate the PTE if necessary; takes PMD lock once only. */
1733 if (pte_alloc(mm, pmd))
1736 while (pages_to_write_in_pmd) {
1738 const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
1740 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
1741 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
1742 int err = insert_page_in_batch_locked(mm, pte,
1743 addr, pages[curr_page_idx], prot);
1744 if (unlikely(err)) {
1745 pte_unmap_unlock(start_pte, pte_lock);
1747 remaining_pages_total -= pte_idx;
1753 pte_unmap_unlock(start_pte, pte_lock);
1754 pages_to_write_in_pmd -= batch_size;
1755 remaining_pages_total -= batch_size;
1757 if (remaining_pages_total)
1761 *num = remaining_pages_total;
1764 #endif /* ifdef pte_index */
1767 * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
1768 * @vma: user vma to map to
1769 * @addr: target start user address of these pages
1770 * @pages: source kernel pages
1771 * @num: in: number of pages to map. out: number of pages that were *not*
1772 * mapped. (0 means all pages were successfully mapped).
1774 * Preferred over vm_insert_page() when inserting multiple pages.
1776 * In case of error, we may have mapped a subset of the provided
1777 * pages. It is the caller's responsibility to account for this case.
1779 * The same restrictions apply as in vm_insert_page().
1781 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
1782 struct page **pages, unsigned long *num)
1785 const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
1787 if (addr < vma->vm_start || end_addr >= vma->vm_end)
1789 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1790 BUG_ON(mmap_read_trylock(vma->vm_mm));
1791 BUG_ON(vma->vm_flags & VM_PFNMAP);
1792 vma->vm_flags |= VM_MIXEDMAP;
1794 /* Defer page refcount checking till we're about to map that page. */
1795 return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
1797 unsigned long idx = 0, pgcount = *num;
1800 for (; idx < pgcount; ++idx) {
1801 err = vm_insert_page(vma, addr + (PAGE_SIZE * idx), pages[idx]);
1805 *num = pgcount - idx;
1807 #endif /* ifdef pte_index */
1809 EXPORT_SYMBOL(vm_insert_pages);
1812 * vm_insert_page - insert single page into user vma
1813 * @vma: user vma to map to
1814 * @addr: target user address of this page
1815 * @page: source kernel page
1817 * This allows drivers to insert individual pages they've allocated
1820 * The page has to be a nice clean _individual_ kernel allocation.
1821 * If you allocate a compound page, you need to have marked it as
1822 * such (__GFP_COMP), or manually just split the page up yourself
1823 * (see split_page()).
1825 * NOTE! Traditionally this was done with "remap_pfn_range()" which
1826 * took an arbitrary page protection parameter. This doesn't allow
1827 * that. Your vma protection will have to be set up correctly, which
1828 * means that if you want a shared writable mapping, you'd better
1829 * ask for a shared writable mapping!
1831 * The page does not need to be reserved.
1833 * Usually this function is called from f_op->mmap() handler
1834 * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
1835 * Caller must set VM_MIXEDMAP on vma if it wants to call this
1836 * function from other places, for example from page-fault handler.
1838 * Return: %0 on success, negative error code otherwise.
1840 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1843 if (addr < vma->vm_start || addr >= vma->vm_end)
1845 if (!page_count(page))
1847 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1848 BUG_ON(mmap_read_trylock(vma->vm_mm));
1849 BUG_ON(vma->vm_flags & VM_PFNMAP);
1850 vma->vm_flags |= VM_MIXEDMAP;
1852 return insert_page(vma, addr, page, vma->vm_page_prot);
1854 EXPORT_SYMBOL(vm_insert_page);
1857 * __vm_map_pages - maps range of kernel pages into user vma
1858 * @vma: user vma to map to
1859 * @pages: pointer to array of source kernel pages
1860 * @num: number of pages in page array
1861 * @offset: user's requested vm_pgoff
1863 * This allows drivers to map range of kernel pages into a user vma.
1865 * Return: 0 on success and error code otherwise.
1867 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
1868 unsigned long num, unsigned long offset)
1870 unsigned long count = vma_pages(vma);
1871 unsigned long uaddr = vma->vm_start;
1874 /* Fail if the user requested offset is beyond the end of the object */
1878 /* Fail if the user requested size exceeds available object size */
1879 if (count > num - offset)
1882 for (i = 0; i < count; i++) {
1883 ret = vm_insert_page(vma, uaddr, pages[offset + i]);
1893 * vm_map_pages - maps range of kernel pages starts with non zero offset
1894 * @vma: user vma to map to
1895 * @pages: pointer to array of source kernel pages
1896 * @num: number of pages in page array
1898 * Maps an object consisting of @num pages, catering for the user's
1899 * requested vm_pgoff
1901 * If we fail to insert any page into the vma, the function will return
1902 * immediately leaving any previously inserted pages present. Callers
1903 * from the mmap handler may immediately return the error as their caller
1904 * will destroy the vma, removing any successfully inserted pages. Other
1905 * callers should make their own arrangements for calling unmap_region().
1907 * Context: Process context. Called by mmap handlers.
1908 * Return: 0 on success and error code otherwise.
1910 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
1913 return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
1915 EXPORT_SYMBOL(vm_map_pages);
1918 * vm_map_pages_zero - map range of kernel pages starts with zero offset
1919 * @vma: user vma to map to
1920 * @pages: pointer to array of source kernel pages
1921 * @num: number of pages in page array
1923 * Similar to vm_map_pages(), except that it explicitly sets the offset
1924 * to 0. This function is intended for the drivers that did not consider
1927 * Context: Process context. Called by mmap handlers.
1928 * Return: 0 on success and error code otherwise.
1930 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
1933 return __vm_map_pages(vma, pages, num, 0);
1935 EXPORT_SYMBOL(vm_map_pages_zero);
1937 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1938 pfn_t pfn, pgprot_t prot, bool mkwrite)
1940 struct mm_struct *mm = vma->vm_mm;
1944 pte = get_locked_pte(mm, addr, &ptl);
1946 return VM_FAULT_OOM;
1947 if (!pte_none(*pte)) {
1950 * For read faults on private mappings the PFN passed
1951 * in may not match the PFN we have mapped if the
1952 * mapped PFN is a writeable COW page. In the mkwrite
1953 * case we are creating a writable PTE for a shared
1954 * mapping and we expect the PFNs to match. If they
1955 * don't match, we are likely racing with block
1956 * allocation and mapping invalidation so just skip the
1959 if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
1960 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
1963 entry = pte_mkyoung(*pte);
1964 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1965 if (ptep_set_access_flags(vma, addr, pte, entry, 1))
1966 update_mmu_cache(vma, addr, pte);
1971 /* Ok, finally just insert the thing.. */
1972 if (pfn_t_devmap(pfn))
1973 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
1975 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1978 entry = pte_mkyoung(entry);
1979 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1982 set_pte_at(mm, addr, pte, entry);
1983 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1986 pte_unmap_unlock(pte, ptl);
1987 return VM_FAULT_NOPAGE;
1991 * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
1992 * @vma: user vma to map to
1993 * @addr: target user address of this page
1994 * @pfn: source kernel pfn
1995 * @pgprot: pgprot flags for the inserted page
1997 * This is exactly like vmf_insert_pfn(), except that it allows drivers
1998 * to override pgprot on a per-page basis.
2000 * This only makes sense for IO mappings, and it makes no sense for
2001 * COW mappings. In general, using multiple vmas is preferable;
2002 * vmf_insert_pfn_prot should only be used if using multiple VMAs is
2005 * See vmf_insert_mixed_prot() for a discussion of the implication of using
2006 * a value of @pgprot different from that of @vma->vm_page_prot.
2008 * Context: Process context. May allocate using %GFP_KERNEL.
2009 * Return: vm_fault_t value.
2011 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
2012 unsigned long pfn, pgprot_t pgprot)
2015 * Technically, architectures with pte_special can avoid all these
2016 * restrictions (same for remap_pfn_range). However we would like
2017 * consistency in testing and feature parity among all, so we should
2018 * try to keep these invariants in place for everybody.
2020 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2021 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2022 (VM_PFNMAP|VM_MIXEDMAP));
2023 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2024 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2026 if (addr < vma->vm_start || addr >= vma->vm_end)
2027 return VM_FAULT_SIGBUS;
2029 if (!pfn_modify_allowed(pfn, pgprot))
2030 return VM_FAULT_SIGBUS;
2032 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
2034 return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
2037 EXPORT_SYMBOL(vmf_insert_pfn_prot);
2040 * vmf_insert_pfn - insert single pfn into user vma
2041 * @vma: user vma to map to
2042 * @addr: target user address of this page
2043 * @pfn: source kernel pfn
2045 * Similar to vm_insert_page, this allows drivers to insert individual pages
2046 * they've allocated into a user vma. Same comments apply.
2048 * This function should only be called from a vm_ops->fault handler, and
2049 * in that case the handler should return the result of this function.
2051 * vma cannot be a COW mapping.
2053 * As this is called only for pages that do not currently exist, we
2054 * do not need to flush old virtual caches or the TLB.
2056 * Context: Process context. May allocate using %GFP_KERNEL.
2057 * Return: vm_fault_t value.
2059 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2062 return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
2064 EXPORT_SYMBOL(vmf_insert_pfn);
2066 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn)
2068 /* these checks mirror the abort conditions in vm_normal_page */
2069 if (vma->vm_flags & VM_MIXEDMAP)
2071 if (pfn_t_devmap(pfn))
2073 if (pfn_t_special(pfn))
2075 if (is_zero_pfn(pfn_t_to_pfn(pfn)))
2080 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
2081 unsigned long addr, pfn_t pfn, pgprot_t pgprot,
2086 BUG_ON(!vm_mixed_ok(vma, pfn));
2088 if (addr < vma->vm_start || addr >= vma->vm_end)
2089 return VM_FAULT_SIGBUS;
2091 track_pfn_insert(vma, &pgprot, pfn);
2093 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
2094 return VM_FAULT_SIGBUS;
2097 * If we don't have pte special, then we have to use the pfn_valid()
2098 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2099 * refcount the page if pfn_valid is true (hence insert_page rather
2100 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
2101 * without pte special, it would there be refcounted as a normal page.
2103 if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
2104 !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
2108 * At this point we are committed to insert_page()
2109 * regardless of whether the caller specified flags that
2110 * result in pfn_t_has_page() == false.
2112 page = pfn_to_page(pfn_t_to_pfn(pfn));
2113 err = insert_page(vma, addr, page, pgprot);
2115 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2119 return VM_FAULT_OOM;
2120 if (err < 0 && err != -EBUSY)
2121 return VM_FAULT_SIGBUS;
2123 return VM_FAULT_NOPAGE;
2127 * vmf_insert_mixed_prot - insert single pfn into user vma with specified pgprot
2128 * @vma: user vma to map to
2129 * @addr: target user address of this page
2130 * @pfn: source kernel pfn
2131 * @pgprot: pgprot flags for the inserted page
2133 * This is exactly like vmf_insert_mixed(), except that it allows drivers
2134 * to override pgprot on a per-page basis.
2136 * Typically this function should be used by drivers to set caching- and
2137 * encryption bits different than those of @vma->vm_page_prot, because
2138 * the caching- or encryption mode may not be known at mmap() time.
2139 * This is ok as long as @vma->vm_page_prot is not used by the core vm
2140 * to set caching and encryption bits for those vmas (except for COW pages).
2141 * This is ensured by core vm only modifying these page table entries using
2142 * functions that don't touch caching- or encryption bits, using pte_modify()
2143 * if needed. (See for example mprotect()).
2144 * Also when new page-table entries are created, this is only done using the
2145 * fault() callback, and never using the value of vma->vm_page_prot,
2146 * except for page-table entries that point to anonymous pages as the result
2149 * Context: Process context. May allocate using %GFP_KERNEL.
2150 * Return: vm_fault_t value.
2152 vm_fault_t vmf_insert_mixed_prot(struct vm_area_struct *vma, unsigned long addr,
2153 pfn_t pfn, pgprot_t pgprot)
2155 return __vm_insert_mixed(vma, addr, pfn, pgprot, false);
2157 EXPORT_SYMBOL(vmf_insert_mixed_prot);
2159 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2162 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, false);
2164 EXPORT_SYMBOL(vmf_insert_mixed);
2167 * If the insertion of PTE failed because someone else already added a
2168 * different entry in the mean time, we treat that as success as we assume
2169 * the same entry was actually inserted.
2171 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2172 unsigned long addr, pfn_t pfn)
2174 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, true);
2176 EXPORT_SYMBOL(vmf_insert_mixed_mkwrite);
2179 * maps a range of physical memory into the requested pages. the old
2180 * mappings are removed. any references to nonexistent pages results
2181 * in null mappings (currently treated as "copy-on-access")
2183 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2184 unsigned long addr, unsigned long end,
2185 unsigned long pfn, pgprot_t prot)
2187 pte_t *pte, *mapped_pte;
2191 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2194 arch_enter_lazy_mmu_mode();
2196 BUG_ON(!pte_none(*pte));
2197 if (!pfn_modify_allowed(pfn, prot)) {
2201 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2203 } while (pte++, addr += PAGE_SIZE, addr != end);
2204 arch_leave_lazy_mmu_mode();
2205 pte_unmap_unlock(mapped_pte, ptl);
2209 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2210 unsigned long addr, unsigned long end,
2211 unsigned long pfn, pgprot_t prot)
2217 pfn -= addr >> PAGE_SHIFT;
2218 pmd = pmd_alloc(mm, pud, addr);
2221 VM_BUG_ON(pmd_trans_huge(*pmd));
2223 next = pmd_addr_end(addr, end);
2224 err = remap_pte_range(mm, pmd, addr, next,
2225 pfn + (addr >> PAGE_SHIFT), prot);
2228 } while (pmd++, addr = next, addr != end);
2232 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2233 unsigned long addr, unsigned long end,
2234 unsigned long pfn, pgprot_t prot)
2240 pfn -= addr >> PAGE_SHIFT;
2241 pud = pud_alloc(mm, p4d, addr);
2245 next = pud_addr_end(addr, end);
2246 err = remap_pmd_range(mm, pud, addr, next,
2247 pfn + (addr >> PAGE_SHIFT), prot);
2250 } while (pud++, addr = next, addr != end);
2254 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2255 unsigned long addr, unsigned long end,
2256 unsigned long pfn, pgprot_t prot)
2262 pfn -= addr >> PAGE_SHIFT;
2263 p4d = p4d_alloc(mm, pgd, addr);
2267 next = p4d_addr_end(addr, end);
2268 err = remap_pud_range(mm, p4d, addr, next,
2269 pfn + (addr >> PAGE_SHIFT), prot);
2272 } while (p4d++, addr = next, addr != end);
2277 * Variant of remap_pfn_range that does not call track_pfn_remap. The caller
2278 * must have pre-validated the caching bits of the pgprot_t.
2280 int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr,
2281 unsigned long pfn, unsigned long size, pgprot_t prot)
2285 unsigned long end = addr + PAGE_ALIGN(size);
2286 struct mm_struct *mm = vma->vm_mm;
2289 if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
2293 * Physically remapped pages are special. Tell the
2294 * rest of the world about it:
2295 * VM_IO tells people not to look at these pages
2296 * (accesses can have side effects).
2297 * VM_PFNMAP tells the core MM that the base pages are just
2298 * raw PFN mappings, and do not have a "struct page" associated
2301 * Disable vma merging and expanding with mremap().
2303 * Omit vma from core dump, even when VM_IO turned off.
2305 * There's a horrible special case to handle copy-on-write
2306 * behaviour that some programs depend on. We mark the "original"
2307 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2308 * See vm_normal_page() for details.
2310 if (is_cow_mapping(vma->vm_flags)) {
2311 if (addr != vma->vm_start || end != vma->vm_end)
2313 vma->vm_pgoff = pfn;
2316 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2318 BUG_ON(addr >= end);
2319 pfn -= addr >> PAGE_SHIFT;
2320 pgd = pgd_offset(mm, addr);
2321 flush_cache_range(vma, addr, end);
2323 next = pgd_addr_end(addr, end);
2324 err = remap_p4d_range(mm, pgd, addr, next,
2325 pfn + (addr >> PAGE_SHIFT), prot);
2328 } while (pgd++, addr = next, addr != end);
2334 * remap_pfn_range - remap kernel memory to userspace
2335 * @vma: user vma to map to
2336 * @addr: target page aligned user address to start at
2337 * @pfn: page frame number of kernel physical memory address
2338 * @size: size of mapping area
2339 * @prot: page protection flags for this mapping
2341 * Note: this is only safe if the mm semaphore is held when called.
2343 * Return: %0 on success, negative error code otherwise.
2345 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2346 unsigned long pfn, unsigned long size, pgprot_t prot)
2350 err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2354 err = remap_pfn_range_notrack(vma, addr, pfn, size, prot);
2356 untrack_pfn(vma, pfn, PAGE_ALIGN(size));
2359 EXPORT_SYMBOL(remap_pfn_range);
2362 * vm_iomap_memory - remap memory to userspace
2363 * @vma: user vma to map to
2364 * @start: start of the physical memory to be mapped
2365 * @len: size of area
2367 * This is a simplified io_remap_pfn_range() for common driver use. The
2368 * driver just needs to give us the physical memory range to be mapped,
2369 * we'll figure out the rest from the vma information.
2371 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2372 * whatever write-combining details or similar.
2374 * Return: %0 on success, negative error code otherwise.
2376 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2378 unsigned long vm_len, pfn, pages;
2380 /* Check that the physical memory area passed in looks valid */
2381 if (start + len < start)
2384 * You *really* shouldn't map things that aren't page-aligned,
2385 * but we've historically allowed it because IO memory might
2386 * just have smaller alignment.
2388 len += start & ~PAGE_MASK;
2389 pfn = start >> PAGE_SHIFT;
2390 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2391 if (pfn + pages < pfn)
2394 /* We start the mapping 'vm_pgoff' pages into the area */
2395 if (vma->vm_pgoff > pages)
2397 pfn += vma->vm_pgoff;
2398 pages -= vma->vm_pgoff;
2400 /* Can we fit all of the mapping? */
2401 vm_len = vma->vm_end - vma->vm_start;
2402 if (vm_len >> PAGE_SHIFT > pages)
2405 /* Ok, let it rip */
2406 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2408 EXPORT_SYMBOL(vm_iomap_memory);
2410 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2411 unsigned long addr, unsigned long end,
2412 pte_fn_t fn, void *data, bool create,
2413 pgtbl_mod_mask *mask)
2415 pte_t *pte, *mapped_pte;
2420 mapped_pte = pte = (mm == &init_mm) ?
2421 pte_alloc_kernel_track(pmd, addr, mask) :
2422 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2426 mapped_pte = pte = (mm == &init_mm) ?
2427 pte_offset_kernel(pmd, addr) :
2428 pte_offset_map_lock(mm, pmd, addr, &ptl);
2431 BUG_ON(pmd_huge(*pmd));
2433 arch_enter_lazy_mmu_mode();
2437 if (create || !pte_none(*pte)) {
2438 err = fn(pte++, addr, data);
2442 } while (addr += PAGE_SIZE, addr != end);
2444 *mask |= PGTBL_PTE_MODIFIED;
2446 arch_leave_lazy_mmu_mode();
2449 pte_unmap_unlock(mapped_pte, ptl);
2453 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2454 unsigned long addr, unsigned long end,
2455 pte_fn_t fn, void *data, bool create,
2456 pgtbl_mod_mask *mask)
2462 BUG_ON(pud_huge(*pud));
2465 pmd = pmd_alloc_track(mm, pud, addr, mask);
2469 pmd = pmd_offset(pud, addr);
2472 next = pmd_addr_end(addr, end);
2473 if (pmd_none(*pmd) && !create)
2475 if (WARN_ON_ONCE(pmd_leaf(*pmd)))
2477 if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) {
2482 err = apply_to_pte_range(mm, pmd, addr, next,
2483 fn, data, create, mask);
2486 } while (pmd++, addr = next, addr != end);
2491 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2492 unsigned long addr, unsigned long end,
2493 pte_fn_t fn, void *data, bool create,
2494 pgtbl_mod_mask *mask)
2501 pud = pud_alloc_track(mm, p4d, addr, mask);
2505 pud = pud_offset(p4d, addr);
2508 next = pud_addr_end(addr, end);
2509 if (pud_none(*pud) && !create)
2511 if (WARN_ON_ONCE(pud_leaf(*pud)))
2513 if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) {
2518 err = apply_to_pmd_range(mm, pud, addr, next,
2519 fn, data, create, mask);
2522 } while (pud++, addr = next, addr != end);
2527 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2528 unsigned long addr, unsigned long end,
2529 pte_fn_t fn, void *data, bool create,
2530 pgtbl_mod_mask *mask)
2537 p4d = p4d_alloc_track(mm, pgd, addr, mask);
2541 p4d = p4d_offset(pgd, addr);
2544 next = p4d_addr_end(addr, end);
2545 if (p4d_none(*p4d) && !create)
2547 if (WARN_ON_ONCE(p4d_leaf(*p4d)))
2549 if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) {
2554 err = apply_to_pud_range(mm, p4d, addr, next,
2555 fn, data, create, mask);
2558 } while (p4d++, addr = next, addr != end);
2563 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2564 unsigned long size, pte_fn_t fn,
2565 void *data, bool create)
2568 unsigned long start = addr, next;
2569 unsigned long end = addr + size;
2570 pgtbl_mod_mask mask = 0;
2573 if (WARN_ON(addr >= end))
2576 pgd = pgd_offset(mm, addr);
2578 next = pgd_addr_end(addr, end);
2579 if (pgd_none(*pgd) && !create)
2581 if (WARN_ON_ONCE(pgd_leaf(*pgd)))
2583 if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) {
2588 err = apply_to_p4d_range(mm, pgd, addr, next,
2589 fn, data, create, &mask);
2592 } while (pgd++, addr = next, addr != end);
2594 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
2595 arch_sync_kernel_mappings(start, start + size);
2601 * Scan a region of virtual memory, filling in page tables as necessary
2602 * and calling a provided function on each leaf page table.
2604 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2605 unsigned long size, pte_fn_t fn, void *data)
2607 return __apply_to_page_range(mm, addr, size, fn, data, true);
2609 EXPORT_SYMBOL_GPL(apply_to_page_range);
2612 * Scan a region of virtual memory, calling a provided function on
2613 * each leaf page table where it exists.
2615 * Unlike apply_to_page_range, this does _not_ fill in page tables
2616 * where they are absent.
2618 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
2619 unsigned long size, pte_fn_t fn, void *data)
2621 return __apply_to_page_range(mm, addr, size, fn, data, false);
2623 EXPORT_SYMBOL_GPL(apply_to_existing_page_range);
2626 * handle_pte_fault chooses page fault handler according to an entry which was
2627 * read non-atomically. Before making any commitment, on those architectures
2628 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2629 * parts, do_swap_page must check under lock before unmapping the pte and
2630 * proceeding (but do_wp_page is only called after already making such a check;
2631 * and do_anonymous_page can safely check later on).
2633 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2634 pte_t *page_table, pte_t orig_pte)
2637 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
2638 if (sizeof(pte_t) > sizeof(unsigned long)) {
2639 spinlock_t *ptl = pte_lockptr(mm, pmd);
2641 same = pte_same(*page_table, orig_pte);
2645 pte_unmap(page_table);
2649 static inline bool cow_user_page(struct page *dst, struct page *src,
2650 struct vm_fault *vmf)
2655 bool locked = false;
2656 struct vm_area_struct *vma = vmf->vma;
2657 struct mm_struct *mm = vma->vm_mm;
2658 unsigned long addr = vmf->address;
2661 copy_user_highpage(dst, src, addr, vma);
2666 * If the source page was a PFN mapping, we don't have
2667 * a "struct page" for it. We do a best-effort copy by
2668 * just copying from the original user address. If that
2669 * fails, we just zero-fill it. Live with it.
2671 kaddr = kmap_atomic(dst);
2672 uaddr = (void __user *)(addr & PAGE_MASK);
2675 * On architectures with software "accessed" bits, we would
2676 * take a double page fault, so mark it accessed here.
2678 if (arch_faults_on_old_pte() && !pte_young(vmf->orig_pte)) {
2681 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2683 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2685 * Other thread has already handled the fault
2686 * and update local tlb only
2688 update_mmu_tlb(vma, addr, vmf->pte);
2693 entry = pte_mkyoung(vmf->orig_pte);
2694 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2695 update_mmu_cache(vma, addr, vmf->pte);
2699 * This really shouldn't fail, because the page is there
2700 * in the page tables. But it might just be unreadable,
2701 * in which case we just give up and fill the result with
2704 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2708 /* Re-validate under PTL if the page is still mapped */
2709 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2711 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2712 /* The PTE changed under us, update local tlb */
2713 update_mmu_tlb(vma, addr, vmf->pte);
2719 * The same page can be mapped back since last copy attempt.
2720 * Try to copy again under PTL.
2722 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2724 * Give a warn in case there can be some obscure
2737 pte_unmap_unlock(vmf->pte, vmf->ptl);
2738 kunmap_atomic(kaddr);
2739 flush_dcache_page(dst);
2744 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2746 struct file *vm_file = vma->vm_file;
2749 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2752 * Special mappings (e.g. VDSO) do not have any file so fake
2753 * a default GFP_KERNEL for them.
2759 * Notify the address space that the page is about to become writable so that
2760 * it can prohibit this or wait for the page to get into an appropriate state.
2762 * We do this without the lock held, so that it can sleep if it needs to.
2764 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf)
2767 struct page *page = vmf->page;
2768 unsigned int old_flags = vmf->flags;
2770 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2772 if (vmf->vma->vm_file &&
2773 IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
2774 return VM_FAULT_SIGBUS;
2776 ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2777 /* Restore original flags so that caller is not surprised */
2778 vmf->flags = old_flags;
2779 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2781 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2783 if (!page->mapping) {
2785 return 0; /* retry */
2787 ret |= VM_FAULT_LOCKED;
2789 VM_BUG_ON_PAGE(!PageLocked(page), page);
2794 * Handle dirtying of a page in shared file mapping on a write fault.
2796 * The function expects the page to be locked and unlocks it.
2798 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
2800 struct vm_area_struct *vma = vmf->vma;
2801 struct address_space *mapping;
2802 struct page *page = vmf->page;
2804 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2806 dirtied = set_page_dirty(page);
2807 VM_BUG_ON_PAGE(PageAnon(page), page);
2809 * Take a local copy of the address_space - page.mapping may be zeroed
2810 * by truncate after unlock_page(). The address_space itself remains
2811 * pinned by vma->vm_file's reference. We rely on unlock_page()'s
2812 * release semantics to prevent the compiler from undoing this copying.
2814 mapping = page_rmapping(page);
2818 file_update_time(vma->vm_file);
2821 * Throttle page dirtying rate down to writeback speed.
2823 * mapping may be NULL here because some device drivers do not
2824 * set page.mapping but still dirty their pages
2826 * Drop the mmap_lock before waiting on IO, if we can. The file
2827 * is pinning the mapping, as per above.
2829 if ((dirtied || page_mkwrite) && mapping) {
2832 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
2833 balance_dirty_pages_ratelimited(mapping);
2836 return VM_FAULT_RETRY;
2844 * Handle write page faults for pages that can be reused in the current vma
2846 * This can happen either due to the mapping being with the VM_SHARED flag,
2847 * or due to us being the last reference standing to the page. In either
2848 * case, all we need to do here is to mark the page as writable and update
2849 * any related book-keeping.
2851 static inline void wp_page_reuse(struct vm_fault *vmf)
2852 __releases(vmf->ptl)
2854 struct vm_area_struct *vma = vmf->vma;
2855 struct page *page = vmf->page;
2858 * Clear the pages cpupid information as the existing
2859 * information potentially belongs to a now completely
2860 * unrelated process.
2863 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2865 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2866 entry = pte_mkyoung(vmf->orig_pte);
2867 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2868 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
2869 update_mmu_cache(vma, vmf->address, vmf->pte);
2870 pte_unmap_unlock(vmf->pte, vmf->ptl);
2871 count_vm_event(PGREUSE);
2875 * Handle the case of a page which we actually need to copy to a new page.
2877 * Called with mmap_lock locked and the old page referenced, but
2878 * without the ptl held.
2880 * High level logic flow:
2882 * - Allocate a page, copy the content of the old page to the new one.
2883 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2884 * - Take the PTL. If the pte changed, bail out and release the allocated page
2885 * - If the pte is still the way we remember it, update the page table and all
2886 * relevant references. This includes dropping the reference the page-table
2887 * held to the old page, as well as updating the rmap.
2888 * - In any case, unlock the PTL and drop the reference we took to the old page.
2890 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
2892 struct vm_area_struct *vma = vmf->vma;
2893 struct mm_struct *mm = vma->vm_mm;
2894 struct page *old_page = vmf->page;
2895 struct page *new_page = NULL;
2897 int page_copied = 0;
2898 struct mmu_notifier_range range;
2900 if (unlikely(anon_vma_prepare(vma)))
2903 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
2904 new_page = alloc_zeroed_user_highpage_movable(vma,
2909 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2914 if (!cow_user_page(new_page, old_page, vmf)) {
2916 * COW failed, if the fault was solved by other,
2917 * it's fine. If not, userspace would re-fault on
2918 * the same address and we will handle the fault
2919 * from the second attempt.
2928 if (mem_cgroup_charge(new_page, mm, GFP_KERNEL))
2930 cgroup_throttle_swaprate(new_page, GFP_KERNEL);
2932 __SetPageUptodate(new_page);
2934 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
2935 vmf->address & PAGE_MASK,
2936 (vmf->address & PAGE_MASK) + PAGE_SIZE);
2937 mmu_notifier_invalidate_range_start(&range);
2940 * Re-check the pte - we dropped the lock
2942 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
2943 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2945 if (!PageAnon(old_page)) {
2946 dec_mm_counter_fast(mm,
2947 mm_counter_file(old_page));
2948 inc_mm_counter_fast(mm, MM_ANONPAGES);
2951 inc_mm_counter_fast(mm, MM_ANONPAGES);
2953 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2954 entry = mk_pte(new_page, vma->vm_page_prot);
2955 entry = pte_sw_mkyoung(entry);
2956 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2959 * Clear the pte entry and flush it first, before updating the
2960 * pte with the new entry, to keep TLBs on different CPUs in
2961 * sync. This code used to set the new PTE then flush TLBs, but
2962 * that left a window where the new PTE could be loaded into
2963 * some TLBs while the old PTE remains in others.
2965 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
2966 page_add_new_anon_rmap(new_page, vma, vmf->address, false);
2967 lru_cache_add_inactive_or_unevictable(new_page, vma);
2969 * We call the notify macro here because, when using secondary
2970 * mmu page tables (such as kvm shadow page tables), we want the
2971 * new page to be mapped directly into the secondary page table.
2973 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
2974 update_mmu_cache(vma, vmf->address, vmf->pte);
2977 * Only after switching the pte to the new page may
2978 * we remove the mapcount here. Otherwise another
2979 * process may come and find the rmap count decremented
2980 * before the pte is switched to the new page, and
2981 * "reuse" the old page writing into it while our pte
2982 * here still points into it and can be read by other
2985 * The critical issue is to order this
2986 * page_remove_rmap with the ptp_clear_flush above.
2987 * Those stores are ordered by (if nothing else,)
2988 * the barrier present in the atomic_add_negative
2989 * in page_remove_rmap.
2991 * Then the TLB flush in ptep_clear_flush ensures that
2992 * no process can access the old page before the
2993 * decremented mapcount is visible. And the old page
2994 * cannot be reused until after the decremented
2995 * mapcount is visible. So transitively, TLBs to
2996 * old page will be flushed before it can be reused.
2998 page_remove_rmap(old_page, false);
3001 /* Free the old page.. */
3002 new_page = old_page;
3005 update_mmu_tlb(vma, vmf->address, vmf->pte);
3011 pte_unmap_unlock(vmf->pte, vmf->ptl);
3013 * No need to double call mmu_notifier->invalidate_range() callback as
3014 * the above ptep_clear_flush_notify() did already call it.
3016 mmu_notifier_invalidate_range_only_end(&range);
3019 * Don't let another task, with possibly unlocked vma,
3020 * keep the mlocked page.
3022 if (page_copied && (vma->vm_flags & VM_LOCKED)) {
3023 lock_page(old_page); /* LRU manipulation */
3024 if (PageMlocked(old_page))
3025 munlock_vma_page(old_page);
3026 unlock_page(old_page);
3029 free_swap_cache(old_page);
3032 return page_copied ? VM_FAULT_WRITE : 0;
3038 return VM_FAULT_OOM;
3042 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
3043 * writeable once the page is prepared
3045 * @vmf: structure describing the fault
3047 * This function handles all that is needed to finish a write page fault in a
3048 * shared mapping due to PTE being read-only once the mapped page is prepared.
3049 * It handles locking of PTE and modifying it.
3051 * The function expects the page to be locked or other protection against
3052 * concurrent faults / writeback (such as DAX radix tree locks).
3054 * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before
3055 * we acquired PTE lock.
3057 vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf)
3059 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
3060 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
3063 * We might have raced with another page fault while we released the
3064 * pte_offset_map_lock.
3066 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
3067 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
3068 pte_unmap_unlock(vmf->pte, vmf->ptl);
3069 return VM_FAULT_NOPAGE;
3076 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
3079 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
3081 struct vm_area_struct *vma = vmf->vma;
3083 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
3086 pte_unmap_unlock(vmf->pte, vmf->ptl);
3087 vmf->flags |= FAULT_FLAG_MKWRITE;
3088 ret = vma->vm_ops->pfn_mkwrite(vmf);
3089 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
3091 return finish_mkwrite_fault(vmf);
3094 return VM_FAULT_WRITE;
3097 static vm_fault_t wp_page_shared(struct vm_fault *vmf)
3098 __releases(vmf->ptl)
3100 struct vm_area_struct *vma = vmf->vma;
3101 vm_fault_t ret = VM_FAULT_WRITE;
3103 get_page(vmf->page);
3105 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
3108 pte_unmap_unlock(vmf->pte, vmf->ptl);
3109 tmp = do_page_mkwrite(vmf);
3110 if (unlikely(!tmp || (tmp &
3111 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3112 put_page(vmf->page);
3115 tmp = finish_mkwrite_fault(vmf);
3116 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3117 unlock_page(vmf->page);
3118 put_page(vmf->page);
3123 lock_page(vmf->page);
3125 ret |= fault_dirty_shared_page(vmf);
3126 put_page(vmf->page);
3132 * This routine handles present pages, when users try to write
3133 * to a shared page. It is done by copying the page to a new address
3134 * and decrementing the shared-page counter for the old page.
3136 * Note that this routine assumes that the protection checks have been
3137 * done by the caller (the low-level page fault routine in most cases).
3138 * Thus we can safely just mark it writable once we've done any necessary
3141 * We also mark the page dirty at this point even though the page will
3142 * change only once the write actually happens. This avoids a few races,
3143 * and potentially makes it more efficient.
3145 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3146 * but allow concurrent faults), with pte both mapped and locked.
3147 * We return with mmap_lock still held, but pte unmapped and unlocked.
3149 static vm_fault_t do_wp_page(struct vm_fault *vmf)
3150 __releases(vmf->ptl)
3152 struct vm_area_struct *vma = vmf->vma;
3154 if (userfaultfd_pte_wp(vma, *vmf->pte)) {
3155 pte_unmap_unlock(vmf->pte, vmf->ptl);
3156 return handle_userfault(vmf, VM_UFFD_WP);
3160 * Userfaultfd write-protect can defer flushes. Ensure the TLB
3161 * is flushed in this case before copying.
3163 if (unlikely(userfaultfd_wp(vmf->vma) &&
3164 mm_tlb_flush_pending(vmf->vma->vm_mm)))
3165 flush_tlb_page(vmf->vma, vmf->address);
3167 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
3170 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
3173 * We should not cow pages in a shared writeable mapping.
3174 * Just mark the pages writable and/or call ops->pfn_mkwrite.
3176 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3177 (VM_WRITE|VM_SHARED))
3178 return wp_pfn_shared(vmf);
3180 pte_unmap_unlock(vmf->pte, vmf->ptl);
3181 return wp_page_copy(vmf);
3185 * Take out anonymous pages first, anonymous shared vmas are
3186 * not dirty accountable.
3188 if (PageAnon(vmf->page)) {
3189 struct page *page = vmf->page;
3191 /* PageKsm() doesn't necessarily raise the page refcount */
3192 if (PageKsm(page) || page_count(page) != 1)
3194 if (!trylock_page(page))
3196 if (PageKsm(page) || page_mapcount(page) != 1 || page_count(page) != 1) {
3201 * Ok, we've got the only map reference, and the only
3202 * page count reference, and the page is locked,
3203 * it's dark out, and we're wearing sunglasses. Hit it.
3207 return VM_FAULT_WRITE;
3208 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3209 (VM_WRITE|VM_SHARED))) {
3210 return wp_page_shared(vmf);
3214 * Ok, we need to copy. Oh, well..
3216 get_page(vmf->page);
3218 pte_unmap_unlock(vmf->pte, vmf->ptl);
3219 return wp_page_copy(vmf);
3222 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
3223 unsigned long start_addr, unsigned long end_addr,
3224 struct zap_details *details)
3226 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
3229 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
3230 struct zap_details *details)
3232 struct vm_area_struct *vma;
3233 pgoff_t vba, vea, zba, zea;
3235 vma_interval_tree_foreach(vma, root,
3236 details->first_index, details->last_index) {
3238 vba = vma->vm_pgoff;
3239 vea = vba + vma_pages(vma) - 1;
3240 zba = details->first_index;
3243 zea = details->last_index;
3247 unmap_mapping_range_vma(vma,
3248 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
3249 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3255 * unmap_mapping_page() - Unmap single page from processes.
3256 * @page: The locked page to be unmapped.
3258 * Unmap this page from any userspace process which still has it mmaped.
3259 * Typically, for efficiency, the range of nearby pages has already been
3260 * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once
3261 * truncation or invalidation holds the lock on a page, it may find that
3262 * the page has been remapped again: and then uses unmap_mapping_page()
3263 * to unmap it finally.
3265 void unmap_mapping_page(struct page *page)
3267 struct address_space *mapping = page->mapping;
3268 struct zap_details details = { };
3270 VM_BUG_ON(!PageLocked(page));
3271 VM_BUG_ON(PageTail(page));
3273 details.check_mapping = mapping;
3274 details.first_index = page->index;
3275 details.last_index = page->index + thp_nr_pages(page) - 1;
3276 details.single_page = page;
3278 i_mmap_lock_write(mapping);
3279 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3280 unmap_mapping_range_tree(&mapping->i_mmap, &details);
3281 i_mmap_unlock_write(mapping);
3285 * unmap_mapping_pages() - Unmap pages from processes.
3286 * @mapping: The address space containing pages to be unmapped.
3287 * @start: Index of first page to be unmapped.
3288 * @nr: Number of pages to be unmapped. 0 to unmap to end of file.
3289 * @even_cows: Whether to unmap even private COWed pages.
3291 * Unmap the pages in this address space from any userspace process which
3292 * has them mmaped. Generally, you want to remove COWed pages as well when
3293 * a file is being truncated, but not when invalidating pages from the page
3296 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
3297 pgoff_t nr, bool even_cows)
3299 struct zap_details details = { };
3301 details.check_mapping = even_cows ? NULL : mapping;
3302 details.first_index = start;
3303 details.last_index = start + nr - 1;
3304 if (details.last_index < details.first_index)
3305 details.last_index = ULONG_MAX;
3307 i_mmap_lock_write(mapping);
3308 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3309 unmap_mapping_range_tree(&mapping->i_mmap, &details);
3310 i_mmap_unlock_write(mapping);
3314 * unmap_mapping_range - unmap the portion of all mmaps in the specified
3315 * address_space corresponding to the specified byte range in the underlying
3318 * @mapping: the address space containing mmaps to be unmapped.
3319 * @holebegin: byte in first page to unmap, relative to the start of
3320 * the underlying file. This will be rounded down to a PAGE_SIZE
3321 * boundary. Note that this is different from truncate_pagecache(), which
3322 * must keep the partial page. In contrast, we must get rid of
3324 * @holelen: size of prospective hole in bytes. This will be rounded
3325 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
3327 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3328 * but 0 when invalidating pagecache, don't throw away private data.
3330 void unmap_mapping_range(struct address_space *mapping,
3331 loff_t const holebegin, loff_t const holelen, int even_cows)
3333 pgoff_t hba = holebegin >> PAGE_SHIFT;
3334 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3336 /* Check for overflow. */
3337 if (sizeof(holelen) > sizeof(hlen)) {
3339 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3340 if (holeend & ~(long long)ULONG_MAX)
3341 hlen = ULONG_MAX - hba + 1;
3344 unmap_mapping_pages(mapping, hba, hlen, even_cows);
3346 EXPORT_SYMBOL(unmap_mapping_range);
3349 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3350 * but allow concurrent faults), and pte mapped but not yet locked.
3351 * We return with pte unmapped and unlocked.
3353 * We return with the mmap_lock locked or unlocked in the same cases
3354 * as does filemap_fault().
3356 vm_fault_t do_swap_page(struct vm_fault *vmf)
3358 struct vm_area_struct *vma = vmf->vma;
3359 struct page *page = NULL, *swapcache;
3360 struct swap_info_struct *si = NULL;
3366 void *shadow = NULL;
3368 if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte))
3371 entry = pte_to_swp_entry(vmf->orig_pte);
3372 if (unlikely(non_swap_entry(entry))) {
3373 if (is_migration_entry(entry)) {
3374 migration_entry_wait(vma->vm_mm, vmf->pmd,
3376 } else if (is_device_private_entry(entry)) {
3377 vmf->page = pfn_swap_entry_to_page(entry);
3378 ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
3379 } else if (is_hwpoison_entry(entry)) {
3380 ret = VM_FAULT_HWPOISON;
3382 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3383 ret = VM_FAULT_SIGBUS;
3388 /* Prevent swapoff from happening to us. */
3389 si = get_swap_device(entry);
3393 delayacct_set_flag(current, DELAYACCT_PF_SWAPIN);
3394 page = lookup_swap_cache(entry, vma, vmf->address);
3398 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
3399 __swap_count(entry) == 1) {
3400 /* skip swapcache */
3401 page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3404 __SetPageLocked(page);
3405 __SetPageSwapBacked(page);
3407 if (mem_cgroup_swapin_charge_page(page,
3408 vma->vm_mm, GFP_KERNEL, entry)) {
3412 mem_cgroup_swapin_uncharge_swap(entry);
3414 shadow = get_shadow_from_swap_cache(entry);
3416 workingset_refault(page, shadow);
3418 lru_cache_add(page);
3420 /* To provide entry to swap_readpage() */
3421 set_page_private(page, entry.val);
3422 swap_readpage(page, true);
3423 set_page_private(page, 0);
3426 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3433 * Back out if somebody else faulted in this pte
3434 * while we released the pte lock.
3436 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3437 vmf->address, &vmf->ptl);
3438 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3440 delayacct_clear_flag(current, DELAYACCT_PF_SWAPIN);
3444 /* Had to read the page from swap area: Major fault */
3445 ret = VM_FAULT_MAJOR;
3446 count_vm_event(PGMAJFAULT);
3447 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3448 } else if (PageHWPoison(page)) {
3450 * hwpoisoned dirty swapcache pages are kept for killing
3451 * owner processes (which may be unknown at hwpoison time)
3453 ret = VM_FAULT_HWPOISON;
3454 delayacct_clear_flag(current, DELAYACCT_PF_SWAPIN);
3458 locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3460 delayacct_clear_flag(current, DELAYACCT_PF_SWAPIN);
3462 ret |= VM_FAULT_RETRY;
3467 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3468 * release the swapcache from under us. The page pin, and pte_same
3469 * test below, are not enough to exclude that. Even if it is still
3470 * swapcache, we need to check that the page's swap has not changed.
3472 if (unlikely((!PageSwapCache(page) ||
3473 page_private(page) != entry.val)) && swapcache)
3476 page = ksm_might_need_to_copy(page, vma, vmf->address);
3477 if (unlikely(!page)) {
3483 cgroup_throttle_swaprate(page, GFP_KERNEL);
3486 * Back out if somebody else already faulted in this pte.
3488 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3490 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3493 if (unlikely(!PageUptodate(page))) {
3494 ret = VM_FAULT_SIGBUS;
3499 * The page isn't present yet, go ahead with the fault.
3501 * Be careful about the sequence of operations here.
3502 * To get its accounting right, reuse_swap_page() must be called
3503 * while the page is counted on swap but not yet in mapcount i.e.
3504 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3505 * must be called after the swap_free(), or it will never succeed.
3508 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3509 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3510 pte = mk_pte(page, vma->vm_page_prot);
3511 if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3512 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3513 vmf->flags &= ~FAULT_FLAG_WRITE;
3514 ret |= VM_FAULT_WRITE;
3515 exclusive = RMAP_EXCLUSIVE;
3517 flush_icache_page(vma, page);
3518 if (pte_swp_soft_dirty(vmf->orig_pte))
3519 pte = pte_mksoft_dirty(pte);
3520 if (pte_swp_uffd_wp(vmf->orig_pte)) {
3521 pte = pte_mkuffd_wp(pte);
3522 pte = pte_wrprotect(pte);
3524 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3525 arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
3526 vmf->orig_pte = pte;
3528 /* ksm created a completely new copy */
3529 if (unlikely(page != swapcache && swapcache)) {
3530 page_add_new_anon_rmap(page, vma, vmf->address, false);
3531 lru_cache_add_inactive_or_unevictable(page, vma);
3533 do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3537 if (mem_cgroup_swap_full(page) ||
3538 (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3539 try_to_free_swap(page);
3541 if (page != swapcache && swapcache) {
3543 * Hold the lock to avoid the swap entry to be reused
3544 * until we take the PT lock for the pte_same() check
3545 * (to avoid false positives from pte_same). For
3546 * further safety release the lock after the swap_free
3547 * so that the swap count won't change under a
3548 * parallel locked swapcache.
3550 unlock_page(swapcache);
3551 put_page(swapcache);
3554 if (vmf->flags & FAULT_FLAG_WRITE) {
3555 ret |= do_wp_page(vmf);
3556 if (ret & VM_FAULT_ERROR)
3557 ret &= VM_FAULT_ERROR;
3561 /* No need to invalidate - it was non-present before */
3562 update_mmu_cache(vma, vmf->address, vmf->pte);
3564 pte_unmap_unlock(vmf->pte, vmf->ptl);
3567 put_swap_device(si);
3570 pte_unmap_unlock(vmf->pte, vmf->ptl);
3575 if (page != swapcache && swapcache) {
3576 unlock_page(swapcache);
3577 put_page(swapcache);
3580 put_swap_device(si);
3585 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3586 * but allow concurrent faults), and pte mapped but not yet locked.
3587 * We return with mmap_lock still held, but pte unmapped and unlocked.
3589 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
3591 struct vm_area_struct *vma = vmf->vma;
3596 /* File mapping without ->vm_ops ? */
3597 if (vma->vm_flags & VM_SHARED)
3598 return VM_FAULT_SIGBUS;
3601 * Use pte_alloc() instead of pte_alloc_map(). We can't run
3602 * pte_offset_map() on pmds where a huge pmd might be created
3603 * from a different thread.
3605 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
3606 * parallel threads are excluded by other means.
3608 * Here we only have mmap_read_lock(mm).
3610 if (pte_alloc(vma->vm_mm, vmf->pmd))
3611 return VM_FAULT_OOM;
3613 /* See comment in handle_pte_fault() */
3614 if (unlikely(pmd_trans_unstable(vmf->pmd)))
3617 /* Use the zero-page for reads */
3618 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3619 !mm_forbids_zeropage(vma->vm_mm)) {
3620 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3621 vma->vm_page_prot));
3622 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3623 vmf->address, &vmf->ptl);
3624 if (!pte_none(*vmf->pte)) {
3625 update_mmu_tlb(vma, vmf->address, vmf->pte);
3628 ret = check_stable_address_space(vma->vm_mm);
3631 /* Deliver the page fault to userland, check inside PT lock */
3632 if (userfaultfd_missing(vma)) {
3633 pte_unmap_unlock(vmf->pte, vmf->ptl);
3634 return handle_userfault(vmf, VM_UFFD_MISSING);
3639 /* Allocate our own private page. */
3640 if (unlikely(anon_vma_prepare(vma)))
3642 page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3646 if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
3648 cgroup_throttle_swaprate(page, GFP_KERNEL);
3651 * The memory barrier inside __SetPageUptodate makes sure that
3652 * preceding stores to the page contents become visible before
3653 * the set_pte_at() write.
3655 __SetPageUptodate(page);
3657 entry = mk_pte(page, vma->vm_page_prot);
3658 entry = pte_sw_mkyoung(entry);
3659 if (vma->vm_flags & VM_WRITE)
3660 entry = pte_mkwrite(pte_mkdirty(entry));
3662 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3664 if (!pte_none(*vmf->pte)) {
3665 update_mmu_cache(vma, vmf->address, vmf->pte);
3669 ret = check_stable_address_space(vma->vm_mm);
3673 /* Deliver the page fault to userland, check inside PT lock */
3674 if (userfaultfd_missing(vma)) {
3675 pte_unmap_unlock(vmf->pte, vmf->ptl);
3677 return handle_userfault(vmf, VM_UFFD_MISSING);
3680 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3681 page_add_new_anon_rmap(page, vma, vmf->address, false);
3682 lru_cache_add_inactive_or_unevictable(page, vma);
3684 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3686 /* No need to invalidate - it was non-present before */
3687 update_mmu_cache(vma, vmf->address, vmf->pte);
3689 pte_unmap_unlock(vmf->pte, vmf->ptl);
3697 return VM_FAULT_OOM;
3701 * The mmap_lock must have been held on entry, and may have been
3702 * released depending on flags and vma->vm_ops->fault() return value.
3703 * See filemap_fault() and __lock_page_retry().
3705 static vm_fault_t __do_fault(struct vm_fault *vmf)
3707 struct vm_area_struct *vma = vmf->vma;
3711 * Preallocate pte before we take page_lock because this might lead to
3712 * deadlocks for memcg reclaim which waits for pages under writeback:
3714 * SetPageWriteback(A)
3720 * wait_on_page_writeback(A)
3721 * SetPageWriteback(B)
3723 * # flush A, B to clear the writeback
3725 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3726 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3727 if (!vmf->prealloc_pte)
3728 return VM_FAULT_OOM;
3729 smp_wmb(); /* See comment in __pte_alloc() */
3732 ret = vma->vm_ops->fault(vmf);
3733 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3734 VM_FAULT_DONE_COW)))
3737 if (unlikely(PageHWPoison(vmf->page))) {
3738 if (ret & VM_FAULT_LOCKED)
3739 unlock_page(vmf->page);
3740 put_page(vmf->page);
3742 return VM_FAULT_HWPOISON;
3745 if (unlikely(!(ret & VM_FAULT_LOCKED)))
3746 lock_page(vmf->page);
3748 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3753 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3754 static void deposit_prealloc_pte(struct vm_fault *vmf)
3756 struct vm_area_struct *vma = vmf->vma;
3758 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3760 * We are going to consume the prealloc table,
3761 * count that as nr_ptes.
3763 mm_inc_nr_ptes(vma->vm_mm);
3764 vmf->prealloc_pte = NULL;
3767 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3769 struct vm_area_struct *vma = vmf->vma;
3770 bool write = vmf->flags & FAULT_FLAG_WRITE;
3771 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3774 vm_fault_t ret = VM_FAULT_FALLBACK;
3776 if (!transhuge_vma_suitable(vma, haddr))
3779 page = compound_head(page);
3780 if (compound_order(page) != HPAGE_PMD_ORDER)
3784 * Archs like ppc64 need additional space to store information
3785 * related to pte entry. Use the preallocated table for that.
3787 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3788 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3789 if (!vmf->prealloc_pte)
3790 return VM_FAULT_OOM;
3791 smp_wmb(); /* See comment in __pte_alloc() */
3794 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3795 if (unlikely(!pmd_none(*vmf->pmd)))
3798 for (i = 0; i < HPAGE_PMD_NR; i++)
3799 flush_icache_page(vma, page + i);
3801 entry = mk_huge_pmd(page, vma->vm_page_prot);
3803 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3805 add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
3806 page_add_file_rmap(page, true);
3808 * deposit and withdraw with pmd lock held
3810 if (arch_needs_pgtable_deposit())
3811 deposit_prealloc_pte(vmf);
3813 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3815 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3817 /* fault is handled */
3819 count_vm_event(THP_FILE_MAPPED);
3821 spin_unlock(vmf->ptl);
3825 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3827 return VM_FAULT_FALLBACK;
3831 void do_set_pte(struct vm_fault *vmf, struct page *page, unsigned long addr)
3833 struct vm_area_struct *vma = vmf->vma;
3834 bool write = vmf->flags & FAULT_FLAG_WRITE;
3835 bool prefault = vmf->address != addr;
3838 flush_icache_page(vma, page);
3839 entry = mk_pte(page, vma->vm_page_prot);
3841 if (prefault && arch_wants_old_prefaulted_pte())
3842 entry = pte_mkold(entry);
3844 entry = pte_sw_mkyoung(entry);
3847 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3848 /* copy-on-write page */
3849 if (write && !(vma->vm_flags & VM_SHARED)) {
3850 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3851 page_add_new_anon_rmap(page, vma, addr, false);
3852 lru_cache_add_inactive_or_unevictable(page, vma);
3854 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3855 page_add_file_rmap(page, false);
3857 set_pte_at(vma->vm_mm, addr, vmf->pte, entry);
3861 * finish_fault - finish page fault once we have prepared the page to fault
3863 * @vmf: structure describing the fault
3865 * This function handles all that is needed to finish a page fault once the
3866 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
3867 * given page, adds reverse page mapping, handles memcg charges and LRU
3870 * The function expects the page to be locked and on success it consumes a
3871 * reference of a page being mapped (for the PTE which maps it).
3873 * Return: %0 on success, %VM_FAULT_ code in case of error.
3875 vm_fault_t finish_fault(struct vm_fault *vmf)
3877 struct vm_area_struct *vma = vmf->vma;
3881 /* Did we COW the page? */
3882 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED))
3883 page = vmf->cow_page;
3888 * check even for read faults because we might have lost our CoWed
3891 if (!(vma->vm_flags & VM_SHARED)) {
3892 ret = check_stable_address_space(vma->vm_mm);
3897 if (pmd_none(*vmf->pmd)) {
3898 if (PageTransCompound(page)) {
3899 ret = do_set_pmd(vmf, page);
3900 if (ret != VM_FAULT_FALLBACK)
3904 if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd)))
3905 return VM_FAULT_OOM;
3908 /* See comment in handle_pte_fault() */
3909 if (pmd_devmap_trans_unstable(vmf->pmd))
3912 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3913 vmf->address, &vmf->ptl);
3915 /* Re-check under ptl */
3916 if (likely(pte_none(*vmf->pte)))
3917 do_set_pte(vmf, page, vmf->address);
3919 ret = VM_FAULT_NOPAGE;
3921 update_mmu_tlb(vma, vmf->address, vmf->pte);
3922 pte_unmap_unlock(vmf->pte, vmf->ptl);
3926 static unsigned long fault_around_bytes __read_mostly =
3927 rounddown_pow_of_two(65536);
3929 #ifdef CONFIG_DEBUG_FS
3930 static int fault_around_bytes_get(void *data, u64 *val)
3932 *val = fault_around_bytes;
3937 * fault_around_bytes must be rounded down to the nearest page order as it's
3938 * what do_fault_around() expects to see.
3940 static int fault_around_bytes_set(void *data, u64 val)
3942 if (val / PAGE_SIZE > PTRS_PER_PTE)
3944 if (val > PAGE_SIZE)
3945 fault_around_bytes = rounddown_pow_of_two(val);
3947 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
3950 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
3951 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
3953 static int __init fault_around_debugfs(void)
3955 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
3956 &fault_around_bytes_fops);
3959 late_initcall(fault_around_debugfs);
3963 * do_fault_around() tries to map few pages around the fault address. The hope
3964 * is that the pages will be needed soon and this will lower the number of
3967 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
3968 * not ready to be mapped: not up-to-date, locked, etc.
3970 * This function is called with the page table lock taken. In the split ptlock
3971 * case the page table lock only protects only those entries which belong to
3972 * the page table corresponding to the fault address.
3974 * This function doesn't cross the VMA boundaries, in order to call map_pages()
3977 * fault_around_bytes defines how many bytes we'll try to map.
3978 * do_fault_around() expects it to be set to a power of two less than or equal
3981 * The virtual address of the area that we map is naturally aligned to
3982 * fault_around_bytes rounded down to the machine page size
3983 * (and therefore to page order). This way it's easier to guarantee
3984 * that we don't cross page table boundaries.
3986 static vm_fault_t do_fault_around(struct vm_fault *vmf)
3988 unsigned long address = vmf->address, nr_pages, mask;
3989 pgoff_t start_pgoff = vmf->pgoff;
3993 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3994 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3996 address = max(address & mask, vmf->vma->vm_start);
3997 off = ((vmf->address - address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
4001 * end_pgoff is either the end of the page table, the end of
4002 * the vma or nr_pages from start_pgoff, depending what is nearest.
4004 end_pgoff = start_pgoff -
4005 ((address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
4007 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
4008 start_pgoff + nr_pages - 1);
4010 if (pmd_none(*vmf->pmd)) {
4011 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
4012 if (!vmf->prealloc_pte)
4013 return VM_FAULT_OOM;
4014 smp_wmb(); /* See comment in __pte_alloc() */
4017 return vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
4020 static vm_fault_t do_read_fault(struct vm_fault *vmf)
4022 struct vm_area_struct *vma = vmf->vma;
4026 * Let's call ->map_pages() first and use ->fault() as fallback
4027 * if page by the offset is not ready to be mapped (cold cache or
4030 if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
4031 if (likely(!userfaultfd_minor(vmf->vma))) {
4032 ret = do_fault_around(vmf);
4038 ret = __do_fault(vmf);
4039 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4042 ret |= finish_fault(vmf);
4043 unlock_page(vmf->page);
4044 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4045 put_page(vmf->page);
4049 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
4051 struct vm_area_struct *vma = vmf->vma;
4054 if (unlikely(anon_vma_prepare(vma)))
4055 return VM_FAULT_OOM;
4057 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
4059 return VM_FAULT_OOM;
4061 if (mem_cgroup_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL)) {
4062 put_page(vmf->cow_page);
4063 return VM_FAULT_OOM;
4065 cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL);
4067 ret = __do_fault(vmf);
4068 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4070 if (ret & VM_FAULT_DONE_COW)
4073 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
4074 __SetPageUptodate(vmf->cow_page);
4076 ret |= finish_fault(vmf);
4077 unlock_page(vmf->page);
4078 put_page(vmf->page);
4079 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4083 put_page(vmf->cow_page);
4087 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
4089 struct vm_area_struct *vma = vmf->vma;
4090 vm_fault_t ret, tmp;
4092 ret = __do_fault(vmf);
4093 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4097 * Check if the backing address space wants to know that the page is
4098 * about to become writable
4100 if (vma->vm_ops->page_mkwrite) {
4101 unlock_page(vmf->page);
4102 tmp = do_page_mkwrite(vmf);
4103 if (unlikely(!tmp ||
4104 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
4105 put_page(vmf->page);
4110 ret |= finish_fault(vmf);
4111 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
4113 unlock_page(vmf->page);
4114 put_page(vmf->page);
4118 ret |= fault_dirty_shared_page(vmf);
4123 * We enter with non-exclusive mmap_lock (to exclude vma changes,
4124 * but allow concurrent faults).
4125 * The mmap_lock may have been released depending on flags and our
4126 * return value. See filemap_fault() and __lock_page_or_retry().
4127 * If mmap_lock is released, vma may become invalid (for example
4128 * by other thread calling munmap()).
4130 static vm_fault_t do_fault(struct vm_fault *vmf)
4132 struct vm_area_struct *vma = vmf->vma;
4133 struct mm_struct *vm_mm = vma->vm_mm;
4137 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
4139 if (!vma->vm_ops->fault) {
4141 * If we find a migration pmd entry or a none pmd entry, which
4142 * should never happen, return SIGBUS
4144 if (unlikely(!pmd_present(*vmf->pmd)))
4145 ret = VM_FAULT_SIGBUS;
4147 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
4152 * Make sure this is not a temporary clearing of pte
4153 * by holding ptl and checking again. A R/M/W update
4154 * of pte involves: take ptl, clearing the pte so that
4155 * we don't have concurrent modification by hardware
4156 * followed by an update.
4158 if (unlikely(pte_none(*vmf->pte)))
4159 ret = VM_FAULT_SIGBUS;
4161 ret = VM_FAULT_NOPAGE;
4163 pte_unmap_unlock(vmf->pte, vmf->ptl);
4165 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
4166 ret = do_read_fault(vmf);
4167 else if (!(vma->vm_flags & VM_SHARED))
4168 ret = do_cow_fault(vmf);
4170 ret = do_shared_fault(vmf);
4172 /* preallocated pagetable is unused: free it */
4173 if (vmf->prealloc_pte) {
4174 pte_free(vm_mm, vmf->prealloc_pte);
4175 vmf->prealloc_pte = NULL;
4180 int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
4181 unsigned long addr, int page_nid, int *flags)
4185 count_vm_numa_event(NUMA_HINT_FAULTS);
4186 if (page_nid == numa_node_id()) {
4187 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
4188 *flags |= TNF_FAULT_LOCAL;
4191 return mpol_misplaced(page, vma, addr);
4194 static vm_fault_t do_numa_page(struct vm_fault *vmf)
4196 struct vm_area_struct *vma = vmf->vma;
4197 struct page *page = NULL;
4198 int page_nid = NUMA_NO_NODE;
4202 bool was_writable = pte_savedwrite(vmf->orig_pte);
4206 * The "pte" at this point cannot be used safely without
4207 * validation through pte_unmap_same(). It's of NUMA type but
4208 * the pfn may be screwed if the read is non atomic.
4210 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
4211 spin_lock(vmf->ptl);
4212 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4213 pte_unmap_unlock(vmf->pte, vmf->ptl);
4217 /* Get the normal PTE */
4218 old_pte = ptep_get(vmf->pte);
4219 pte = pte_modify(old_pte, vma->vm_page_prot);
4221 page = vm_normal_page(vma, vmf->address, pte);
4225 /* TODO: handle PTE-mapped THP */
4226 if (PageCompound(page))
4230 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
4231 * much anyway since they can be in shared cache state. This misses
4232 * the case where a mapping is writable but the process never writes
4233 * to it but pte_write gets cleared during protection updates and
4234 * pte_dirty has unpredictable behaviour between PTE scan updates,
4235 * background writeback, dirty balancing and application behaviour.
4238 flags |= TNF_NO_GROUP;
4241 * Flag if the page is shared between multiple address spaces. This
4242 * is later used when determining whether to group tasks together
4244 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
4245 flags |= TNF_SHARED;
4247 last_cpupid = page_cpupid_last(page);
4248 page_nid = page_to_nid(page);
4249 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
4251 if (target_nid == NUMA_NO_NODE) {
4255 pte_unmap_unlock(vmf->pte, vmf->ptl);
4257 /* Migrate to the requested node */
4258 if (migrate_misplaced_page(page, vma, target_nid)) {
4259 page_nid = target_nid;
4260 flags |= TNF_MIGRATED;
4262 flags |= TNF_MIGRATE_FAIL;
4263 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4264 spin_lock(vmf->ptl);
4265 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4266 pte_unmap_unlock(vmf->pte, vmf->ptl);
4273 if (page_nid != NUMA_NO_NODE)
4274 task_numa_fault(last_cpupid, page_nid, 1, flags);
4278 * Make it present again, depending on how arch implements
4279 * non-accessible ptes, some can allow access by kernel mode.
4281 old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte);
4282 pte = pte_modify(old_pte, vma->vm_page_prot);
4283 pte = pte_mkyoung(pte);
4285 pte = pte_mkwrite(pte);
4286 ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte);
4287 update_mmu_cache(vma, vmf->address, vmf->pte);
4288 pte_unmap_unlock(vmf->pte, vmf->ptl);
4292 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4294 if (vma_is_anonymous(vmf->vma))
4295 return do_huge_pmd_anonymous_page(vmf);
4296 if (vmf->vma->vm_ops->huge_fault)
4297 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4298 return VM_FAULT_FALLBACK;
4301 /* `inline' is required to avoid gcc 4.1.2 build error */
4302 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf)
4304 if (vma_is_anonymous(vmf->vma)) {
4305 if (userfaultfd_huge_pmd_wp(vmf->vma, vmf->orig_pmd))
4306 return handle_userfault(vmf, VM_UFFD_WP);
4307 return do_huge_pmd_wp_page(vmf);
4309 if (vmf->vma->vm_ops->huge_fault) {
4310 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4312 if (!(ret & VM_FAULT_FALLBACK))
4316 /* COW or write-notify handled on pte level: split pmd. */
4317 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4319 return VM_FAULT_FALLBACK;
4322 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4324 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
4325 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4326 /* No support for anonymous transparent PUD pages yet */
4327 if (vma_is_anonymous(vmf->vma))
4329 if (vmf->vma->vm_ops->huge_fault) {
4330 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4332 if (!(ret & VM_FAULT_FALLBACK))
4336 /* COW or write-notify not handled on PUD level: split pud.*/
4337 __split_huge_pud(vmf->vma, vmf->pud, vmf->address);
4338 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4339 return VM_FAULT_FALLBACK;
4342 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4344 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4345 /* No support for anonymous transparent PUD pages yet */
4346 if (vma_is_anonymous(vmf->vma))
4347 return VM_FAULT_FALLBACK;
4348 if (vmf->vma->vm_ops->huge_fault)
4349 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4350 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4351 return VM_FAULT_FALLBACK;
4355 * These routines also need to handle stuff like marking pages dirty
4356 * and/or accessed for architectures that don't do it in hardware (most
4357 * RISC architectures). The early dirtying is also good on the i386.
4359 * There is also a hook called "update_mmu_cache()" that architectures
4360 * with external mmu caches can use to update those (ie the Sparc or
4361 * PowerPC hashed page tables that act as extended TLBs).
4363 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
4364 * concurrent faults).
4366 * The mmap_lock may have been released depending on flags and our return value.
4367 * See filemap_fault() and __lock_page_or_retry().
4369 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4373 if (unlikely(pmd_none(*vmf->pmd))) {
4375 * Leave __pte_alloc() until later: because vm_ops->fault may
4376 * want to allocate huge page, and if we expose page table
4377 * for an instant, it will be difficult to retract from
4378 * concurrent faults and from rmap lookups.
4383 * If a huge pmd materialized under us just retry later. Use
4384 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead
4385 * of pmd_trans_huge() to ensure the pmd didn't become
4386 * pmd_trans_huge under us and then back to pmd_none, as a
4387 * result of MADV_DONTNEED running immediately after a huge pmd
4388 * fault in a different thread of this mm, in turn leading to a
4389 * misleading pmd_trans_huge() retval. All we have to ensure is
4390 * that it is a regular pmd that we can walk with
4391 * pte_offset_map() and we can do that through an atomic read
4392 * in C, which is what pmd_trans_unstable() provides.
4394 if (pmd_devmap_trans_unstable(vmf->pmd))
4397 * A regular pmd is established and it can't morph into a huge
4398 * pmd from under us anymore at this point because we hold the
4399 * mmap_lock read mode and khugepaged takes it in write mode.
4400 * So now it's safe to run pte_offset_map().
4402 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4403 vmf->orig_pte = *vmf->pte;
4406 * some architectures can have larger ptes than wordsize,
4407 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4408 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4409 * accesses. The code below just needs a consistent view
4410 * for the ifs and we later double check anyway with the
4411 * ptl lock held. So here a barrier will do.
4414 if (pte_none(vmf->orig_pte)) {
4415 pte_unmap(vmf->pte);
4421 if (vma_is_anonymous(vmf->vma))
4422 return do_anonymous_page(vmf);
4424 return do_fault(vmf);
4427 if (!pte_present(vmf->orig_pte))
4428 return do_swap_page(vmf);
4430 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4431 return do_numa_page(vmf);
4433 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4434 spin_lock(vmf->ptl);
4435 entry = vmf->orig_pte;
4436 if (unlikely(!pte_same(*vmf->pte, entry))) {
4437 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
4440 if (vmf->flags & FAULT_FLAG_WRITE) {
4441 if (!pte_write(entry))
4442 return do_wp_page(vmf);
4443 entry = pte_mkdirty(entry);
4445 entry = pte_mkyoung(entry);
4446 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4447 vmf->flags & FAULT_FLAG_WRITE)) {
4448 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4450 /* Skip spurious TLB flush for retried page fault */
4451 if (vmf->flags & FAULT_FLAG_TRIED)
4454 * This is needed only for protection faults but the arch code
4455 * is not yet telling us if this is a protection fault or not.
4456 * This still avoids useless tlb flushes for .text page faults
4459 if (vmf->flags & FAULT_FLAG_WRITE)
4460 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4463 pte_unmap_unlock(vmf->pte, vmf->ptl);
4468 * By the time we get here, we already hold the mm semaphore
4470 * The mmap_lock may have been released depending on flags and our
4471 * return value. See filemap_fault() and __lock_page_or_retry().
4473 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
4474 unsigned long address, unsigned int flags)
4476 struct vm_fault vmf = {
4478 .address = address & PAGE_MASK,
4480 .pgoff = linear_page_index(vma, address),
4481 .gfp_mask = __get_fault_gfp_mask(vma),
4483 unsigned int dirty = flags & FAULT_FLAG_WRITE;
4484 struct mm_struct *mm = vma->vm_mm;
4489 pgd = pgd_offset(mm, address);
4490 p4d = p4d_alloc(mm, pgd, address);
4492 return VM_FAULT_OOM;
4494 vmf.pud = pud_alloc(mm, p4d, address);
4496 return VM_FAULT_OOM;
4498 if (pud_none(*vmf.pud) && __transparent_hugepage_enabled(vma)) {
4499 ret = create_huge_pud(&vmf);
4500 if (!(ret & VM_FAULT_FALLBACK))
4503 pud_t orig_pud = *vmf.pud;
4506 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4508 /* NUMA case for anonymous PUDs would go here */
4510 if (dirty && !pud_write(orig_pud)) {
4511 ret = wp_huge_pud(&vmf, orig_pud);
4512 if (!(ret & VM_FAULT_FALLBACK))
4515 huge_pud_set_accessed(&vmf, orig_pud);
4521 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4523 return VM_FAULT_OOM;
4525 /* Huge pud page fault raced with pmd_alloc? */
4526 if (pud_trans_unstable(vmf.pud))
4529 if (pmd_none(*vmf.pmd) && __transparent_hugepage_enabled(vma)) {
4530 ret = create_huge_pmd(&vmf);
4531 if (!(ret & VM_FAULT_FALLBACK))
4534 vmf.orig_pmd = *vmf.pmd;
4537 if (unlikely(is_swap_pmd(vmf.orig_pmd))) {
4538 VM_BUG_ON(thp_migration_supported() &&
4539 !is_pmd_migration_entry(vmf.orig_pmd));
4540 if (is_pmd_migration_entry(vmf.orig_pmd))
4541 pmd_migration_entry_wait(mm, vmf.pmd);
4544 if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) {
4545 if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma))
4546 return do_huge_pmd_numa_page(&vmf);
4548 if (dirty && !pmd_write(vmf.orig_pmd)) {
4549 ret = wp_huge_pmd(&vmf);
4550 if (!(ret & VM_FAULT_FALLBACK))
4553 huge_pmd_set_accessed(&vmf);
4559 return handle_pte_fault(&vmf);
4563 * mm_account_fault - Do page fault accounting
4565 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting
4566 * of perf event counters, but we'll still do the per-task accounting to
4567 * the task who triggered this page fault.
4568 * @address: the faulted address.
4569 * @flags: the fault flags.
4570 * @ret: the fault retcode.
4572 * This will take care of most of the page fault accounting. Meanwhile, it
4573 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
4574 * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
4575 * still be in per-arch page fault handlers at the entry of page fault.
4577 static inline void mm_account_fault(struct pt_regs *regs,
4578 unsigned long address, unsigned int flags,
4584 * We don't do accounting for some specific faults:
4586 * - Unsuccessful faults (e.g. when the address wasn't valid). That
4587 * includes arch_vma_access_permitted() failing before reaching here.
4588 * So this is not a "this many hardware page faults" counter. We
4589 * should use the hw profiling for that.
4591 * - Incomplete faults (VM_FAULT_RETRY). They will only be counted
4592 * once they're completed.
4594 if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY))
4598 * We define the fault as a major fault when the final successful fault
4599 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
4600 * handle it immediately previously).
4602 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
4610 * If the fault is done for GUP, regs will be NULL. We only do the
4611 * accounting for the per thread fault counters who triggered the
4612 * fault, and we skip the perf event updates.
4618 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
4620 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
4624 * By the time we get here, we already hold the mm semaphore
4626 * The mmap_lock may have been released depending on flags and our
4627 * return value. See filemap_fault() and __lock_page_or_retry().
4629 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4630 unsigned int flags, struct pt_regs *regs)
4634 __set_current_state(TASK_RUNNING);
4636 count_vm_event(PGFAULT);
4637 count_memcg_event_mm(vma->vm_mm, PGFAULT);
4639 /* do counter updates before entering really critical section. */
4640 check_sync_rss_stat(current);
4642 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4643 flags & FAULT_FLAG_INSTRUCTION,
4644 flags & FAULT_FLAG_REMOTE))
4645 return VM_FAULT_SIGSEGV;
4648 * Enable the memcg OOM handling for faults triggered in user
4649 * space. Kernel faults are handled more gracefully.
4651 if (flags & FAULT_FLAG_USER)
4652 mem_cgroup_enter_user_fault();
4654 if (unlikely(is_vm_hugetlb_page(vma)))
4655 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4657 ret = __handle_mm_fault(vma, address, flags);
4659 if (flags & FAULT_FLAG_USER) {
4660 mem_cgroup_exit_user_fault();
4662 * The task may have entered a memcg OOM situation but
4663 * if the allocation error was handled gracefully (no
4664 * VM_FAULT_OOM), there is no need to kill anything.
4665 * Just clean up the OOM state peacefully.
4667 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4668 mem_cgroup_oom_synchronize(false);
4671 mm_account_fault(regs, address, flags, ret);
4675 EXPORT_SYMBOL_GPL(handle_mm_fault);
4677 #ifndef __PAGETABLE_P4D_FOLDED
4679 * Allocate p4d page table.
4680 * We've already handled the fast-path in-line.
4682 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4684 p4d_t *new = p4d_alloc_one(mm, address);
4688 smp_wmb(); /* See comment in __pte_alloc */
4690 spin_lock(&mm->page_table_lock);
4691 if (pgd_present(*pgd)) /* Another has populated it */
4694 pgd_populate(mm, pgd, new);
4695 spin_unlock(&mm->page_table_lock);
4698 #endif /* __PAGETABLE_P4D_FOLDED */
4700 #ifndef __PAGETABLE_PUD_FOLDED
4702 * Allocate page upper directory.
4703 * We've already handled the fast-path in-line.
4705 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4707 pud_t *new = pud_alloc_one(mm, address);
4711 smp_wmb(); /* See comment in __pte_alloc */
4713 spin_lock(&mm->page_table_lock);
4714 if (!p4d_present(*p4d)) {
4716 p4d_populate(mm, p4d, new);
4717 } else /* Another has populated it */
4719 spin_unlock(&mm->page_table_lock);
4722 #endif /* __PAGETABLE_PUD_FOLDED */
4724 #ifndef __PAGETABLE_PMD_FOLDED
4726 * Allocate page middle directory.
4727 * We've already handled the fast-path in-line.
4729 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4732 pmd_t *new = pmd_alloc_one(mm, address);
4736 smp_wmb(); /* See comment in __pte_alloc */
4738 ptl = pud_lock(mm, pud);
4739 if (!pud_present(*pud)) {
4741 pud_populate(mm, pud, new);
4742 } else /* Another has populated it */
4747 #endif /* __PAGETABLE_PMD_FOLDED */
4749 int follow_invalidate_pte(struct mm_struct *mm, unsigned long address,
4750 struct mmu_notifier_range *range, pte_t **ptepp,
4751 pmd_t **pmdpp, spinlock_t **ptlp)
4759 pgd = pgd_offset(mm, address);
4760 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4763 p4d = p4d_offset(pgd, address);
4764 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4767 pud = pud_offset(p4d, address);
4768 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4771 pmd = pmd_offset(pud, address);
4772 VM_BUG_ON(pmd_trans_huge(*pmd));
4774 if (pmd_huge(*pmd)) {
4779 mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0,
4780 NULL, mm, address & PMD_MASK,
4781 (address & PMD_MASK) + PMD_SIZE);
4782 mmu_notifier_invalidate_range_start(range);
4784 *ptlp = pmd_lock(mm, pmd);
4785 if (pmd_huge(*pmd)) {
4791 mmu_notifier_invalidate_range_end(range);
4794 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4798 mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
4799 address & PAGE_MASK,
4800 (address & PAGE_MASK) + PAGE_SIZE);
4801 mmu_notifier_invalidate_range_start(range);
4803 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4804 if (!pte_present(*ptep))
4809 pte_unmap_unlock(ptep, *ptlp);
4811 mmu_notifier_invalidate_range_end(range);
4817 * follow_pte - look up PTE at a user virtual address
4818 * @mm: the mm_struct of the target address space
4819 * @address: user virtual address
4820 * @ptepp: location to store found PTE
4821 * @ptlp: location to store the lock for the PTE
4823 * On a successful return, the pointer to the PTE is stored in @ptepp;
4824 * the corresponding lock is taken and its location is stored in @ptlp.
4825 * The contents of the PTE are only stable until @ptlp is released;
4826 * any further use, if any, must be protected against invalidation
4827 * with MMU notifiers.
4829 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore
4830 * should be taken for read.
4832 * KVM uses this function. While it is arguably less bad than ``follow_pfn``,
4833 * it is not a good general-purpose API.
4835 * Return: zero on success, -ve otherwise.
4837 int follow_pte(struct mm_struct *mm, unsigned long address,
4838 pte_t **ptepp, spinlock_t **ptlp)
4840 return follow_invalidate_pte(mm, address, NULL, ptepp, NULL, ptlp);
4842 EXPORT_SYMBOL_GPL(follow_pte);
4845 * follow_pfn - look up PFN at a user virtual address
4846 * @vma: memory mapping
4847 * @address: user virtual address
4848 * @pfn: location to store found PFN
4850 * Only IO mappings and raw PFN mappings are allowed.
4852 * This function does not allow the caller to read the permissions
4853 * of the PTE. Do not use it.
4855 * Return: zero and the pfn at @pfn on success, -ve otherwise.
4857 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4864 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4867 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4870 *pfn = pte_pfn(*ptep);
4871 pte_unmap_unlock(ptep, ptl);
4874 EXPORT_SYMBOL(follow_pfn);
4876 #ifdef CONFIG_HAVE_IOREMAP_PROT
4877 int follow_phys(struct vm_area_struct *vma,
4878 unsigned long address, unsigned int flags,
4879 unsigned long *prot, resource_size_t *phys)
4885 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4888 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4892 if ((flags & FOLL_WRITE) && !pte_write(pte))
4895 *prot = pgprot_val(pte_pgprot(pte));
4896 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4900 pte_unmap_unlock(ptep, ptl);
4906 * generic_access_phys - generic implementation for iomem mmap access
4907 * @vma: the vma to access
4908 * @addr: userspace address, not relative offset within @vma
4909 * @buf: buffer to read/write
4910 * @len: length of transfer
4911 * @write: set to FOLL_WRITE when writing, otherwise reading
4913 * This is a generic implementation for &vm_operations_struct.access for an
4914 * iomem mapping. This callback is used by access_process_vm() when the @vma is
4917 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4918 void *buf, int len, int write)
4920 resource_size_t phys_addr;
4921 unsigned long prot = 0;
4922 void __iomem *maddr;
4925 int offset = offset_in_page(addr);
4928 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4932 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl))
4935 pte_unmap_unlock(ptep, ptl);
4937 prot = pgprot_val(pte_pgprot(pte));
4938 phys_addr = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4940 if ((write & FOLL_WRITE) && !pte_write(pte))
4943 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4947 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl))
4950 if (!pte_same(pte, *ptep)) {
4951 pte_unmap_unlock(ptep, ptl);
4958 memcpy_toio(maddr + offset, buf, len);
4960 memcpy_fromio(buf, maddr + offset, len);
4962 pte_unmap_unlock(ptep, ptl);
4968 EXPORT_SYMBOL_GPL(generic_access_phys);
4972 * Access another process' address space as given in mm.
4974 int __access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf,
4975 int len, unsigned int gup_flags)
4977 struct vm_area_struct *vma;
4978 void *old_buf = buf;
4979 int write = gup_flags & FOLL_WRITE;
4981 if (mmap_read_lock_killable(mm))
4984 /* ignore errors, just check how much was successfully transferred */
4986 int bytes, ret, offset;
4988 struct page *page = NULL;
4990 ret = get_user_pages_remote(mm, addr, 1,
4991 gup_flags, &page, &vma, NULL);
4993 #ifndef CONFIG_HAVE_IOREMAP_PROT
4997 * Check if this is a VM_IO | VM_PFNMAP VMA, which
4998 * we can access using slightly different code.
5000 vma = vma_lookup(mm, addr);
5003 if (vma->vm_ops && vma->vm_ops->access)
5004 ret = vma->vm_ops->access(vma, addr, buf,
5012 offset = addr & (PAGE_SIZE-1);
5013 if (bytes > PAGE_SIZE-offset)
5014 bytes = PAGE_SIZE-offset;
5018 copy_to_user_page(vma, page, addr,
5019 maddr + offset, buf, bytes);
5020 set_page_dirty_lock(page);
5022 copy_from_user_page(vma, page, addr,
5023 buf, maddr + offset, bytes);
5032 mmap_read_unlock(mm);
5034 return buf - old_buf;
5038 * access_remote_vm - access another process' address space
5039 * @mm: the mm_struct of the target address space
5040 * @addr: start address to access
5041 * @buf: source or destination buffer
5042 * @len: number of bytes to transfer
5043 * @gup_flags: flags modifying lookup behaviour
5045 * The caller must hold a reference on @mm.
5047 * Return: number of bytes copied from source to destination.
5049 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
5050 void *buf, int len, unsigned int gup_flags)
5052 return __access_remote_vm(mm, addr, buf, len, gup_flags);
5056 * Access another process' address space.
5057 * Source/target buffer must be kernel space,
5058 * Do not walk the page table directly, use get_user_pages
5060 int access_process_vm(struct task_struct *tsk, unsigned long addr,
5061 void *buf, int len, unsigned int gup_flags)
5063 struct mm_struct *mm;
5066 mm = get_task_mm(tsk);
5070 ret = __access_remote_vm(mm, addr, buf, len, gup_flags);
5076 EXPORT_SYMBOL_GPL(access_process_vm);
5079 * Print the name of a VMA.
5081 void print_vma_addr(char *prefix, unsigned long ip)
5083 struct mm_struct *mm = current->mm;
5084 struct vm_area_struct *vma;
5087 * we might be running from an atomic context so we cannot sleep
5089 if (!mmap_read_trylock(mm))
5092 vma = find_vma(mm, ip);
5093 if (vma && vma->vm_file) {
5094 struct file *f = vma->vm_file;
5095 char *buf = (char *)__get_free_page(GFP_NOWAIT);
5099 p = file_path(f, buf, PAGE_SIZE);
5102 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
5104 vma->vm_end - vma->vm_start);
5105 free_page((unsigned long)buf);
5108 mmap_read_unlock(mm);
5111 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5112 void __might_fault(const char *file, int line)
5115 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
5116 * holding the mmap_lock, this is safe because kernel memory doesn't
5117 * get paged out, therefore we'll never actually fault, and the
5118 * below annotations will generate false positives.
5120 if (uaccess_kernel())
5122 if (pagefault_disabled())
5124 __might_sleep(file, line, 0);
5125 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5127 might_lock_read(¤t->mm->mmap_lock);
5130 EXPORT_SYMBOL(__might_fault);
5133 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
5135 * Process all subpages of the specified huge page with the specified
5136 * operation. The target subpage will be processed last to keep its
5139 static inline void process_huge_page(
5140 unsigned long addr_hint, unsigned int pages_per_huge_page,
5141 void (*process_subpage)(unsigned long addr, int idx, void *arg),
5145 unsigned long addr = addr_hint &
5146 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5148 /* Process target subpage last to keep its cache lines hot */
5150 n = (addr_hint - addr) / PAGE_SIZE;
5151 if (2 * n <= pages_per_huge_page) {
5152 /* If target subpage in first half of huge page */
5155 /* Process subpages at the end of huge page */
5156 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
5158 process_subpage(addr + i * PAGE_SIZE, i, arg);
5161 /* If target subpage in second half of huge page */
5162 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
5163 l = pages_per_huge_page - n;
5164 /* Process subpages at the begin of huge page */
5165 for (i = 0; i < base; i++) {
5167 process_subpage(addr + i * PAGE_SIZE, i, arg);
5171 * Process remaining subpages in left-right-left-right pattern
5172 * towards the target subpage
5174 for (i = 0; i < l; i++) {
5175 int left_idx = base + i;
5176 int right_idx = base + 2 * l - 1 - i;
5179 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
5181 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
5185 static void clear_gigantic_page(struct page *page,
5187 unsigned int pages_per_huge_page)
5190 struct page *p = page;
5193 for (i = 0; i < pages_per_huge_page;
5194 i++, p = mem_map_next(p, page, i)) {
5196 clear_user_highpage(p, addr + i * PAGE_SIZE);
5200 static void clear_subpage(unsigned long addr, int idx, void *arg)
5202 struct page *page = arg;
5204 clear_user_highpage(page + idx, addr);
5207 void clear_huge_page(struct page *page,
5208 unsigned long addr_hint, unsigned int pages_per_huge_page)
5210 unsigned long addr = addr_hint &
5211 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5213 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5214 clear_gigantic_page(page, addr, pages_per_huge_page);
5218 process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
5221 static void copy_user_gigantic_page(struct page *dst, struct page *src,
5223 struct vm_area_struct *vma,
5224 unsigned int pages_per_huge_page)
5227 struct page *dst_base = dst;
5228 struct page *src_base = src;
5230 for (i = 0; i < pages_per_huge_page; ) {
5232 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
5235 dst = mem_map_next(dst, dst_base, i);
5236 src = mem_map_next(src, src_base, i);
5240 struct copy_subpage_arg {
5243 struct vm_area_struct *vma;
5246 static void copy_subpage(unsigned long addr, int idx, void *arg)
5248 struct copy_subpage_arg *copy_arg = arg;
5250 copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
5251 addr, copy_arg->vma);
5254 void copy_user_huge_page(struct page *dst, struct page *src,
5255 unsigned long addr_hint, struct vm_area_struct *vma,
5256 unsigned int pages_per_huge_page)
5258 unsigned long addr = addr_hint &
5259 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5260 struct copy_subpage_arg arg = {
5266 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5267 copy_user_gigantic_page(dst, src, addr, vma,
5268 pages_per_huge_page);
5272 process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
5275 long copy_huge_page_from_user(struct page *dst_page,
5276 const void __user *usr_src,
5277 unsigned int pages_per_huge_page,
5278 bool allow_pagefault)
5280 void *src = (void *)usr_src;
5282 unsigned long i, rc = 0;
5283 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
5284 struct page *subpage = dst_page;
5286 for (i = 0; i < pages_per_huge_page;
5287 i++, subpage = mem_map_next(subpage, dst_page, i)) {
5288 if (allow_pagefault)
5289 page_kaddr = kmap(subpage);
5291 page_kaddr = kmap_atomic(subpage);
5292 rc = copy_from_user(page_kaddr,
5293 (const void __user *)(src + i * PAGE_SIZE),
5295 if (allow_pagefault)
5298 kunmap_atomic(page_kaddr);
5300 ret_val -= (PAGE_SIZE - rc);
5308 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
5310 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
5312 static struct kmem_cache *page_ptl_cachep;
5314 void __init ptlock_cache_init(void)
5316 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
5320 bool ptlock_alloc(struct page *page)
5324 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
5331 void ptlock_free(struct page *page)
5333 kmem_cache_free(page_ptl_cachep, page->ptl);