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/mm_inline.h>
45 #include <linux/sched/mm.h>
46 #include <linux/sched/coredump.h>
47 #include <linux/sched/numa_balancing.h>
48 #include <linux/sched/task.h>
49 #include <linux/hugetlb.h>
50 #include <linux/mman.h>
51 #include <linux/swap.h>
52 #include <linux/highmem.h>
53 #include <linux/pagemap.h>
54 #include <linux/memremap.h>
55 #include <linux/ksm.h>
56 #include <linux/rmap.h>
57 #include <linux/export.h>
58 #include <linux/delayacct.h>
59 #include <linux/init.h>
60 #include <linux/pfn_t.h>
61 #include <linux/writeback.h>
62 #include <linux/memcontrol.h>
63 #include <linux/mmu_notifier.h>
64 #include <linux/swapops.h>
65 #include <linux/elf.h>
66 #include <linux/gfp.h>
67 #include <linux/migrate.h>
68 #include <linux/string.h>
69 #include <linux/debugfs.h>
70 #include <linux/userfaultfd_k.h>
71 #include <linux/dax.h>
72 #include <linux/oom.h>
73 #include <linux/numa.h>
74 #include <linux/perf_event.h>
75 #include <linux/ptrace.h>
76 #include <linux/vmalloc.h>
77 #include <linux/mm_inline.h>
79 #include <trace/events/kmem.h>
82 #include <asm/mmu_context.h>
83 #include <asm/pgalloc.h>
84 #include <linux/uaccess.h>
86 #include <asm/tlbflush.h>
88 #include "pgalloc-track.h"
92 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
93 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
97 unsigned long max_mapnr;
98 EXPORT_SYMBOL(max_mapnr);
100 struct page *mem_map;
101 EXPORT_SYMBOL(mem_map);
104 static vm_fault_t do_fault(struct vm_fault *vmf);
107 * A number of key systems in x86 including ioremap() rely on the assumption
108 * that high_memory defines the upper bound on direct map memory, then end
109 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and
110 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
114 EXPORT_SYMBOL(high_memory);
117 * Randomize the address space (stacks, mmaps, brk, etc.).
119 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
120 * as ancient (libc5 based) binaries can segfault. )
122 int randomize_va_space __read_mostly =
123 #ifdef CONFIG_COMPAT_BRK
129 #ifndef arch_faults_on_old_pte
130 static inline bool arch_faults_on_old_pte(void)
133 * Those arches which don't have hw access flag feature need to
134 * implement their own helper. By default, "true" means pagefault
135 * will be hit on old pte.
141 #ifndef arch_wants_old_prefaulted_pte
142 static inline bool arch_wants_old_prefaulted_pte(void)
145 * Transitioning a PTE from 'old' to 'young' can be expensive on
146 * some architectures, even if it's performed in hardware. By
147 * default, "false" means prefaulted entries will be 'young'.
153 static int __init disable_randmaps(char *s)
155 randomize_va_space = 0;
158 __setup("norandmaps", disable_randmaps);
160 unsigned long zero_pfn __read_mostly;
161 EXPORT_SYMBOL(zero_pfn);
163 unsigned long highest_memmap_pfn __read_mostly;
166 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
168 static int __init init_zero_pfn(void)
170 zero_pfn = page_to_pfn(ZERO_PAGE(0));
173 early_initcall(init_zero_pfn);
175 void mm_trace_rss_stat(struct mm_struct *mm, int member, long count)
177 trace_rss_stat(mm, member, count);
180 #if defined(SPLIT_RSS_COUNTING)
182 void sync_mm_rss(struct mm_struct *mm)
186 for (i = 0; i < NR_MM_COUNTERS; i++) {
187 if (current->rss_stat.count[i]) {
188 add_mm_counter(mm, i, current->rss_stat.count[i]);
189 current->rss_stat.count[i] = 0;
192 current->rss_stat.events = 0;
195 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
197 struct task_struct *task = current;
199 if (likely(task->mm == mm))
200 task->rss_stat.count[member] += val;
202 add_mm_counter(mm, member, val);
204 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
205 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
207 /* sync counter once per 64 page faults */
208 #define TASK_RSS_EVENTS_THRESH (64)
209 static void check_sync_rss_stat(struct task_struct *task)
211 if (unlikely(task != current))
213 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
214 sync_mm_rss(task->mm);
216 #else /* SPLIT_RSS_COUNTING */
218 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
219 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
221 static void check_sync_rss_stat(struct task_struct *task)
225 #endif /* SPLIT_RSS_COUNTING */
228 * Note: this doesn't free the actual pages themselves. That
229 * has been handled earlier when unmapping all the memory regions.
231 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
234 pgtable_t token = pmd_pgtable(*pmd);
236 pte_free_tlb(tlb, token, addr);
237 mm_dec_nr_ptes(tlb->mm);
240 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
241 unsigned long addr, unsigned long end,
242 unsigned long floor, unsigned long ceiling)
249 pmd = pmd_offset(pud, addr);
251 next = pmd_addr_end(addr, end);
252 if (pmd_none_or_clear_bad(pmd))
254 free_pte_range(tlb, pmd, addr);
255 } while (pmd++, addr = next, addr != end);
265 if (end - 1 > ceiling - 1)
268 pmd = pmd_offset(pud, start);
270 pmd_free_tlb(tlb, pmd, start);
271 mm_dec_nr_pmds(tlb->mm);
274 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
275 unsigned long addr, unsigned long end,
276 unsigned long floor, unsigned long ceiling)
283 pud = pud_offset(p4d, addr);
285 next = pud_addr_end(addr, end);
286 if (pud_none_or_clear_bad(pud))
288 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
289 } while (pud++, addr = next, addr != end);
299 if (end - 1 > ceiling - 1)
302 pud = pud_offset(p4d, start);
304 pud_free_tlb(tlb, pud, start);
305 mm_dec_nr_puds(tlb->mm);
308 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
309 unsigned long addr, unsigned long end,
310 unsigned long floor, unsigned long ceiling)
317 p4d = p4d_offset(pgd, addr);
319 next = p4d_addr_end(addr, end);
320 if (p4d_none_or_clear_bad(p4d))
322 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
323 } while (p4d++, addr = next, addr != end);
329 ceiling &= PGDIR_MASK;
333 if (end - 1 > ceiling - 1)
336 p4d = p4d_offset(pgd, start);
338 p4d_free_tlb(tlb, p4d, start);
342 * This function frees user-level page tables of a process.
344 void free_pgd_range(struct mmu_gather *tlb,
345 unsigned long addr, unsigned long end,
346 unsigned long floor, unsigned long ceiling)
352 * The next few lines have given us lots of grief...
354 * Why are we testing PMD* at this top level? Because often
355 * there will be no work to do at all, and we'd prefer not to
356 * go all the way down to the bottom just to discover that.
358 * Why all these "- 1"s? Because 0 represents both the bottom
359 * of the address space and the top of it (using -1 for the
360 * top wouldn't help much: the masks would do the wrong thing).
361 * The rule is that addr 0 and floor 0 refer to the bottom of
362 * the address space, but end 0 and ceiling 0 refer to the top
363 * Comparisons need to use "end - 1" and "ceiling - 1" (though
364 * that end 0 case should be mythical).
366 * Wherever addr is brought up or ceiling brought down, we must
367 * be careful to reject "the opposite 0" before it confuses the
368 * subsequent tests. But what about where end is brought down
369 * by PMD_SIZE below? no, end can't go down to 0 there.
371 * Whereas we round start (addr) and ceiling down, by different
372 * masks at different levels, in order to test whether a table
373 * now has no other vmas using it, so can be freed, we don't
374 * bother to round floor or end up - the tests don't need that.
388 if (end - 1 > ceiling - 1)
393 * We add page table cache pages with PAGE_SIZE,
394 * (see pte_free_tlb()), flush the tlb if we need
396 tlb_change_page_size(tlb, PAGE_SIZE);
397 pgd = pgd_offset(tlb->mm, addr);
399 next = pgd_addr_end(addr, end);
400 if (pgd_none_or_clear_bad(pgd))
402 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
403 } while (pgd++, addr = next, addr != end);
406 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
407 unsigned long floor, unsigned long ceiling)
410 struct vm_area_struct *next = vma->vm_next;
411 unsigned long addr = vma->vm_start;
414 * Hide vma from rmap and truncate_pagecache before freeing
417 unlink_anon_vmas(vma);
418 unlink_file_vma(vma);
420 if (is_vm_hugetlb_page(vma)) {
421 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
422 floor, next ? next->vm_start : ceiling);
425 * Optimization: gather nearby vmas into one call down
427 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
428 && !is_vm_hugetlb_page(next)) {
431 unlink_anon_vmas(vma);
432 unlink_file_vma(vma);
434 free_pgd_range(tlb, addr, vma->vm_end,
435 floor, next ? next->vm_start : ceiling);
441 void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte)
443 spinlock_t *ptl = pmd_lock(mm, pmd);
445 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
448 * Ensure all pte setup (eg. pte page lock and page clearing) are
449 * visible before the pte is made visible to other CPUs by being
450 * put into page tables.
452 * The other side of the story is the pointer chasing in the page
453 * table walking code (when walking the page table without locking;
454 * ie. most of the time). Fortunately, these data accesses consist
455 * of a chain of data-dependent loads, meaning most CPUs (alpha
456 * being the notable exception) will already guarantee loads are
457 * seen in-order. See the alpha page table accessors for the
458 * smp_rmb() barriers in page table walking code.
460 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
461 pmd_populate(mm, pmd, *pte);
467 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
469 pgtable_t new = pte_alloc_one(mm);
473 pmd_install(mm, pmd, &new);
479 int __pte_alloc_kernel(pmd_t *pmd)
481 pte_t *new = pte_alloc_one_kernel(&init_mm);
485 spin_lock(&init_mm.page_table_lock);
486 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
487 smp_wmb(); /* See comment in pmd_install() */
488 pmd_populate_kernel(&init_mm, pmd, new);
491 spin_unlock(&init_mm.page_table_lock);
493 pte_free_kernel(&init_mm, new);
497 static inline void init_rss_vec(int *rss)
499 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
502 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
506 if (current->mm == mm)
508 for (i = 0; i < NR_MM_COUNTERS; i++)
510 add_mm_counter(mm, i, rss[i]);
514 * This function is called to print an error when a bad pte
515 * is found. For example, we might have a PFN-mapped pte in
516 * a region that doesn't allow it.
518 * The calling function must still handle the error.
520 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
521 pte_t pte, struct page *page)
523 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
524 p4d_t *p4d = p4d_offset(pgd, addr);
525 pud_t *pud = pud_offset(p4d, addr);
526 pmd_t *pmd = pmd_offset(pud, addr);
527 struct address_space *mapping;
529 static unsigned long resume;
530 static unsigned long nr_shown;
531 static unsigned long nr_unshown;
534 * Allow a burst of 60 reports, then keep quiet for that minute;
535 * or allow a steady drip of one report per second.
537 if (nr_shown == 60) {
538 if (time_before(jiffies, resume)) {
543 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
550 resume = jiffies + 60 * HZ;
552 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
553 index = linear_page_index(vma, addr);
555 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
557 (long long)pte_val(pte), (long long)pmd_val(*pmd));
559 dump_page(page, "bad pte");
560 pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n",
561 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
562 pr_alert("file:%pD fault:%ps mmap:%ps readpage:%ps\n",
564 vma->vm_ops ? vma->vm_ops->fault : NULL,
565 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
566 mapping ? mapping->a_ops->readpage : NULL);
568 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
572 * vm_normal_page -- This function gets the "struct page" associated with a pte.
574 * "Special" mappings do not wish to be associated with a "struct page" (either
575 * it doesn't exist, or it exists but they don't want to touch it). In this
576 * case, NULL is returned here. "Normal" mappings do have a struct page.
578 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
579 * pte bit, in which case this function is trivial. Secondly, an architecture
580 * may not have a spare pte bit, which requires a more complicated scheme,
583 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
584 * special mapping (even if there are underlying and valid "struct pages").
585 * COWed pages of a VM_PFNMAP are always normal.
587 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
588 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
589 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
590 * mapping will always honor the rule
592 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
594 * And for normal mappings this is false.
596 * This restricts such mappings to be a linear translation from virtual address
597 * to pfn. To get around this restriction, we allow arbitrary mappings so long
598 * as the vma is not a COW mapping; in that case, we know that all ptes are
599 * special (because none can have been COWed).
602 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
604 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
605 * page" backing, however the difference is that _all_ pages with a struct
606 * page (that is, those where pfn_valid is true) are refcounted and considered
607 * normal pages by the VM. The disadvantage is that pages are refcounted
608 * (which can be slower and simply not an option for some PFNMAP users). The
609 * advantage is that we don't have to follow the strict linearity rule of
610 * PFNMAP mappings in order to support COWable mappings.
613 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
616 unsigned long pfn = pte_pfn(pte);
618 if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
619 if (likely(!pte_special(pte)))
621 if (vma->vm_ops && vma->vm_ops->find_special_page)
622 return vma->vm_ops->find_special_page(vma, addr);
623 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
625 if (is_zero_pfn(pfn))
630 print_bad_pte(vma, addr, pte, NULL);
634 /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
636 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
637 if (vma->vm_flags & VM_MIXEDMAP) {
643 off = (addr - vma->vm_start) >> PAGE_SHIFT;
644 if (pfn == vma->vm_pgoff + off)
646 if (!is_cow_mapping(vma->vm_flags))
651 if (is_zero_pfn(pfn))
655 if (unlikely(pfn > highest_memmap_pfn)) {
656 print_bad_pte(vma, addr, pte, NULL);
661 * NOTE! We still have PageReserved() pages in the page tables.
662 * eg. VDSO mappings can cause them to exist.
665 return pfn_to_page(pfn);
668 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
669 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
672 unsigned long pfn = pmd_pfn(pmd);
675 * There is no pmd_special() but there may be special pmds, e.g.
676 * in a direct-access (dax) mapping, so let's just replicate the
677 * !CONFIG_ARCH_HAS_PTE_SPECIAL case from vm_normal_page() here.
679 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
680 if (vma->vm_flags & VM_MIXEDMAP) {
686 off = (addr - vma->vm_start) >> PAGE_SHIFT;
687 if (pfn == vma->vm_pgoff + off)
689 if (!is_cow_mapping(vma->vm_flags))
696 if (is_huge_zero_pmd(pmd))
698 if (unlikely(pfn > highest_memmap_pfn))
702 * NOTE! We still have PageReserved() pages in the page tables.
703 * eg. VDSO mappings can cause them to exist.
706 return pfn_to_page(pfn);
710 static void restore_exclusive_pte(struct vm_area_struct *vma,
711 struct page *page, unsigned long address,
717 pte = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot)));
718 if (pte_swp_soft_dirty(*ptep))
719 pte = pte_mksoft_dirty(pte);
721 entry = pte_to_swp_entry(*ptep);
722 if (pte_swp_uffd_wp(*ptep))
723 pte = pte_mkuffd_wp(pte);
724 else if (is_writable_device_exclusive_entry(entry))
725 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
727 VM_BUG_ON(pte_write(pte) && !(PageAnon(page) && PageAnonExclusive(page)));
730 * No need to take a page reference as one was already
731 * created when the swap entry was made.
734 page_add_anon_rmap(page, vma, address, RMAP_NONE);
737 * Currently device exclusive access only supports anonymous
738 * memory so the entry shouldn't point to a filebacked page.
740 WARN_ON_ONCE(!PageAnon(page));
742 set_pte_at(vma->vm_mm, address, ptep, pte);
745 * No need to invalidate - it was non-present before. However
746 * secondary CPUs may have mappings that need invalidating.
748 update_mmu_cache(vma, address, ptep);
752 * Tries to restore an exclusive pte if the page lock can be acquired without
756 try_restore_exclusive_pte(pte_t *src_pte, struct vm_area_struct *vma,
759 swp_entry_t entry = pte_to_swp_entry(*src_pte);
760 struct page *page = pfn_swap_entry_to_page(entry);
762 if (trylock_page(page)) {
763 restore_exclusive_pte(vma, page, addr, src_pte);
772 * copy one vm_area from one task to the other. Assumes the page tables
773 * already present in the new task to be cleared in the whole range
774 * covered by this vma.
778 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
779 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *dst_vma,
780 struct vm_area_struct *src_vma, unsigned long addr, int *rss)
782 unsigned long vm_flags = dst_vma->vm_flags;
783 pte_t pte = *src_pte;
785 swp_entry_t entry = pte_to_swp_entry(pte);
787 if (likely(!non_swap_entry(entry))) {
788 if (swap_duplicate(entry) < 0)
791 /* make sure dst_mm is on swapoff's mmlist. */
792 if (unlikely(list_empty(&dst_mm->mmlist))) {
793 spin_lock(&mmlist_lock);
794 if (list_empty(&dst_mm->mmlist))
795 list_add(&dst_mm->mmlist,
797 spin_unlock(&mmlist_lock);
799 /* Mark the swap entry as shared. */
800 if (pte_swp_exclusive(*src_pte)) {
801 pte = pte_swp_clear_exclusive(*src_pte);
802 set_pte_at(src_mm, addr, src_pte, pte);
805 } else if (is_migration_entry(entry)) {
806 page = pfn_swap_entry_to_page(entry);
808 rss[mm_counter(page)]++;
810 if (!is_readable_migration_entry(entry) &&
811 is_cow_mapping(vm_flags)) {
813 * COW mappings require pages in both parent and child
814 * to be set to read. A previously exclusive entry is
817 entry = make_readable_migration_entry(
819 pte = swp_entry_to_pte(entry);
820 if (pte_swp_soft_dirty(*src_pte))
821 pte = pte_swp_mksoft_dirty(pte);
822 if (pte_swp_uffd_wp(*src_pte))
823 pte = pte_swp_mkuffd_wp(pte);
824 set_pte_at(src_mm, addr, src_pte, pte);
826 } else if (is_device_private_entry(entry)) {
827 page = pfn_swap_entry_to_page(entry);
830 * Update rss count even for unaddressable pages, as
831 * they should treated just like normal pages in this
834 * We will likely want to have some new rss counters
835 * for unaddressable pages, at some point. But for now
836 * keep things as they are.
839 rss[mm_counter(page)]++;
840 /* Cannot fail as these pages cannot get pinned. */
841 BUG_ON(page_try_dup_anon_rmap(page, false, src_vma));
844 * We do not preserve soft-dirty information, because so
845 * far, checkpoint/restore is the only feature that
846 * requires that. And checkpoint/restore does not work
847 * when a device driver is involved (you cannot easily
848 * save and restore device driver state).
850 if (is_writable_device_private_entry(entry) &&
851 is_cow_mapping(vm_flags)) {
852 entry = make_readable_device_private_entry(
854 pte = swp_entry_to_pte(entry);
855 if (pte_swp_uffd_wp(*src_pte))
856 pte = pte_swp_mkuffd_wp(pte);
857 set_pte_at(src_mm, addr, src_pte, pte);
859 } else if (is_device_exclusive_entry(entry)) {
861 * Make device exclusive entries present by restoring the
862 * original entry then copying as for a present pte. Device
863 * exclusive entries currently only support private writable
864 * (ie. COW) mappings.
866 VM_BUG_ON(!is_cow_mapping(src_vma->vm_flags));
867 if (try_restore_exclusive_pte(src_pte, src_vma, addr))
871 if (!userfaultfd_wp(dst_vma))
872 pte = pte_swp_clear_uffd_wp(pte);
873 set_pte_at(dst_mm, addr, dst_pte, pte);
878 * Copy a present and normal page.
880 * NOTE! The usual case is that this isn't required;
881 * instead, the caller can just increase the page refcount
882 * and re-use the pte the traditional way.
884 * And if we need a pre-allocated page but don't yet have
885 * one, return a negative error to let the preallocation
886 * code know so that it can do so outside the page table
890 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
891 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
892 struct page **prealloc, struct page *page)
894 struct page *new_page;
897 new_page = *prealloc;
902 * We have a prealloc page, all good! Take it
903 * over and copy the page & arm it.
906 copy_user_highpage(new_page, page, addr, src_vma);
907 __SetPageUptodate(new_page);
908 page_add_new_anon_rmap(new_page, dst_vma, addr);
909 lru_cache_add_inactive_or_unevictable(new_page, dst_vma);
910 rss[mm_counter(new_page)]++;
912 /* All done, just insert the new page copy in the child */
913 pte = mk_pte(new_page, dst_vma->vm_page_prot);
914 pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
915 if (userfaultfd_pte_wp(dst_vma, *src_pte))
916 /* Uffd-wp needs to be delivered to dest pte as well */
917 pte = pte_wrprotect(pte_mkuffd_wp(pte));
918 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
923 * Copy one pte. Returns 0 if succeeded, or -EAGAIN if one preallocated page
924 * is required to copy this pte.
927 copy_present_pte(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
928 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
929 struct page **prealloc)
931 struct mm_struct *src_mm = src_vma->vm_mm;
932 unsigned long vm_flags = src_vma->vm_flags;
933 pte_t pte = *src_pte;
936 page = vm_normal_page(src_vma, addr, pte);
937 if (page && PageAnon(page)) {
939 * If this page may have been pinned by the parent process,
940 * copy the page immediately for the child so that we'll always
941 * guarantee the pinned page won't be randomly replaced in the
945 if (unlikely(page_try_dup_anon_rmap(page, false, src_vma))) {
946 /* Page maybe pinned, we have to copy. */
948 return copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
949 addr, rss, prealloc, page);
951 rss[mm_counter(page)]++;
954 page_dup_file_rmap(page, false);
955 rss[mm_counter(page)]++;
959 * If it's a COW mapping, write protect it both
960 * in the parent and the child
962 if (is_cow_mapping(vm_flags) && pte_write(pte)) {
963 ptep_set_wrprotect(src_mm, addr, src_pte);
964 pte = pte_wrprotect(pte);
966 VM_BUG_ON(page && PageAnon(page) && PageAnonExclusive(page));
969 * If it's a shared mapping, mark it clean in
972 if (vm_flags & VM_SHARED)
973 pte = pte_mkclean(pte);
974 pte = pte_mkold(pte);
976 if (!userfaultfd_wp(dst_vma))
977 pte = pte_clear_uffd_wp(pte);
979 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
983 static inline struct page *
984 page_copy_prealloc(struct mm_struct *src_mm, struct vm_area_struct *vma,
987 struct page *new_page;
989 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, addr);
993 if (mem_cgroup_charge(page_folio(new_page), src_mm, GFP_KERNEL)) {
997 cgroup_throttle_swaprate(new_page, GFP_KERNEL);
1003 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1004 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1007 struct mm_struct *dst_mm = dst_vma->vm_mm;
1008 struct mm_struct *src_mm = src_vma->vm_mm;
1009 pte_t *orig_src_pte, *orig_dst_pte;
1010 pte_t *src_pte, *dst_pte;
1011 spinlock_t *src_ptl, *dst_ptl;
1012 int progress, ret = 0;
1013 int rss[NR_MM_COUNTERS];
1014 swp_entry_t entry = (swp_entry_t){0};
1015 struct page *prealloc = NULL;
1021 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
1026 src_pte = pte_offset_map(src_pmd, addr);
1027 src_ptl = pte_lockptr(src_mm, src_pmd);
1028 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1029 orig_src_pte = src_pte;
1030 orig_dst_pte = dst_pte;
1031 arch_enter_lazy_mmu_mode();
1035 * We are holding two locks at this point - either of them
1036 * could generate latencies in another task on another CPU.
1038 if (progress >= 32) {
1040 if (need_resched() ||
1041 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
1044 if (pte_none(*src_pte)) {
1048 if (unlikely(!pte_present(*src_pte))) {
1049 ret = copy_nonpresent_pte(dst_mm, src_mm,
1054 entry = pte_to_swp_entry(*src_pte);
1056 } else if (ret == -EBUSY) {
1064 * Device exclusive entry restored, continue by copying
1065 * the now present pte.
1067 WARN_ON_ONCE(ret != -ENOENT);
1069 /* copy_present_pte() will clear `*prealloc' if consumed */
1070 ret = copy_present_pte(dst_vma, src_vma, dst_pte, src_pte,
1071 addr, rss, &prealloc);
1073 * If we need a pre-allocated page for this pte, drop the
1074 * locks, allocate, and try again.
1076 if (unlikely(ret == -EAGAIN))
1078 if (unlikely(prealloc)) {
1080 * pre-alloc page cannot be reused by next time so as
1081 * to strictly follow mempolicy (e.g., alloc_page_vma()
1082 * will allocate page according to address). This
1083 * could only happen if one pinned pte changed.
1089 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
1091 arch_leave_lazy_mmu_mode();
1092 spin_unlock(src_ptl);
1093 pte_unmap(orig_src_pte);
1094 add_mm_rss_vec(dst_mm, rss);
1095 pte_unmap_unlock(orig_dst_pte, dst_ptl);
1099 VM_WARN_ON_ONCE(!entry.val);
1100 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
1105 } else if (ret == -EBUSY) {
1107 } else if (ret == -EAGAIN) {
1108 prealloc = page_copy_prealloc(src_mm, src_vma, addr);
1115 /* We've captured and resolved the error. Reset, try again. */
1121 if (unlikely(prealloc))
1127 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1128 pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1131 struct mm_struct *dst_mm = dst_vma->vm_mm;
1132 struct mm_struct *src_mm = src_vma->vm_mm;
1133 pmd_t *src_pmd, *dst_pmd;
1136 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1139 src_pmd = pmd_offset(src_pud, addr);
1141 next = pmd_addr_end(addr, end);
1142 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1143 || pmd_devmap(*src_pmd)) {
1145 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
1146 err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd,
1147 addr, dst_vma, src_vma);
1154 if (pmd_none_or_clear_bad(src_pmd))
1156 if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
1159 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1164 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1165 p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
1168 struct mm_struct *dst_mm = dst_vma->vm_mm;
1169 struct mm_struct *src_mm = src_vma->vm_mm;
1170 pud_t *src_pud, *dst_pud;
1173 dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1176 src_pud = pud_offset(src_p4d, addr);
1178 next = pud_addr_end(addr, end);
1179 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1182 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
1183 err = copy_huge_pud(dst_mm, src_mm,
1184 dst_pud, src_pud, addr, src_vma);
1191 if (pud_none_or_clear_bad(src_pud))
1193 if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
1196 } while (dst_pud++, src_pud++, addr = next, addr != end);
1201 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1202 pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
1205 struct mm_struct *dst_mm = dst_vma->vm_mm;
1206 p4d_t *src_p4d, *dst_p4d;
1209 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1212 src_p4d = p4d_offset(src_pgd, addr);
1214 next = p4d_addr_end(addr, end);
1215 if (p4d_none_or_clear_bad(src_p4d))
1217 if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
1220 } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1225 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1227 pgd_t *src_pgd, *dst_pgd;
1229 unsigned long addr = src_vma->vm_start;
1230 unsigned long end = src_vma->vm_end;
1231 struct mm_struct *dst_mm = dst_vma->vm_mm;
1232 struct mm_struct *src_mm = src_vma->vm_mm;
1233 struct mmu_notifier_range range;
1238 * Don't copy ptes where a page fault will fill them correctly.
1239 * Fork becomes much lighter when there are big shared or private
1240 * readonly mappings. The tradeoff is that copy_page_range is more
1241 * efficient than faulting.
1243 if (!(src_vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1247 if (is_vm_hugetlb_page(src_vma))
1248 return copy_hugetlb_page_range(dst_mm, src_mm, src_vma);
1250 if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
1252 * We do not free on error cases below as remove_vma
1253 * gets called on error from higher level routine
1255 ret = track_pfn_copy(src_vma);
1261 * We need to invalidate the secondary MMU mappings only when
1262 * there could be a permission downgrade on the ptes of the
1263 * parent mm. And a permission downgrade will only happen if
1264 * is_cow_mapping() returns true.
1266 is_cow = is_cow_mapping(src_vma->vm_flags);
1269 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
1270 0, src_vma, src_mm, addr, end);
1271 mmu_notifier_invalidate_range_start(&range);
1273 * Disabling preemption is not needed for the write side, as
1274 * the read side doesn't spin, but goes to the mmap_lock.
1276 * Use the raw variant of the seqcount_t write API to avoid
1277 * lockdep complaining about preemptibility.
1279 mmap_assert_write_locked(src_mm);
1280 raw_write_seqcount_begin(&src_mm->write_protect_seq);
1284 dst_pgd = pgd_offset(dst_mm, addr);
1285 src_pgd = pgd_offset(src_mm, addr);
1287 next = pgd_addr_end(addr, end);
1288 if (pgd_none_or_clear_bad(src_pgd))
1290 if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
1295 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1298 raw_write_seqcount_end(&src_mm->write_protect_seq);
1299 mmu_notifier_invalidate_range_end(&range);
1305 * Parameter block passed down to zap_pte_range in exceptional cases.
1307 struct zap_details {
1308 struct folio *single_folio; /* Locked folio to be unmapped */
1309 bool even_cows; /* Zap COWed private pages too? */
1310 zap_flags_t zap_flags; /* Extra flags for zapping */
1313 /* Whether we should zap all COWed (private) pages too */
1314 static inline bool should_zap_cows(struct zap_details *details)
1316 /* By default, zap all pages */
1320 /* Or, we zap COWed pages only if the caller wants to */
1321 return details->even_cows;
1324 /* Decides whether we should zap this page with the page pointer specified */
1325 static inline bool should_zap_page(struct zap_details *details, struct page *page)
1327 /* If we can make a decision without *page.. */
1328 if (should_zap_cows(details))
1331 /* E.g. the caller passes NULL for the case of a zero page */
1335 /* Otherwise we should only zap non-anon pages */
1336 return !PageAnon(page);
1339 static inline bool zap_drop_file_uffd_wp(struct zap_details *details)
1344 return details->zap_flags & ZAP_FLAG_DROP_MARKER;
1348 * This function makes sure that we'll replace the none pte with an uffd-wp
1349 * swap special pte marker when necessary. Must be with the pgtable lock held.
1352 zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
1353 unsigned long addr, pte_t *pte,
1354 struct zap_details *details, pte_t pteval)
1356 if (zap_drop_file_uffd_wp(details))
1359 pte_install_uffd_wp_if_needed(vma, addr, pte, pteval);
1362 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1363 struct vm_area_struct *vma, pmd_t *pmd,
1364 unsigned long addr, unsigned long end,
1365 struct zap_details *details)
1367 struct mm_struct *mm = tlb->mm;
1368 int force_flush = 0;
1369 int rss[NR_MM_COUNTERS];
1375 tlb_change_page_size(tlb, PAGE_SIZE);
1378 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1380 flush_tlb_batched_pending(mm);
1381 arch_enter_lazy_mmu_mode();
1386 if (pte_none(ptent))
1392 if (pte_present(ptent)) {
1393 page = vm_normal_page(vma, addr, ptent);
1394 if (unlikely(!should_zap_page(details, page)))
1396 ptent = ptep_get_and_clear_full(mm, addr, pte,
1398 tlb_remove_tlb_entry(tlb, pte, addr);
1399 zap_install_uffd_wp_if_needed(vma, addr, pte, details,
1401 if (unlikely(!page))
1404 if (!PageAnon(page)) {
1405 if (pte_dirty(ptent)) {
1407 set_page_dirty(page);
1409 if (pte_young(ptent) &&
1410 likely(!(vma->vm_flags & VM_SEQ_READ)))
1411 mark_page_accessed(page);
1413 rss[mm_counter(page)]--;
1414 page_remove_rmap(page, vma, false);
1415 if (unlikely(page_mapcount(page) < 0))
1416 print_bad_pte(vma, addr, ptent, page);
1417 if (unlikely(__tlb_remove_page(tlb, page))) {
1425 entry = pte_to_swp_entry(ptent);
1426 if (is_device_private_entry(entry) ||
1427 is_device_exclusive_entry(entry)) {
1428 page = pfn_swap_entry_to_page(entry);
1429 if (unlikely(!should_zap_page(details, page)))
1432 * Both device private/exclusive mappings should only
1433 * work with anonymous page so far, so we don't need to
1434 * consider uffd-wp bit when zap. For more information,
1435 * see zap_install_uffd_wp_if_needed().
1437 WARN_ON_ONCE(!vma_is_anonymous(vma));
1438 rss[mm_counter(page)]--;
1439 if (is_device_private_entry(entry))
1440 page_remove_rmap(page, vma, false);
1442 } else if (!non_swap_entry(entry)) {
1443 /* Genuine swap entry, hence a private anon page */
1444 if (!should_zap_cows(details))
1447 if (unlikely(!free_swap_and_cache(entry)))
1448 print_bad_pte(vma, addr, ptent, NULL);
1449 } else if (is_migration_entry(entry)) {
1450 page = pfn_swap_entry_to_page(entry);
1451 if (!should_zap_page(details, page))
1453 rss[mm_counter(page)]--;
1454 } else if (pte_marker_entry_uffd_wp(entry)) {
1455 /* Only drop the uffd-wp marker if explicitly requested */
1456 if (!zap_drop_file_uffd_wp(details))
1458 } else if (is_hwpoison_entry(entry)) {
1459 if (!should_zap_cows(details))
1462 /* We should have covered all the swap entry types */
1465 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1466 zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
1467 } while (pte++, addr += PAGE_SIZE, addr != end);
1469 add_mm_rss_vec(mm, rss);
1470 arch_leave_lazy_mmu_mode();
1472 /* Do the actual TLB flush before dropping ptl */
1474 tlb_flush_mmu_tlbonly(tlb);
1475 pte_unmap_unlock(start_pte, ptl);
1478 * If we forced a TLB flush (either due to running out of
1479 * batch buffers or because we needed to flush dirty TLB
1480 * entries before releasing the ptl), free the batched
1481 * memory too. Restart if we didn't do everything.
1496 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1497 struct vm_area_struct *vma, pud_t *pud,
1498 unsigned long addr, unsigned long end,
1499 struct zap_details *details)
1504 pmd = pmd_offset(pud, addr);
1506 next = pmd_addr_end(addr, end);
1507 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1508 if (next - addr != HPAGE_PMD_SIZE)
1509 __split_huge_pmd(vma, pmd, addr, false, NULL);
1510 else if (zap_huge_pmd(tlb, vma, pmd, addr))
1513 } else if (details && details->single_folio &&
1514 folio_test_pmd_mappable(details->single_folio) &&
1515 next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) {
1516 spinlock_t *ptl = pmd_lock(tlb->mm, pmd);
1518 * Take and drop THP pmd lock so that we cannot return
1519 * prematurely, while zap_huge_pmd() has cleared *pmd,
1520 * but not yet decremented compound_mapcount().
1526 * Here there can be other concurrent MADV_DONTNEED or
1527 * trans huge page faults running, and if the pmd is
1528 * none or trans huge it can change under us. This is
1529 * because MADV_DONTNEED holds the mmap_lock in read
1532 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1534 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1537 } while (pmd++, addr = next, addr != end);
1542 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1543 struct vm_area_struct *vma, p4d_t *p4d,
1544 unsigned long addr, unsigned long end,
1545 struct zap_details *details)
1550 pud = pud_offset(p4d, addr);
1552 next = pud_addr_end(addr, end);
1553 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1554 if (next - addr != HPAGE_PUD_SIZE) {
1555 mmap_assert_locked(tlb->mm);
1556 split_huge_pud(vma, pud, addr);
1557 } else if (zap_huge_pud(tlb, vma, pud, addr))
1561 if (pud_none_or_clear_bad(pud))
1563 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1566 } while (pud++, addr = next, addr != end);
1571 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1572 struct vm_area_struct *vma, pgd_t *pgd,
1573 unsigned long addr, unsigned long end,
1574 struct zap_details *details)
1579 p4d = p4d_offset(pgd, addr);
1581 next = p4d_addr_end(addr, end);
1582 if (p4d_none_or_clear_bad(p4d))
1584 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1585 } while (p4d++, addr = next, addr != end);
1590 void unmap_page_range(struct mmu_gather *tlb,
1591 struct vm_area_struct *vma,
1592 unsigned long addr, unsigned long end,
1593 struct zap_details *details)
1598 BUG_ON(addr >= end);
1599 tlb_start_vma(tlb, vma);
1600 pgd = pgd_offset(vma->vm_mm, addr);
1602 next = pgd_addr_end(addr, end);
1603 if (pgd_none_or_clear_bad(pgd))
1605 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1606 } while (pgd++, addr = next, addr != end);
1607 tlb_end_vma(tlb, vma);
1611 static void unmap_single_vma(struct mmu_gather *tlb,
1612 struct vm_area_struct *vma, unsigned long start_addr,
1613 unsigned long end_addr,
1614 struct zap_details *details)
1616 unsigned long start = max(vma->vm_start, start_addr);
1619 if (start >= vma->vm_end)
1621 end = min(vma->vm_end, end_addr);
1622 if (end <= vma->vm_start)
1626 uprobe_munmap(vma, start, end);
1628 if (unlikely(vma->vm_flags & VM_PFNMAP))
1629 untrack_pfn(vma, 0, 0);
1632 if (unlikely(is_vm_hugetlb_page(vma))) {
1634 * It is undesirable to test vma->vm_file as it
1635 * should be non-null for valid hugetlb area.
1636 * However, vm_file will be NULL in the error
1637 * cleanup path of mmap_region. When
1638 * hugetlbfs ->mmap method fails,
1639 * mmap_region() nullifies vma->vm_file
1640 * before calling this function to clean up.
1641 * Since no pte has actually been setup, it is
1642 * safe to do nothing in this case.
1645 i_mmap_lock_write(vma->vm_file->f_mapping);
1646 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1647 i_mmap_unlock_write(vma->vm_file->f_mapping);
1650 unmap_page_range(tlb, vma, start, end, details);
1655 * unmap_vmas - unmap a range of memory covered by a list of vma's
1656 * @tlb: address of the caller's struct mmu_gather
1657 * @vma: the starting vma
1658 * @start_addr: virtual address at which to start unmapping
1659 * @end_addr: virtual address at which to end unmapping
1661 * Unmap all pages in the vma list.
1663 * Only addresses between `start' and `end' will be unmapped.
1665 * The VMA list must be sorted in ascending virtual address order.
1667 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1668 * range after unmap_vmas() returns. So the only responsibility here is to
1669 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1670 * drops the lock and schedules.
1672 void unmap_vmas(struct mmu_gather *tlb,
1673 struct vm_area_struct *vma, unsigned long start_addr,
1674 unsigned long end_addr)
1676 struct mmu_notifier_range range;
1677 struct zap_details details = {
1678 .zap_flags = ZAP_FLAG_DROP_MARKER,
1679 /* Careful - we need to zap private pages too! */
1683 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
1684 start_addr, end_addr);
1685 mmu_notifier_invalidate_range_start(&range);
1686 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1687 unmap_single_vma(tlb, vma, start_addr, end_addr, &details);
1688 mmu_notifier_invalidate_range_end(&range);
1692 * zap_page_range - remove user pages in a given range
1693 * @vma: vm_area_struct holding the applicable pages
1694 * @start: starting address of pages to zap
1695 * @size: number of bytes to zap
1697 * Caller must protect the VMA list
1699 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1702 struct mmu_notifier_range range;
1703 struct mmu_gather tlb;
1706 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1707 start, start + size);
1708 tlb_gather_mmu(&tlb, vma->vm_mm);
1709 update_hiwater_rss(vma->vm_mm);
1710 mmu_notifier_invalidate_range_start(&range);
1711 for ( ; vma && vma->vm_start < range.end; vma = vma->vm_next)
1712 unmap_single_vma(&tlb, vma, start, range.end, NULL);
1713 mmu_notifier_invalidate_range_end(&range);
1714 tlb_finish_mmu(&tlb);
1718 * zap_page_range_single - remove user pages in a given range
1719 * @vma: vm_area_struct holding the applicable pages
1720 * @address: starting address of pages to zap
1721 * @size: number of bytes to zap
1722 * @details: details of shared cache invalidation
1724 * The range must fit into one VMA.
1726 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1727 unsigned long size, struct zap_details *details)
1729 struct mmu_notifier_range range;
1730 struct mmu_gather tlb;
1733 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1734 address, address + size);
1735 tlb_gather_mmu(&tlb, vma->vm_mm);
1736 update_hiwater_rss(vma->vm_mm);
1737 mmu_notifier_invalidate_range_start(&range);
1738 unmap_single_vma(&tlb, vma, address, range.end, details);
1739 mmu_notifier_invalidate_range_end(&range);
1740 tlb_finish_mmu(&tlb);
1744 * zap_vma_ptes - remove ptes mapping the vma
1745 * @vma: vm_area_struct holding ptes to be zapped
1746 * @address: starting address of pages to zap
1747 * @size: number of bytes to zap
1749 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1751 * The entire address range must be fully contained within the vma.
1754 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1757 if (!range_in_vma(vma, address, address + size) ||
1758 !(vma->vm_flags & VM_PFNMAP))
1761 zap_page_range_single(vma, address, size, NULL);
1763 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1765 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
1772 pgd = pgd_offset(mm, addr);
1773 p4d = p4d_alloc(mm, pgd, addr);
1776 pud = pud_alloc(mm, p4d, addr);
1779 pmd = pmd_alloc(mm, pud, addr);
1783 VM_BUG_ON(pmd_trans_huge(*pmd));
1787 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1790 pmd_t *pmd = walk_to_pmd(mm, addr);
1794 return pte_alloc_map_lock(mm, pmd, addr, ptl);
1797 static int validate_page_before_insert(struct page *page)
1799 if (PageAnon(page) || PageSlab(page) || page_has_type(page))
1801 flush_dcache_page(page);
1805 static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
1806 unsigned long addr, struct page *page, pgprot_t prot)
1808 if (!pte_none(*pte))
1810 /* Ok, finally just insert the thing.. */
1812 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
1813 page_add_file_rmap(page, vma, false);
1814 set_pte_at(vma->vm_mm, addr, pte, mk_pte(page, prot));
1819 * This is the old fallback for page remapping.
1821 * For historical reasons, it only allows reserved pages. Only
1822 * old drivers should use this, and they needed to mark their
1823 * pages reserved for the old functions anyway.
1825 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1826 struct page *page, pgprot_t prot)
1832 retval = validate_page_before_insert(page);
1836 pte = get_locked_pte(vma->vm_mm, addr, &ptl);
1839 retval = insert_page_into_pte_locked(vma, pte, addr, page, prot);
1840 pte_unmap_unlock(pte, ptl);
1846 static int insert_page_in_batch_locked(struct vm_area_struct *vma, pte_t *pte,
1847 unsigned long addr, struct page *page, pgprot_t prot)
1851 if (!page_count(page))
1853 err = validate_page_before_insert(page);
1856 return insert_page_into_pte_locked(vma, pte, addr, page, prot);
1859 /* insert_pages() amortizes the cost of spinlock operations
1860 * when inserting pages in a loop. Arch *must* define pte_index.
1862 static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
1863 struct page **pages, unsigned long *num, pgprot_t prot)
1866 pte_t *start_pte, *pte;
1867 spinlock_t *pte_lock;
1868 struct mm_struct *const mm = vma->vm_mm;
1869 unsigned long curr_page_idx = 0;
1870 unsigned long remaining_pages_total = *num;
1871 unsigned long pages_to_write_in_pmd;
1875 pmd = walk_to_pmd(mm, addr);
1879 pages_to_write_in_pmd = min_t(unsigned long,
1880 remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
1882 /* Allocate the PTE if necessary; takes PMD lock once only. */
1884 if (pte_alloc(mm, pmd))
1887 while (pages_to_write_in_pmd) {
1889 const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
1891 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
1892 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
1893 int err = insert_page_in_batch_locked(vma, pte,
1894 addr, pages[curr_page_idx], prot);
1895 if (unlikely(err)) {
1896 pte_unmap_unlock(start_pte, pte_lock);
1898 remaining_pages_total -= pte_idx;
1904 pte_unmap_unlock(start_pte, pte_lock);
1905 pages_to_write_in_pmd -= batch_size;
1906 remaining_pages_total -= batch_size;
1908 if (remaining_pages_total)
1912 *num = remaining_pages_total;
1915 #endif /* ifdef pte_index */
1918 * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
1919 * @vma: user vma to map to
1920 * @addr: target start user address of these pages
1921 * @pages: source kernel pages
1922 * @num: in: number of pages to map. out: number of pages that were *not*
1923 * mapped. (0 means all pages were successfully mapped).
1925 * Preferred over vm_insert_page() when inserting multiple pages.
1927 * In case of error, we may have mapped a subset of the provided
1928 * pages. It is the caller's responsibility to account for this case.
1930 * The same restrictions apply as in vm_insert_page().
1932 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
1933 struct page **pages, unsigned long *num)
1936 const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
1938 if (addr < vma->vm_start || end_addr >= vma->vm_end)
1940 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1941 BUG_ON(mmap_read_trylock(vma->vm_mm));
1942 BUG_ON(vma->vm_flags & VM_PFNMAP);
1943 vma->vm_flags |= VM_MIXEDMAP;
1945 /* Defer page refcount checking till we're about to map that page. */
1946 return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
1948 unsigned long idx = 0, pgcount = *num;
1951 for (; idx < pgcount; ++idx) {
1952 err = vm_insert_page(vma, addr + (PAGE_SIZE * idx), pages[idx]);
1956 *num = pgcount - idx;
1958 #endif /* ifdef pte_index */
1960 EXPORT_SYMBOL(vm_insert_pages);
1963 * vm_insert_page - insert single page into user vma
1964 * @vma: user vma to map to
1965 * @addr: target user address of this page
1966 * @page: source kernel page
1968 * This allows drivers to insert individual pages they've allocated
1971 * The page has to be a nice clean _individual_ kernel allocation.
1972 * If you allocate a compound page, you need to have marked it as
1973 * such (__GFP_COMP), or manually just split the page up yourself
1974 * (see split_page()).
1976 * NOTE! Traditionally this was done with "remap_pfn_range()" which
1977 * took an arbitrary page protection parameter. This doesn't allow
1978 * that. Your vma protection will have to be set up correctly, which
1979 * means that if you want a shared writable mapping, you'd better
1980 * ask for a shared writable mapping!
1982 * The page does not need to be reserved.
1984 * Usually this function is called from f_op->mmap() handler
1985 * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
1986 * Caller must set VM_MIXEDMAP on vma if it wants to call this
1987 * function from other places, for example from page-fault handler.
1989 * Return: %0 on success, negative error code otherwise.
1991 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1994 if (addr < vma->vm_start || addr >= vma->vm_end)
1996 if (!page_count(page))
1998 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1999 BUG_ON(mmap_read_trylock(vma->vm_mm));
2000 BUG_ON(vma->vm_flags & VM_PFNMAP);
2001 vma->vm_flags |= VM_MIXEDMAP;
2003 return insert_page(vma, addr, page, vma->vm_page_prot);
2005 EXPORT_SYMBOL(vm_insert_page);
2008 * __vm_map_pages - maps range of kernel pages into user vma
2009 * @vma: user vma to map to
2010 * @pages: pointer to array of source kernel pages
2011 * @num: number of pages in page array
2012 * @offset: user's requested vm_pgoff
2014 * This allows drivers to map range of kernel pages into a user vma.
2016 * Return: 0 on success and error code otherwise.
2018 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2019 unsigned long num, unsigned long offset)
2021 unsigned long count = vma_pages(vma);
2022 unsigned long uaddr = vma->vm_start;
2025 /* Fail if the user requested offset is beyond the end of the object */
2029 /* Fail if the user requested size exceeds available object size */
2030 if (count > num - offset)
2033 for (i = 0; i < count; i++) {
2034 ret = vm_insert_page(vma, uaddr, pages[offset + i]);
2044 * vm_map_pages - maps range of kernel pages starts with non zero offset
2045 * @vma: user vma to map to
2046 * @pages: pointer to array of source kernel pages
2047 * @num: number of pages in page array
2049 * Maps an object consisting of @num pages, catering for the user's
2050 * requested vm_pgoff
2052 * If we fail to insert any page into the vma, the function will return
2053 * immediately leaving any previously inserted pages present. Callers
2054 * from the mmap handler may immediately return the error as their caller
2055 * will destroy the vma, removing any successfully inserted pages. Other
2056 * callers should make their own arrangements for calling unmap_region().
2058 * Context: Process context. Called by mmap handlers.
2059 * Return: 0 on success and error code otherwise.
2061 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2064 return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
2066 EXPORT_SYMBOL(vm_map_pages);
2069 * vm_map_pages_zero - map range of kernel pages starts with zero offset
2070 * @vma: user vma to map to
2071 * @pages: pointer to array of source kernel pages
2072 * @num: number of pages in page array
2074 * Similar to vm_map_pages(), except that it explicitly sets the offset
2075 * to 0. This function is intended for the drivers that did not consider
2078 * Context: Process context. Called by mmap handlers.
2079 * Return: 0 on success and error code otherwise.
2081 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
2084 return __vm_map_pages(vma, pages, num, 0);
2086 EXPORT_SYMBOL(vm_map_pages_zero);
2088 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2089 pfn_t pfn, pgprot_t prot, bool mkwrite)
2091 struct mm_struct *mm = vma->vm_mm;
2095 pte = get_locked_pte(mm, addr, &ptl);
2097 return VM_FAULT_OOM;
2098 if (!pte_none(*pte)) {
2101 * For read faults on private mappings the PFN passed
2102 * in may not match the PFN we have mapped if the
2103 * mapped PFN is a writeable COW page. In the mkwrite
2104 * case we are creating a writable PTE for a shared
2105 * mapping and we expect the PFNs to match. If they
2106 * don't match, we are likely racing with block
2107 * allocation and mapping invalidation so just skip the
2110 if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
2111 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
2114 entry = pte_mkyoung(*pte);
2115 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2116 if (ptep_set_access_flags(vma, addr, pte, entry, 1))
2117 update_mmu_cache(vma, addr, pte);
2122 /* Ok, finally just insert the thing.. */
2123 if (pfn_t_devmap(pfn))
2124 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
2126 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
2129 entry = pte_mkyoung(entry);
2130 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2133 set_pte_at(mm, addr, pte, entry);
2134 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2137 pte_unmap_unlock(pte, ptl);
2138 return VM_FAULT_NOPAGE;
2142 * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
2143 * @vma: user vma to map to
2144 * @addr: target user address of this page
2145 * @pfn: source kernel pfn
2146 * @pgprot: pgprot flags for the inserted page
2148 * This is exactly like vmf_insert_pfn(), except that it allows drivers
2149 * to override pgprot on a per-page basis.
2151 * This only makes sense for IO mappings, and it makes no sense for
2152 * COW mappings. In general, using multiple vmas is preferable;
2153 * vmf_insert_pfn_prot should only be used if using multiple VMAs is
2156 * See vmf_insert_mixed_prot() for a discussion of the implication of using
2157 * a value of @pgprot different from that of @vma->vm_page_prot.
2159 * Context: Process context. May allocate using %GFP_KERNEL.
2160 * Return: vm_fault_t value.
2162 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
2163 unsigned long pfn, pgprot_t pgprot)
2166 * Technically, architectures with pte_special can avoid all these
2167 * restrictions (same for remap_pfn_range). However we would like
2168 * consistency in testing and feature parity among all, so we should
2169 * try to keep these invariants in place for everybody.
2171 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2172 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2173 (VM_PFNMAP|VM_MIXEDMAP));
2174 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2175 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2177 if (addr < vma->vm_start || addr >= vma->vm_end)
2178 return VM_FAULT_SIGBUS;
2180 if (!pfn_modify_allowed(pfn, pgprot))
2181 return VM_FAULT_SIGBUS;
2183 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
2185 return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
2188 EXPORT_SYMBOL(vmf_insert_pfn_prot);
2191 * vmf_insert_pfn - insert single pfn into user vma
2192 * @vma: user vma to map to
2193 * @addr: target user address of this page
2194 * @pfn: source kernel pfn
2196 * Similar to vm_insert_page, this allows drivers to insert individual pages
2197 * they've allocated into a user vma. Same comments apply.
2199 * This function should only be called from a vm_ops->fault handler, and
2200 * in that case the handler should return the result of this function.
2202 * vma cannot be a COW mapping.
2204 * As this is called only for pages that do not currently exist, we
2205 * do not need to flush old virtual caches or the TLB.
2207 * Context: Process context. May allocate using %GFP_KERNEL.
2208 * Return: vm_fault_t value.
2210 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2213 return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
2215 EXPORT_SYMBOL(vmf_insert_pfn);
2217 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn)
2219 /* these checks mirror the abort conditions in vm_normal_page */
2220 if (vma->vm_flags & VM_MIXEDMAP)
2222 if (pfn_t_devmap(pfn))
2224 if (pfn_t_special(pfn))
2226 if (is_zero_pfn(pfn_t_to_pfn(pfn)))
2231 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
2232 unsigned long addr, pfn_t pfn, pgprot_t pgprot,
2237 BUG_ON(!vm_mixed_ok(vma, pfn));
2239 if (addr < vma->vm_start || addr >= vma->vm_end)
2240 return VM_FAULT_SIGBUS;
2242 track_pfn_insert(vma, &pgprot, pfn);
2244 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
2245 return VM_FAULT_SIGBUS;
2248 * If we don't have pte special, then we have to use the pfn_valid()
2249 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2250 * refcount the page if pfn_valid is true (hence insert_page rather
2251 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
2252 * without pte special, it would there be refcounted as a normal page.
2254 if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
2255 !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
2259 * At this point we are committed to insert_page()
2260 * regardless of whether the caller specified flags that
2261 * result in pfn_t_has_page() == false.
2263 page = pfn_to_page(pfn_t_to_pfn(pfn));
2264 err = insert_page(vma, addr, page, pgprot);
2266 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2270 return VM_FAULT_OOM;
2271 if (err < 0 && err != -EBUSY)
2272 return VM_FAULT_SIGBUS;
2274 return VM_FAULT_NOPAGE;
2278 * vmf_insert_mixed_prot - insert single pfn into user vma with specified pgprot
2279 * @vma: user vma to map to
2280 * @addr: target user address of this page
2281 * @pfn: source kernel pfn
2282 * @pgprot: pgprot flags for the inserted page
2284 * This is exactly like vmf_insert_mixed(), except that it allows drivers
2285 * to override pgprot on a per-page basis.
2287 * Typically this function should be used by drivers to set caching- and
2288 * encryption bits different than those of @vma->vm_page_prot, because
2289 * the caching- or encryption mode may not be known at mmap() time.
2290 * This is ok as long as @vma->vm_page_prot is not used by the core vm
2291 * to set caching and encryption bits for those vmas (except for COW pages).
2292 * This is ensured by core vm only modifying these page table entries using
2293 * functions that don't touch caching- or encryption bits, using pte_modify()
2294 * if needed. (See for example mprotect()).
2295 * Also when new page-table entries are created, this is only done using the
2296 * fault() callback, and never using the value of vma->vm_page_prot,
2297 * except for page-table entries that point to anonymous pages as the result
2300 * Context: Process context. May allocate using %GFP_KERNEL.
2301 * Return: vm_fault_t value.
2303 vm_fault_t vmf_insert_mixed_prot(struct vm_area_struct *vma, unsigned long addr,
2304 pfn_t pfn, pgprot_t pgprot)
2306 return __vm_insert_mixed(vma, addr, pfn, pgprot, false);
2308 EXPORT_SYMBOL(vmf_insert_mixed_prot);
2310 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2313 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, false);
2315 EXPORT_SYMBOL(vmf_insert_mixed);
2318 * If the insertion of PTE failed because someone else already added a
2319 * different entry in the mean time, we treat that as success as we assume
2320 * the same entry was actually inserted.
2322 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2323 unsigned long addr, pfn_t pfn)
2325 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, true);
2327 EXPORT_SYMBOL(vmf_insert_mixed_mkwrite);
2330 * maps a range of physical memory into the requested pages. the old
2331 * mappings are removed. any references to nonexistent pages results
2332 * in null mappings (currently treated as "copy-on-access")
2334 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2335 unsigned long addr, unsigned long end,
2336 unsigned long pfn, pgprot_t prot)
2338 pte_t *pte, *mapped_pte;
2342 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2345 arch_enter_lazy_mmu_mode();
2347 BUG_ON(!pte_none(*pte));
2348 if (!pfn_modify_allowed(pfn, prot)) {
2352 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2354 } while (pte++, addr += PAGE_SIZE, addr != end);
2355 arch_leave_lazy_mmu_mode();
2356 pte_unmap_unlock(mapped_pte, ptl);
2360 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2361 unsigned long addr, unsigned long end,
2362 unsigned long pfn, pgprot_t prot)
2368 pfn -= addr >> PAGE_SHIFT;
2369 pmd = pmd_alloc(mm, pud, addr);
2372 VM_BUG_ON(pmd_trans_huge(*pmd));
2374 next = pmd_addr_end(addr, end);
2375 err = remap_pte_range(mm, pmd, addr, next,
2376 pfn + (addr >> PAGE_SHIFT), prot);
2379 } while (pmd++, addr = next, addr != end);
2383 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2384 unsigned long addr, unsigned long end,
2385 unsigned long pfn, pgprot_t prot)
2391 pfn -= addr >> PAGE_SHIFT;
2392 pud = pud_alloc(mm, p4d, addr);
2396 next = pud_addr_end(addr, end);
2397 err = remap_pmd_range(mm, pud, addr, next,
2398 pfn + (addr >> PAGE_SHIFT), prot);
2401 } while (pud++, addr = next, addr != end);
2405 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2406 unsigned long addr, unsigned long end,
2407 unsigned long pfn, pgprot_t prot)
2413 pfn -= addr >> PAGE_SHIFT;
2414 p4d = p4d_alloc(mm, pgd, addr);
2418 next = p4d_addr_end(addr, end);
2419 err = remap_pud_range(mm, p4d, addr, next,
2420 pfn + (addr >> PAGE_SHIFT), prot);
2423 } while (p4d++, addr = next, addr != end);
2428 * Variant of remap_pfn_range that does not call track_pfn_remap. The caller
2429 * must have pre-validated the caching bits of the pgprot_t.
2431 int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr,
2432 unsigned long pfn, unsigned long size, pgprot_t prot)
2436 unsigned long end = addr + PAGE_ALIGN(size);
2437 struct mm_struct *mm = vma->vm_mm;
2440 if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
2444 * Physically remapped pages are special. Tell the
2445 * rest of the world about it:
2446 * VM_IO tells people not to look at these pages
2447 * (accesses can have side effects).
2448 * VM_PFNMAP tells the core MM that the base pages are just
2449 * raw PFN mappings, and do not have a "struct page" associated
2452 * Disable vma merging and expanding with mremap().
2454 * Omit vma from core dump, even when VM_IO turned off.
2456 * There's a horrible special case to handle copy-on-write
2457 * behaviour that some programs depend on. We mark the "original"
2458 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2459 * See vm_normal_page() for details.
2461 if (is_cow_mapping(vma->vm_flags)) {
2462 if (addr != vma->vm_start || end != vma->vm_end)
2464 vma->vm_pgoff = pfn;
2467 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2469 BUG_ON(addr >= end);
2470 pfn -= addr >> PAGE_SHIFT;
2471 pgd = pgd_offset(mm, addr);
2472 flush_cache_range(vma, addr, end);
2474 next = pgd_addr_end(addr, end);
2475 err = remap_p4d_range(mm, pgd, addr, next,
2476 pfn + (addr >> PAGE_SHIFT), prot);
2479 } while (pgd++, addr = next, addr != end);
2485 * remap_pfn_range - remap kernel memory to userspace
2486 * @vma: user vma to map to
2487 * @addr: target page aligned user address to start at
2488 * @pfn: page frame number of kernel physical memory address
2489 * @size: size of mapping area
2490 * @prot: page protection flags for this mapping
2492 * Note: this is only safe if the mm semaphore is held when called.
2494 * Return: %0 on success, negative error code otherwise.
2496 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2497 unsigned long pfn, unsigned long size, pgprot_t prot)
2501 err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2505 err = remap_pfn_range_notrack(vma, addr, pfn, size, prot);
2507 untrack_pfn(vma, pfn, PAGE_ALIGN(size));
2510 EXPORT_SYMBOL(remap_pfn_range);
2513 * vm_iomap_memory - remap memory to userspace
2514 * @vma: user vma to map to
2515 * @start: start of the physical memory to be mapped
2516 * @len: size of area
2518 * This is a simplified io_remap_pfn_range() for common driver use. The
2519 * driver just needs to give us the physical memory range to be mapped,
2520 * we'll figure out the rest from the vma information.
2522 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2523 * whatever write-combining details or similar.
2525 * Return: %0 on success, negative error code otherwise.
2527 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2529 unsigned long vm_len, pfn, pages;
2531 /* Check that the physical memory area passed in looks valid */
2532 if (start + len < start)
2535 * You *really* shouldn't map things that aren't page-aligned,
2536 * but we've historically allowed it because IO memory might
2537 * just have smaller alignment.
2539 len += start & ~PAGE_MASK;
2540 pfn = start >> PAGE_SHIFT;
2541 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2542 if (pfn + pages < pfn)
2545 /* We start the mapping 'vm_pgoff' pages into the area */
2546 if (vma->vm_pgoff > pages)
2548 pfn += vma->vm_pgoff;
2549 pages -= vma->vm_pgoff;
2551 /* Can we fit all of the mapping? */
2552 vm_len = vma->vm_end - vma->vm_start;
2553 if (vm_len >> PAGE_SHIFT > pages)
2556 /* Ok, let it rip */
2557 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2559 EXPORT_SYMBOL(vm_iomap_memory);
2561 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2562 unsigned long addr, unsigned long end,
2563 pte_fn_t fn, void *data, bool create,
2564 pgtbl_mod_mask *mask)
2566 pte_t *pte, *mapped_pte;
2571 mapped_pte = pte = (mm == &init_mm) ?
2572 pte_alloc_kernel_track(pmd, addr, mask) :
2573 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2577 mapped_pte = pte = (mm == &init_mm) ?
2578 pte_offset_kernel(pmd, addr) :
2579 pte_offset_map_lock(mm, pmd, addr, &ptl);
2582 BUG_ON(pmd_huge(*pmd));
2584 arch_enter_lazy_mmu_mode();
2588 if (create || !pte_none(*pte)) {
2589 err = fn(pte++, addr, data);
2593 } while (addr += PAGE_SIZE, addr != end);
2595 *mask |= PGTBL_PTE_MODIFIED;
2597 arch_leave_lazy_mmu_mode();
2600 pte_unmap_unlock(mapped_pte, ptl);
2604 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2605 unsigned long addr, unsigned long end,
2606 pte_fn_t fn, void *data, bool create,
2607 pgtbl_mod_mask *mask)
2613 BUG_ON(pud_huge(*pud));
2616 pmd = pmd_alloc_track(mm, pud, addr, mask);
2620 pmd = pmd_offset(pud, addr);
2623 next = pmd_addr_end(addr, end);
2624 if (pmd_none(*pmd) && !create)
2626 if (WARN_ON_ONCE(pmd_leaf(*pmd)))
2628 if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) {
2633 err = apply_to_pte_range(mm, pmd, addr, next,
2634 fn, data, create, mask);
2637 } while (pmd++, addr = next, addr != end);
2642 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2643 unsigned long addr, unsigned long end,
2644 pte_fn_t fn, void *data, bool create,
2645 pgtbl_mod_mask *mask)
2652 pud = pud_alloc_track(mm, p4d, addr, mask);
2656 pud = pud_offset(p4d, addr);
2659 next = pud_addr_end(addr, end);
2660 if (pud_none(*pud) && !create)
2662 if (WARN_ON_ONCE(pud_leaf(*pud)))
2664 if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) {
2669 err = apply_to_pmd_range(mm, pud, addr, next,
2670 fn, data, create, mask);
2673 } while (pud++, addr = next, addr != end);
2678 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2679 unsigned long addr, unsigned long end,
2680 pte_fn_t fn, void *data, bool create,
2681 pgtbl_mod_mask *mask)
2688 p4d = p4d_alloc_track(mm, pgd, addr, mask);
2692 p4d = p4d_offset(pgd, addr);
2695 next = p4d_addr_end(addr, end);
2696 if (p4d_none(*p4d) && !create)
2698 if (WARN_ON_ONCE(p4d_leaf(*p4d)))
2700 if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) {
2705 err = apply_to_pud_range(mm, p4d, addr, next,
2706 fn, data, create, mask);
2709 } while (p4d++, addr = next, addr != end);
2714 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2715 unsigned long size, pte_fn_t fn,
2716 void *data, bool create)
2719 unsigned long start = addr, next;
2720 unsigned long end = addr + size;
2721 pgtbl_mod_mask mask = 0;
2724 if (WARN_ON(addr >= end))
2727 pgd = pgd_offset(mm, addr);
2729 next = pgd_addr_end(addr, end);
2730 if (pgd_none(*pgd) && !create)
2732 if (WARN_ON_ONCE(pgd_leaf(*pgd)))
2734 if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) {
2739 err = apply_to_p4d_range(mm, pgd, addr, next,
2740 fn, data, create, &mask);
2743 } while (pgd++, addr = next, addr != end);
2745 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
2746 arch_sync_kernel_mappings(start, start + size);
2752 * Scan a region of virtual memory, filling in page tables as necessary
2753 * and calling a provided function on each leaf page table.
2755 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2756 unsigned long size, pte_fn_t fn, void *data)
2758 return __apply_to_page_range(mm, addr, size, fn, data, true);
2760 EXPORT_SYMBOL_GPL(apply_to_page_range);
2763 * Scan a region of virtual memory, calling a provided function on
2764 * each leaf page table where it exists.
2766 * Unlike apply_to_page_range, this does _not_ fill in page tables
2767 * where they are absent.
2769 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
2770 unsigned long size, pte_fn_t fn, void *data)
2772 return __apply_to_page_range(mm, addr, size, fn, data, false);
2774 EXPORT_SYMBOL_GPL(apply_to_existing_page_range);
2777 * handle_pte_fault chooses page fault handler according to an entry which was
2778 * read non-atomically. Before making any commitment, on those architectures
2779 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2780 * parts, do_swap_page must check under lock before unmapping the pte and
2781 * proceeding (but do_wp_page is only called after already making such a check;
2782 * and do_anonymous_page can safely check later on).
2784 static inline int pte_unmap_same(struct vm_fault *vmf)
2787 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
2788 if (sizeof(pte_t) > sizeof(unsigned long)) {
2789 spinlock_t *ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
2791 same = pte_same(*vmf->pte, vmf->orig_pte);
2795 pte_unmap(vmf->pte);
2800 static inline bool __wp_page_copy_user(struct page *dst, struct page *src,
2801 struct vm_fault *vmf)
2806 bool locked = false;
2807 struct vm_area_struct *vma = vmf->vma;
2808 struct mm_struct *mm = vma->vm_mm;
2809 unsigned long addr = vmf->address;
2812 copy_user_highpage(dst, src, addr, vma);
2817 * If the source page was a PFN mapping, we don't have
2818 * a "struct page" for it. We do a best-effort copy by
2819 * just copying from the original user address. If that
2820 * fails, we just zero-fill it. Live with it.
2822 kaddr = kmap_atomic(dst);
2823 uaddr = (void __user *)(addr & PAGE_MASK);
2826 * On architectures with software "accessed" bits, we would
2827 * take a double page fault, so mark it accessed here.
2829 if (arch_faults_on_old_pte() && !pte_young(vmf->orig_pte)) {
2832 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2834 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2836 * Other thread has already handled the fault
2837 * and update local tlb only
2839 update_mmu_tlb(vma, addr, vmf->pte);
2844 entry = pte_mkyoung(vmf->orig_pte);
2845 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2846 update_mmu_cache(vma, addr, vmf->pte);
2850 * This really shouldn't fail, because the page is there
2851 * in the page tables. But it might just be unreadable,
2852 * in which case we just give up and fill the result with
2855 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2859 /* Re-validate under PTL if the page is still mapped */
2860 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2862 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2863 /* The PTE changed under us, update local tlb */
2864 update_mmu_tlb(vma, addr, vmf->pte);
2870 * The same page can be mapped back since last copy attempt.
2871 * Try to copy again under PTL.
2873 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2875 * Give a warn in case there can be some obscure
2888 pte_unmap_unlock(vmf->pte, vmf->ptl);
2889 kunmap_atomic(kaddr);
2890 flush_dcache_page(dst);
2895 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2897 struct file *vm_file = vma->vm_file;
2900 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2903 * Special mappings (e.g. VDSO) do not have any file so fake
2904 * a default GFP_KERNEL for them.
2910 * Notify the address space that the page is about to become writable so that
2911 * it can prohibit this or wait for the page to get into an appropriate state.
2913 * We do this without the lock held, so that it can sleep if it needs to.
2915 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf)
2918 struct page *page = vmf->page;
2919 unsigned int old_flags = vmf->flags;
2921 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2923 if (vmf->vma->vm_file &&
2924 IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
2925 return VM_FAULT_SIGBUS;
2927 ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2928 /* Restore original flags so that caller is not surprised */
2929 vmf->flags = old_flags;
2930 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2932 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2934 if (!page->mapping) {
2936 return 0; /* retry */
2938 ret |= VM_FAULT_LOCKED;
2940 VM_BUG_ON_PAGE(!PageLocked(page), page);
2945 * Handle dirtying of a page in shared file mapping on a write fault.
2947 * The function expects the page to be locked and unlocks it.
2949 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
2951 struct vm_area_struct *vma = vmf->vma;
2952 struct address_space *mapping;
2953 struct page *page = vmf->page;
2955 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2957 dirtied = set_page_dirty(page);
2958 VM_BUG_ON_PAGE(PageAnon(page), page);
2960 * Take a local copy of the address_space - page.mapping may be zeroed
2961 * by truncate after unlock_page(). The address_space itself remains
2962 * pinned by vma->vm_file's reference. We rely on unlock_page()'s
2963 * release semantics to prevent the compiler from undoing this copying.
2965 mapping = page_rmapping(page);
2969 file_update_time(vma->vm_file);
2972 * Throttle page dirtying rate down to writeback speed.
2974 * mapping may be NULL here because some device drivers do not
2975 * set page.mapping but still dirty their pages
2977 * Drop the mmap_lock before waiting on IO, if we can. The file
2978 * is pinning the mapping, as per above.
2980 if ((dirtied || page_mkwrite) && mapping) {
2983 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
2984 balance_dirty_pages_ratelimited(mapping);
2987 return VM_FAULT_RETRY;
2995 * Handle write page faults for pages that can be reused in the current vma
2997 * This can happen either due to the mapping being with the VM_SHARED flag,
2998 * or due to us being the last reference standing to the page. In either
2999 * case, all we need to do here is to mark the page as writable and update
3000 * any related book-keeping.
3002 static inline void wp_page_reuse(struct vm_fault *vmf)
3003 __releases(vmf->ptl)
3005 struct vm_area_struct *vma = vmf->vma;
3006 struct page *page = vmf->page;
3009 VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE));
3010 VM_BUG_ON(PageAnon(page) && !PageAnonExclusive(page));
3013 * Clear the pages cpupid information as the existing
3014 * information potentially belongs to a now completely
3015 * unrelated process.
3018 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
3020 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3021 entry = pte_mkyoung(vmf->orig_pte);
3022 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3023 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
3024 update_mmu_cache(vma, vmf->address, vmf->pte);
3025 pte_unmap_unlock(vmf->pte, vmf->ptl);
3026 count_vm_event(PGREUSE);
3030 * Handle the case of a page which we actually need to copy to a new page,
3031 * either due to COW or unsharing.
3033 * Called with mmap_lock locked and the old page referenced, but
3034 * without the ptl held.
3036 * High level logic flow:
3038 * - Allocate a page, copy the content of the old page to the new one.
3039 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
3040 * - Take the PTL. If the pte changed, bail out and release the allocated page
3041 * - If the pte is still the way we remember it, update the page table and all
3042 * relevant references. This includes dropping the reference the page-table
3043 * held to the old page, as well as updating the rmap.
3044 * - In any case, unlock the PTL and drop the reference we took to the old page.
3046 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
3048 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3049 struct vm_area_struct *vma = vmf->vma;
3050 struct mm_struct *mm = vma->vm_mm;
3051 struct page *old_page = vmf->page;
3052 struct page *new_page = NULL;
3054 int page_copied = 0;
3055 struct mmu_notifier_range range;
3057 if (unlikely(anon_vma_prepare(vma)))
3060 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
3061 new_page = alloc_zeroed_user_highpage_movable(vma,
3066 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3071 if (!__wp_page_copy_user(new_page, old_page, vmf)) {
3073 * COW failed, if the fault was solved by other,
3074 * it's fine. If not, userspace would re-fault on
3075 * the same address and we will handle the fault
3076 * from the second attempt.
3085 if (mem_cgroup_charge(page_folio(new_page), mm, GFP_KERNEL))
3087 cgroup_throttle_swaprate(new_page, GFP_KERNEL);
3089 __SetPageUptodate(new_page);
3091 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
3092 vmf->address & PAGE_MASK,
3093 (vmf->address & PAGE_MASK) + PAGE_SIZE);
3094 mmu_notifier_invalidate_range_start(&range);
3097 * Re-check the pte - we dropped the lock
3099 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
3100 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
3102 if (!PageAnon(old_page)) {
3103 dec_mm_counter_fast(mm,
3104 mm_counter_file(old_page));
3105 inc_mm_counter_fast(mm, MM_ANONPAGES);
3108 inc_mm_counter_fast(mm, MM_ANONPAGES);
3110 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3111 entry = mk_pte(new_page, vma->vm_page_prot);
3112 entry = pte_sw_mkyoung(entry);
3113 if (unlikely(unshare)) {
3114 if (pte_soft_dirty(vmf->orig_pte))
3115 entry = pte_mksoft_dirty(entry);
3116 if (pte_uffd_wp(vmf->orig_pte))
3117 entry = pte_mkuffd_wp(entry);
3119 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3123 * Clear the pte entry and flush it first, before updating the
3124 * pte with the new entry, to keep TLBs on different CPUs in
3125 * sync. This code used to set the new PTE then flush TLBs, but
3126 * that left a window where the new PTE could be loaded into
3127 * some TLBs while the old PTE remains in others.
3129 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
3130 page_add_new_anon_rmap(new_page, vma, vmf->address);
3131 lru_cache_add_inactive_or_unevictable(new_page, vma);
3133 * We call the notify macro here because, when using secondary
3134 * mmu page tables (such as kvm shadow page tables), we want the
3135 * new page to be mapped directly into the secondary page table.
3137 BUG_ON(unshare && pte_write(entry));
3138 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
3139 update_mmu_cache(vma, vmf->address, vmf->pte);
3142 * Only after switching the pte to the new page may
3143 * we remove the mapcount here. Otherwise another
3144 * process may come and find the rmap count decremented
3145 * before the pte is switched to the new page, and
3146 * "reuse" the old page writing into it while our pte
3147 * here still points into it and can be read by other
3150 * The critical issue is to order this
3151 * page_remove_rmap with the ptp_clear_flush above.
3152 * Those stores are ordered by (if nothing else,)
3153 * the barrier present in the atomic_add_negative
3154 * in page_remove_rmap.
3156 * Then the TLB flush in ptep_clear_flush ensures that
3157 * no process can access the old page before the
3158 * decremented mapcount is visible. And the old page
3159 * cannot be reused until after the decremented
3160 * mapcount is visible. So transitively, TLBs to
3161 * old page will be flushed before it can be reused.
3163 page_remove_rmap(old_page, vma, false);
3166 /* Free the old page.. */
3167 new_page = old_page;
3170 update_mmu_tlb(vma, vmf->address, vmf->pte);
3176 pte_unmap_unlock(vmf->pte, vmf->ptl);
3178 * No need to double call mmu_notifier->invalidate_range() callback as
3179 * the above ptep_clear_flush_notify() did already call it.
3181 mmu_notifier_invalidate_range_only_end(&range);
3184 free_swap_cache(old_page);
3187 return (page_copied && !unshare) ? VM_FAULT_WRITE : 0;
3193 return VM_FAULT_OOM;
3197 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
3198 * writeable once the page is prepared
3200 * @vmf: structure describing the fault
3202 * This function handles all that is needed to finish a write page fault in a
3203 * shared mapping due to PTE being read-only once the mapped page is prepared.
3204 * It handles locking of PTE and modifying it.
3206 * The function expects the page to be locked or other protection against
3207 * concurrent faults / writeback (such as DAX radix tree locks).
3209 * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before
3210 * we acquired PTE lock.
3212 vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf)
3214 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
3215 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
3218 * We might have raced with another page fault while we released the
3219 * pte_offset_map_lock.
3221 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
3222 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
3223 pte_unmap_unlock(vmf->pte, vmf->ptl);
3224 return VM_FAULT_NOPAGE;
3231 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
3234 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
3236 struct vm_area_struct *vma = vmf->vma;
3238 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
3241 pte_unmap_unlock(vmf->pte, vmf->ptl);
3242 vmf->flags |= FAULT_FLAG_MKWRITE;
3243 ret = vma->vm_ops->pfn_mkwrite(vmf);
3244 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
3246 return finish_mkwrite_fault(vmf);
3249 return VM_FAULT_WRITE;
3252 static vm_fault_t wp_page_shared(struct vm_fault *vmf)
3253 __releases(vmf->ptl)
3255 struct vm_area_struct *vma = vmf->vma;
3256 vm_fault_t ret = VM_FAULT_WRITE;
3258 get_page(vmf->page);
3260 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
3263 pte_unmap_unlock(vmf->pte, vmf->ptl);
3264 tmp = do_page_mkwrite(vmf);
3265 if (unlikely(!tmp || (tmp &
3266 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3267 put_page(vmf->page);
3270 tmp = finish_mkwrite_fault(vmf);
3271 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3272 unlock_page(vmf->page);
3273 put_page(vmf->page);
3278 lock_page(vmf->page);
3280 ret |= fault_dirty_shared_page(vmf);
3281 put_page(vmf->page);
3287 * This routine handles present pages, when
3288 * * users try to write to a shared page (FAULT_FLAG_WRITE)
3289 * * GUP wants to take a R/O pin on a possibly shared anonymous page
3290 * (FAULT_FLAG_UNSHARE)
3292 * It is done by copying the page to a new address and decrementing the
3293 * shared-page counter for the old page.
3295 * Note that this routine assumes that the protection checks have been
3296 * done by the caller (the low-level page fault routine in most cases).
3297 * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've
3298 * done any necessary COW.
3300 * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even
3301 * though the page will change only once the write actually happens. This
3302 * avoids a few races, and potentially makes it more efficient.
3304 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3305 * but allow concurrent faults), with pte both mapped and locked.
3306 * We return with mmap_lock still held, but pte unmapped and unlocked.
3308 static vm_fault_t do_wp_page(struct vm_fault *vmf)
3309 __releases(vmf->ptl)
3311 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3312 struct vm_area_struct *vma = vmf->vma;
3314 VM_BUG_ON(unshare && (vmf->flags & FAULT_FLAG_WRITE));
3315 VM_BUG_ON(!unshare && !(vmf->flags & FAULT_FLAG_WRITE));
3317 if (likely(!unshare)) {
3318 if (userfaultfd_pte_wp(vma, *vmf->pte)) {
3319 pte_unmap_unlock(vmf->pte, vmf->ptl);
3320 return handle_userfault(vmf, VM_UFFD_WP);
3324 * Userfaultfd write-protect can defer flushes. Ensure the TLB
3325 * is flushed in this case before copying.
3327 if (unlikely(userfaultfd_wp(vmf->vma) &&
3328 mm_tlb_flush_pending(vmf->vma->vm_mm)))
3329 flush_tlb_page(vmf->vma, vmf->address);
3332 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
3334 if (unlikely(unshare)) {
3335 /* No anonymous page -> nothing to do. */
3336 pte_unmap_unlock(vmf->pte, vmf->ptl);
3341 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
3344 * We should not cow pages in a shared writeable mapping.
3345 * Just mark the pages writable and/or call ops->pfn_mkwrite.
3347 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3348 (VM_WRITE|VM_SHARED))
3349 return wp_pfn_shared(vmf);
3351 pte_unmap_unlock(vmf->pte, vmf->ptl);
3352 return wp_page_copy(vmf);
3356 * Take out anonymous pages first, anonymous shared vmas are
3357 * not dirty accountable.
3359 if (PageAnon(vmf->page)) {
3360 struct page *page = vmf->page;
3363 * If the page is exclusive to this process we must reuse the
3364 * page without further checks.
3366 if (PageAnonExclusive(page))
3370 * We have to verify under page lock: these early checks are
3371 * just an optimization to avoid locking the page and freeing
3372 * the swapcache if there is little hope that we can reuse.
3374 * PageKsm() doesn't necessarily raise the page refcount.
3376 if (PageKsm(page) || page_count(page) > 3)
3380 * Note: We cannot easily detect+handle references from
3381 * remote LRU pagevecs or references to PageLRU() pages.
3384 if (page_count(page) > 1 + PageSwapCache(page))
3386 if (!trylock_page(page))
3388 if (PageSwapCache(page))
3389 try_to_free_swap(page);
3390 if (PageKsm(page) || page_count(page) != 1) {
3395 * Ok, we've got the only page reference from our mapping
3396 * and the page is locked, it's dark out, and we're wearing
3397 * sunglasses. Hit it.
3399 page_move_anon_rmap(page, vma);
3402 if (unlikely(unshare)) {
3403 pte_unmap_unlock(vmf->pte, vmf->ptl);
3407 return VM_FAULT_WRITE;
3408 } else if (unshare) {
3409 /* No anonymous page -> nothing to do. */
3410 pte_unmap_unlock(vmf->pte, vmf->ptl);
3412 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3413 (VM_WRITE|VM_SHARED))) {
3414 return wp_page_shared(vmf);
3418 * Ok, we need to copy. Oh, well..
3420 get_page(vmf->page);
3422 pte_unmap_unlock(vmf->pte, vmf->ptl);
3424 if (PageKsm(vmf->page))
3425 count_vm_event(COW_KSM);
3427 return wp_page_copy(vmf);
3430 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
3431 unsigned long start_addr, unsigned long end_addr,
3432 struct zap_details *details)
3434 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
3437 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
3438 pgoff_t first_index,
3440 struct zap_details *details)
3442 struct vm_area_struct *vma;
3443 pgoff_t vba, vea, zba, zea;
3445 vma_interval_tree_foreach(vma, root, first_index, last_index) {
3446 vba = vma->vm_pgoff;
3447 vea = vba + vma_pages(vma) - 1;
3448 zba = max(first_index, vba);
3449 zea = min(last_index, vea);
3451 unmap_mapping_range_vma(vma,
3452 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
3453 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3459 * unmap_mapping_folio() - Unmap single folio from processes.
3460 * @folio: The locked folio to be unmapped.
3462 * Unmap this folio from any userspace process which still has it mmaped.
3463 * Typically, for efficiency, the range of nearby pages has already been
3464 * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once
3465 * truncation or invalidation holds the lock on a folio, it may find that
3466 * the page has been remapped again: and then uses unmap_mapping_folio()
3467 * to unmap it finally.
3469 void unmap_mapping_folio(struct folio *folio)
3471 struct address_space *mapping = folio->mapping;
3472 struct zap_details details = { };
3473 pgoff_t first_index;
3476 VM_BUG_ON(!folio_test_locked(folio));
3478 first_index = folio->index;
3479 last_index = folio->index + folio_nr_pages(folio) - 1;
3481 details.even_cows = false;
3482 details.single_folio = folio;
3483 details.zap_flags = ZAP_FLAG_DROP_MARKER;
3485 i_mmap_lock_read(mapping);
3486 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3487 unmap_mapping_range_tree(&mapping->i_mmap, first_index,
3488 last_index, &details);
3489 i_mmap_unlock_read(mapping);
3493 * unmap_mapping_pages() - Unmap pages from processes.
3494 * @mapping: The address space containing pages to be unmapped.
3495 * @start: Index of first page to be unmapped.
3496 * @nr: Number of pages to be unmapped. 0 to unmap to end of file.
3497 * @even_cows: Whether to unmap even private COWed pages.
3499 * Unmap the pages in this address space from any userspace process which
3500 * has them mmaped. Generally, you want to remove COWed pages as well when
3501 * a file is being truncated, but not when invalidating pages from the page
3504 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
3505 pgoff_t nr, bool even_cows)
3507 struct zap_details details = { };
3508 pgoff_t first_index = start;
3509 pgoff_t last_index = start + nr - 1;
3511 details.even_cows = even_cows;
3512 if (last_index < first_index)
3513 last_index = ULONG_MAX;
3515 i_mmap_lock_read(mapping);
3516 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3517 unmap_mapping_range_tree(&mapping->i_mmap, first_index,
3518 last_index, &details);
3519 i_mmap_unlock_read(mapping);
3521 EXPORT_SYMBOL_GPL(unmap_mapping_pages);
3524 * unmap_mapping_range - unmap the portion of all mmaps in the specified
3525 * address_space corresponding to the specified byte range in the underlying
3528 * @mapping: the address space containing mmaps to be unmapped.
3529 * @holebegin: byte in first page to unmap, relative to the start of
3530 * the underlying file. This will be rounded down to a PAGE_SIZE
3531 * boundary. Note that this is different from truncate_pagecache(), which
3532 * must keep the partial page. In contrast, we must get rid of
3534 * @holelen: size of prospective hole in bytes. This will be rounded
3535 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
3537 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3538 * but 0 when invalidating pagecache, don't throw away private data.
3540 void unmap_mapping_range(struct address_space *mapping,
3541 loff_t const holebegin, loff_t const holelen, int even_cows)
3543 pgoff_t hba = holebegin >> PAGE_SHIFT;
3544 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3546 /* Check for overflow. */
3547 if (sizeof(holelen) > sizeof(hlen)) {
3549 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3550 if (holeend & ~(long long)ULONG_MAX)
3551 hlen = ULONG_MAX - hba + 1;
3554 unmap_mapping_pages(mapping, hba, hlen, even_cows);
3556 EXPORT_SYMBOL(unmap_mapping_range);
3559 * Restore a potential device exclusive pte to a working pte entry
3561 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf)
3563 struct page *page = vmf->page;
3564 struct vm_area_struct *vma = vmf->vma;
3565 struct mmu_notifier_range range;
3567 if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags))
3568 return VM_FAULT_RETRY;
3569 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma,
3570 vma->vm_mm, vmf->address & PAGE_MASK,
3571 (vmf->address & PAGE_MASK) + PAGE_SIZE, NULL);
3572 mmu_notifier_invalidate_range_start(&range);
3574 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3576 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3577 restore_exclusive_pte(vma, page, vmf->address, vmf->pte);
3579 pte_unmap_unlock(vmf->pte, vmf->ptl);
3582 mmu_notifier_invalidate_range_end(&range);
3586 static inline bool should_try_to_free_swap(struct page *page,
3587 struct vm_area_struct *vma,
3588 unsigned int fault_flags)
3590 if (!PageSwapCache(page))
3592 if (mem_cgroup_swap_full(page) || (vma->vm_flags & VM_LOCKED) ||
3596 * If we want to map a page that's in the swapcache writable, we
3597 * have to detect via the refcount if we're really the exclusive
3598 * user. Try freeing the swapcache to get rid of the swapcache
3599 * reference only in case it's likely that we'll be the exlusive user.
3601 return (fault_flags & FAULT_FLAG_WRITE) && !PageKsm(page) &&
3602 page_count(page) == 2;
3605 static vm_fault_t pte_marker_clear(struct vm_fault *vmf)
3607 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
3608 vmf->address, &vmf->ptl);
3610 * Be careful so that we will only recover a special uffd-wp pte into a
3611 * none pte. Otherwise it means the pte could have changed, so retry.
3613 if (is_pte_marker(*vmf->pte))
3614 pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte);
3615 pte_unmap_unlock(vmf->pte, vmf->ptl);
3620 * This is actually a page-missing access, but with uffd-wp special pte
3621 * installed. It means this pte was wr-protected before being unmapped.
3623 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf)
3626 * Just in case there're leftover special ptes even after the region
3627 * got unregistered - we can simply clear them. We can also do that
3628 * proactively when e.g. when we do UFFDIO_UNREGISTER upon some uffd-wp
3629 * ranges, but it should be more efficient to be done lazily here.
3631 if (unlikely(!userfaultfd_wp(vmf->vma) || vma_is_anonymous(vmf->vma)))
3632 return pte_marker_clear(vmf);
3634 /* do_fault() can handle pte markers too like none pte */
3635 return do_fault(vmf);
3638 static vm_fault_t handle_pte_marker(struct vm_fault *vmf)
3640 swp_entry_t entry = pte_to_swp_entry(vmf->orig_pte);
3641 unsigned long marker = pte_marker_get(entry);
3644 * PTE markers should always be with file-backed memories, and the
3645 * marker should never be empty. If anything weird happened, the best
3646 * thing to do is to kill the process along with its mm.
3648 if (WARN_ON_ONCE(vma_is_anonymous(vmf->vma) || !marker))
3649 return VM_FAULT_SIGBUS;
3651 if (pte_marker_entry_uffd_wp(entry))
3652 return pte_marker_handle_uffd_wp(vmf);
3654 /* This is an unknown pte marker */
3655 return VM_FAULT_SIGBUS;
3659 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3660 * but allow concurrent faults), and pte mapped but not yet locked.
3661 * We return with pte unmapped and unlocked.
3663 * We return with the mmap_lock locked or unlocked in the same cases
3664 * as does filemap_fault().
3666 vm_fault_t do_swap_page(struct vm_fault *vmf)
3668 struct vm_area_struct *vma = vmf->vma;
3669 struct page *page = NULL, *swapcache;
3670 struct swap_info_struct *si = NULL;
3671 rmap_t rmap_flags = RMAP_NONE;
3672 bool exclusive = false;
3677 void *shadow = NULL;
3679 if (!pte_unmap_same(vmf))
3682 entry = pte_to_swp_entry(vmf->orig_pte);
3683 if (unlikely(non_swap_entry(entry))) {
3684 if (is_migration_entry(entry)) {
3685 migration_entry_wait(vma->vm_mm, vmf->pmd,
3687 } else if (is_device_exclusive_entry(entry)) {
3688 vmf->page = pfn_swap_entry_to_page(entry);
3689 ret = remove_device_exclusive_entry(vmf);
3690 } else if (is_device_private_entry(entry)) {
3691 vmf->page = pfn_swap_entry_to_page(entry);
3692 ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
3693 } else if (is_hwpoison_entry(entry)) {
3694 ret = VM_FAULT_HWPOISON;
3695 } else if (is_pte_marker_entry(entry)) {
3696 ret = handle_pte_marker(vmf);
3698 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3699 ret = VM_FAULT_SIGBUS;
3704 /* Prevent swapoff from happening to us. */
3705 si = get_swap_device(entry);
3709 page = lookup_swap_cache(entry, vma, vmf->address);
3713 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
3714 __swap_count(entry) == 1) {
3715 /* skip swapcache */
3716 page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3719 __SetPageLocked(page);
3720 __SetPageSwapBacked(page);
3722 if (mem_cgroup_swapin_charge_page(page,
3723 vma->vm_mm, GFP_KERNEL, entry)) {
3727 mem_cgroup_swapin_uncharge_swap(entry);
3729 shadow = get_shadow_from_swap_cache(entry);
3731 workingset_refault(page_folio(page),
3734 lru_cache_add(page);
3736 /* To provide entry to swap_readpage() */
3737 set_page_private(page, entry.val);
3738 swap_readpage(page, true, NULL);
3739 set_page_private(page, 0);
3742 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3749 * Back out if somebody else faulted in this pte
3750 * while we released the pte lock.
3752 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3753 vmf->address, &vmf->ptl);
3754 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3759 /* Had to read the page from swap area: Major fault */
3760 ret = VM_FAULT_MAJOR;
3761 count_vm_event(PGMAJFAULT);
3762 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3763 } else if (PageHWPoison(page)) {
3765 * hwpoisoned dirty swapcache pages are kept for killing
3766 * owner processes (which may be unknown at hwpoison time)
3768 ret = VM_FAULT_HWPOISON;
3772 locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3775 ret |= VM_FAULT_RETRY;
3781 * Make sure try_to_free_swap or swapoff did not release the
3782 * swapcache from under us. The page pin, and pte_same test
3783 * below, are not enough to exclude that. Even if it is still
3784 * swapcache, we need to check that the page's swap has not
3787 if (unlikely(!PageSwapCache(page) ||
3788 page_private(page) != entry.val))
3792 * KSM sometimes has to copy on read faults, for example, if
3793 * page->index of !PageKSM() pages would be nonlinear inside the
3794 * anon VMA -- PageKSM() is lost on actual swapout.
3796 page = ksm_might_need_to_copy(page, vma, vmf->address);
3797 if (unlikely(!page)) {
3804 * If we want to map a page that's in the swapcache writable, we
3805 * have to detect via the refcount if we're really the exclusive
3806 * owner. Try removing the extra reference from the local LRU
3807 * pagevecs if required.
3809 if ((vmf->flags & FAULT_FLAG_WRITE) && page == swapcache &&
3810 !PageKsm(page) && !PageLRU(page))
3814 cgroup_throttle_swaprate(page, GFP_KERNEL);
3817 * Back out if somebody else already faulted in this pte.
3819 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3821 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3824 if (unlikely(!PageUptodate(page))) {
3825 ret = VM_FAULT_SIGBUS;
3830 * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte
3831 * must never point at an anonymous page in the swapcache that is
3832 * PG_anon_exclusive. Sanity check that this holds and especially, that
3833 * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity
3834 * check after taking the PT lock and making sure that nobody
3835 * concurrently faulted in this page and set PG_anon_exclusive.
3837 BUG_ON(!PageAnon(page) && PageMappedToDisk(page));
3838 BUG_ON(PageAnon(page) && PageAnonExclusive(page));
3841 * Check under PT lock (to protect against concurrent fork() sharing
3842 * the swap entry concurrently) for certainly exclusive pages.
3844 if (!PageKsm(page)) {
3846 * Note that pte_swp_exclusive() == false for architectures
3847 * without __HAVE_ARCH_PTE_SWP_EXCLUSIVE.
3849 exclusive = pte_swp_exclusive(vmf->orig_pte);
3850 if (page != swapcache) {
3852 * We have a fresh page that is not exposed to the
3853 * swapcache -> certainly exclusive.
3856 } else if (exclusive && PageWriteback(page) &&
3857 (swp_swap_info(entry)->flags & SWP_STABLE_WRITES)) {
3859 * This is tricky: not all swap backends support
3860 * concurrent page modifications while under writeback.
3862 * So if we stumble over such a page in the swapcache
3863 * we must not set the page exclusive, otherwise we can
3864 * map it writable without further checks and modify it
3865 * while still under writeback.
3867 * For these problematic swap backends, simply drop the
3868 * exclusive marker: this is perfectly fine as we start
3869 * writeback only if we fully unmapped the page and
3870 * there are no unexpected references on the page after
3871 * unmapping succeeded. After fully unmapped, no
3872 * further GUP references (FOLL_GET and FOLL_PIN) can
3873 * appear, so dropping the exclusive marker and mapping
3874 * it only R/O is fine.
3881 * Remove the swap entry and conditionally try to free up the swapcache.
3882 * We're already holding a reference on the page but haven't mapped it
3886 if (should_try_to_free_swap(page, vma, vmf->flags))
3887 try_to_free_swap(page);
3889 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3890 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3891 pte = mk_pte(page, vma->vm_page_prot);
3894 * Same logic as in do_wp_page(); however, optimize for pages that are
3895 * certainly not shared either because we just allocated them without
3896 * exposing them to the swapcache or because the swap entry indicates
3899 if (!PageKsm(page) && (exclusive || page_count(page) == 1)) {
3900 if (vmf->flags & FAULT_FLAG_WRITE) {
3901 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3902 vmf->flags &= ~FAULT_FLAG_WRITE;
3903 ret |= VM_FAULT_WRITE;
3905 rmap_flags |= RMAP_EXCLUSIVE;
3907 flush_icache_page(vma, page);
3908 if (pte_swp_soft_dirty(vmf->orig_pte))
3909 pte = pte_mksoft_dirty(pte);
3910 if (pte_swp_uffd_wp(vmf->orig_pte)) {
3911 pte = pte_mkuffd_wp(pte);
3912 pte = pte_wrprotect(pte);
3914 vmf->orig_pte = pte;
3916 /* ksm created a completely new copy */
3917 if (unlikely(page != swapcache && swapcache)) {
3918 page_add_new_anon_rmap(page, vma, vmf->address);
3919 lru_cache_add_inactive_or_unevictable(page, vma);
3921 page_add_anon_rmap(page, vma, vmf->address, rmap_flags);
3924 VM_BUG_ON(!PageAnon(page) || (pte_write(pte) && !PageAnonExclusive(page)));
3925 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3926 arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
3929 if (page != swapcache && swapcache) {
3931 * Hold the lock to avoid the swap entry to be reused
3932 * until we take the PT lock for the pte_same() check
3933 * (to avoid false positives from pte_same). For
3934 * further safety release the lock after the swap_free
3935 * so that the swap count won't change under a
3936 * parallel locked swapcache.
3938 unlock_page(swapcache);
3939 put_page(swapcache);
3942 if (vmf->flags & FAULT_FLAG_WRITE) {
3943 ret |= do_wp_page(vmf);
3944 if (ret & VM_FAULT_ERROR)
3945 ret &= VM_FAULT_ERROR;
3949 /* No need to invalidate - it was non-present before */
3950 update_mmu_cache(vma, vmf->address, vmf->pte);
3952 pte_unmap_unlock(vmf->pte, vmf->ptl);
3955 put_swap_device(si);
3958 pte_unmap_unlock(vmf->pte, vmf->ptl);
3963 if (page != swapcache && swapcache) {
3964 unlock_page(swapcache);
3965 put_page(swapcache);
3968 put_swap_device(si);
3973 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3974 * but allow concurrent faults), and pte mapped but not yet locked.
3975 * We return with mmap_lock still held, but pte unmapped and unlocked.
3977 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
3979 struct vm_area_struct *vma = vmf->vma;
3984 /* File mapping without ->vm_ops ? */
3985 if (vma->vm_flags & VM_SHARED)
3986 return VM_FAULT_SIGBUS;
3989 * Use pte_alloc() instead of pte_alloc_map(). We can't run
3990 * pte_offset_map() on pmds where a huge pmd might be created
3991 * from a different thread.
3993 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
3994 * parallel threads are excluded by other means.
3996 * Here we only have mmap_read_lock(mm).
3998 if (pte_alloc(vma->vm_mm, vmf->pmd))
3999 return VM_FAULT_OOM;
4001 /* See comment in handle_pte_fault() */
4002 if (unlikely(pmd_trans_unstable(vmf->pmd)))
4005 /* Use the zero-page for reads */
4006 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
4007 !mm_forbids_zeropage(vma->vm_mm)) {
4008 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
4009 vma->vm_page_prot));
4010 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4011 vmf->address, &vmf->ptl);
4012 if (!pte_none(*vmf->pte)) {
4013 update_mmu_tlb(vma, vmf->address, vmf->pte);
4016 ret = check_stable_address_space(vma->vm_mm);
4019 /* Deliver the page fault to userland, check inside PT lock */
4020 if (userfaultfd_missing(vma)) {
4021 pte_unmap_unlock(vmf->pte, vmf->ptl);
4022 return handle_userfault(vmf, VM_UFFD_MISSING);
4027 /* Allocate our own private page. */
4028 if (unlikely(anon_vma_prepare(vma)))
4030 page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
4034 if (mem_cgroup_charge(page_folio(page), vma->vm_mm, GFP_KERNEL))
4036 cgroup_throttle_swaprate(page, GFP_KERNEL);
4039 * The memory barrier inside __SetPageUptodate makes sure that
4040 * preceding stores to the page contents become visible before
4041 * the set_pte_at() write.
4043 __SetPageUptodate(page);
4045 entry = mk_pte(page, vma->vm_page_prot);
4046 entry = pte_sw_mkyoung(entry);
4047 if (vma->vm_flags & VM_WRITE)
4048 entry = pte_mkwrite(pte_mkdirty(entry));
4050 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
4052 if (!pte_none(*vmf->pte)) {
4053 update_mmu_cache(vma, vmf->address, vmf->pte);
4057 ret = check_stable_address_space(vma->vm_mm);
4061 /* Deliver the page fault to userland, check inside PT lock */
4062 if (userfaultfd_missing(vma)) {
4063 pte_unmap_unlock(vmf->pte, vmf->ptl);
4065 return handle_userfault(vmf, VM_UFFD_MISSING);
4068 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
4069 page_add_new_anon_rmap(page, vma, vmf->address);
4070 lru_cache_add_inactive_or_unevictable(page, vma);
4072 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
4074 /* No need to invalidate - it was non-present before */
4075 update_mmu_cache(vma, vmf->address, vmf->pte);
4077 pte_unmap_unlock(vmf->pte, vmf->ptl);
4085 return VM_FAULT_OOM;
4089 * The mmap_lock must have been held on entry, and may have been
4090 * released depending on flags and vma->vm_ops->fault() return value.
4091 * See filemap_fault() and __lock_page_retry().
4093 static vm_fault_t __do_fault(struct vm_fault *vmf)
4095 struct vm_area_struct *vma = vmf->vma;
4099 * Preallocate pte before we take page_lock because this might lead to
4100 * deadlocks for memcg reclaim which waits for pages under writeback:
4102 * SetPageWriteback(A)
4108 * wait_on_page_writeback(A)
4109 * SetPageWriteback(B)
4111 * # flush A, B to clear the writeback
4113 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
4114 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
4115 if (!vmf->prealloc_pte)
4116 return VM_FAULT_OOM;
4119 ret = vma->vm_ops->fault(vmf);
4120 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
4121 VM_FAULT_DONE_COW)))
4124 if (unlikely(PageHWPoison(vmf->page))) {
4125 struct page *page = vmf->page;
4126 vm_fault_t poisonret = VM_FAULT_HWPOISON;
4127 if (ret & VM_FAULT_LOCKED) {
4128 if (page_mapped(page))
4129 unmap_mapping_pages(page_mapping(page),
4130 page->index, 1, false);
4131 /* Retry if a clean page was removed from the cache. */
4132 if (invalidate_inode_page(page))
4133 poisonret = VM_FAULT_NOPAGE;
4141 if (unlikely(!(ret & VM_FAULT_LOCKED)))
4142 lock_page(vmf->page);
4144 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
4149 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4150 static void deposit_prealloc_pte(struct vm_fault *vmf)
4152 struct vm_area_struct *vma = vmf->vma;
4154 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
4156 * We are going to consume the prealloc table,
4157 * count that as nr_ptes.
4159 mm_inc_nr_ptes(vma->vm_mm);
4160 vmf->prealloc_pte = NULL;
4163 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
4165 struct vm_area_struct *vma = vmf->vma;
4166 bool write = vmf->flags & FAULT_FLAG_WRITE;
4167 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
4170 vm_fault_t ret = VM_FAULT_FALLBACK;
4172 if (!transhuge_vma_suitable(vma, haddr))
4175 page = compound_head(page);
4176 if (compound_order(page) != HPAGE_PMD_ORDER)
4180 * Just backoff if any subpage of a THP is corrupted otherwise
4181 * the corrupted page may mapped by PMD silently to escape the
4182 * check. This kind of THP just can be PTE mapped. Access to
4183 * the corrupted subpage should trigger SIGBUS as expected.
4185 if (unlikely(PageHasHWPoisoned(page)))
4189 * Archs like ppc64 need additional space to store information
4190 * related to pte entry. Use the preallocated table for that.
4192 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
4193 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
4194 if (!vmf->prealloc_pte)
4195 return VM_FAULT_OOM;
4198 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
4199 if (unlikely(!pmd_none(*vmf->pmd)))
4202 for (i = 0; i < HPAGE_PMD_NR; i++)
4203 flush_icache_page(vma, page + i);
4205 entry = mk_huge_pmd(page, vma->vm_page_prot);
4207 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
4209 add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
4210 page_add_file_rmap(page, vma, true);
4213 * deposit and withdraw with pmd lock held
4215 if (arch_needs_pgtable_deposit())
4216 deposit_prealloc_pte(vmf);
4218 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
4220 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
4222 /* fault is handled */
4224 count_vm_event(THP_FILE_MAPPED);
4226 spin_unlock(vmf->ptl);
4230 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
4232 return VM_FAULT_FALLBACK;
4236 void do_set_pte(struct vm_fault *vmf, struct page *page, unsigned long addr)
4238 struct vm_area_struct *vma = vmf->vma;
4239 bool uffd_wp = pte_marker_uffd_wp(vmf->orig_pte);
4240 bool write = vmf->flags & FAULT_FLAG_WRITE;
4241 bool prefault = vmf->address != addr;
4244 flush_icache_page(vma, page);
4245 entry = mk_pte(page, vma->vm_page_prot);
4247 if (prefault && arch_wants_old_prefaulted_pte())
4248 entry = pte_mkold(entry);
4250 entry = pte_sw_mkyoung(entry);
4253 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
4254 if (unlikely(uffd_wp))
4255 entry = pte_mkuffd_wp(pte_wrprotect(entry));
4256 /* copy-on-write page */
4257 if (write && !(vma->vm_flags & VM_SHARED)) {
4258 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
4259 page_add_new_anon_rmap(page, vma, addr);
4260 lru_cache_add_inactive_or_unevictable(page, vma);
4262 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
4263 page_add_file_rmap(page, vma, false);
4265 set_pte_at(vma->vm_mm, addr, vmf->pte, entry);
4268 static bool vmf_pte_changed(struct vm_fault *vmf)
4270 if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)
4271 return !pte_same(*vmf->pte, vmf->orig_pte);
4273 return !pte_none(*vmf->pte);
4277 * finish_fault - finish page fault once we have prepared the page to fault
4279 * @vmf: structure describing the fault
4281 * This function handles all that is needed to finish a page fault once the
4282 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
4283 * given page, adds reverse page mapping, handles memcg charges and LRU
4286 * The function expects the page to be locked and on success it consumes a
4287 * reference of a page being mapped (for the PTE which maps it).
4289 * Return: %0 on success, %VM_FAULT_ code in case of error.
4291 vm_fault_t finish_fault(struct vm_fault *vmf)
4293 struct vm_area_struct *vma = vmf->vma;
4297 /* Did we COW the page? */
4298 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED))
4299 page = vmf->cow_page;
4304 * check even for read faults because we might have lost our CoWed
4307 if (!(vma->vm_flags & VM_SHARED)) {
4308 ret = check_stable_address_space(vma->vm_mm);
4313 if (pmd_none(*vmf->pmd)) {
4314 if (PageTransCompound(page)) {
4315 ret = do_set_pmd(vmf, page);
4316 if (ret != VM_FAULT_FALLBACK)
4320 if (vmf->prealloc_pte)
4321 pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte);
4322 else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd)))
4323 return VM_FAULT_OOM;
4326 /* See comment in handle_pte_fault() */
4327 if (pmd_devmap_trans_unstable(vmf->pmd))
4330 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4331 vmf->address, &vmf->ptl);
4333 /* Re-check under ptl */
4334 if (likely(!vmf_pte_changed(vmf)))
4335 do_set_pte(vmf, page, vmf->address);
4337 ret = VM_FAULT_NOPAGE;
4339 update_mmu_tlb(vma, vmf->address, vmf->pte);
4340 pte_unmap_unlock(vmf->pte, vmf->ptl);
4344 static unsigned long fault_around_bytes __read_mostly =
4345 rounddown_pow_of_two(65536);
4347 #ifdef CONFIG_DEBUG_FS
4348 static int fault_around_bytes_get(void *data, u64 *val)
4350 *val = fault_around_bytes;
4355 * fault_around_bytes must be rounded down to the nearest page order as it's
4356 * what do_fault_around() expects to see.
4358 static int fault_around_bytes_set(void *data, u64 val)
4360 if (val / PAGE_SIZE > PTRS_PER_PTE)
4362 if (val > PAGE_SIZE)
4363 fault_around_bytes = rounddown_pow_of_two(val);
4365 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
4368 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
4369 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
4371 static int __init fault_around_debugfs(void)
4373 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
4374 &fault_around_bytes_fops);
4377 late_initcall(fault_around_debugfs);
4381 * do_fault_around() tries to map few pages around the fault address. The hope
4382 * is that the pages will be needed soon and this will lower the number of
4385 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
4386 * not ready to be mapped: not up-to-date, locked, etc.
4388 * This function is called with the page table lock taken. In the split ptlock
4389 * case the page table lock only protects only those entries which belong to
4390 * the page table corresponding to the fault address.
4392 * This function doesn't cross the VMA boundaries, in order to call map_pages()
4395 * fault_around_bytes defines how many bytes we'll try to map.
4396 * do_fault_around() expects it to be set to a power of two less than or equal
4399 * The virtual address of the area that we map is naturally aligned to
4400 * fault_around_bytes rounded down to the machine page size
4401 * (and therefore to page order). This way it's easier to guarantee
4402 * that we don't cross page table boundaries.
4404 static vm_fault_t do_fault_around(struct vm_fault *vmf)
4406 unsigned long address = vmf->address, nr_pages, mask;
4407 pgoff_t start_pgoff = vmf->pgoff;
4411 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
4412 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
4414 address = max(address & mask, vmf->vma->vm_start);
4415 off = ((vmf->address - address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
4419 * end_pgoff is either the end of the page table, the end of
4420 * the vma or nr_pages from start_pgoff, depending what is nearest.
4422 end_pgoff = start_pgoff -
4423 ((address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
4425 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
4426 start_pgoff + nr_pages - 1);
4428 if (pmd_none(*vmf->pmd)) {
4429 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
4430 if (!vmf->prealloc_pte)
4431 return VM_FAULT_OOM;
4434 return vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
4437 /* Return true if we should do read fault-around, false otherwise */
4438 static inline bool should_fault_around(struct vm_fault *vmf)
4440 /* No ->map_pages? No way to fault around... */
4441 if (!vmf->vma->vm_ops->map_pages)
4444 if (uffd_disable_fault_around(vmf->vma))
4447 return fault_around_bytes >> PAGE_SHIFT > 1;
4450 static vm_fault_t do_read_fault(struct vm_fault *vmf)
4455 * Let's call ->map_pages() first and use ->fault() as fallback
4456 * if page by the offset is not ready to be mapped (cold cache or
4459 if (should_fault_around(vmf)) {
4460 ret = do_fault_around(vmf);
4465 ret = __do_fault(vmf);
4466 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4469 ret |= finish_fault(vmf);
4470 unlock_page(vmf->page);
4471 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4472 put_page(vmf->page);
4476 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
4478 struct vm_area_struct *vma = vmf->vma;
4481 if (unlikely(anon_vma_prepare(vma)))
4482 return VM_FAULT_OOM;
4484 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
4486 return VM_FAULT_OOM;
4488 if (mem_cgroup_charge(page_folio(vmf->cow_page), vma->vm_mm,
4490 put_page(vmf->cow_page);
4491 return VM_FAULT_OOM;
4493 cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL);
4495 ret = __do_fault(vmf);
4496 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4498 if (ret & VM_FAULT_DONE_COW)
4501 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
4502 __SetPageUptodate(vmf->cow_page);
4504 ret |= finish_fault(vmf);
4505 unlock_page(vmf->page);
4506 put_page(vmf->page);
4507 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4511 put_page(vmf->cow_page);
4515 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
4517 struct vm_area_struct *vma = vmf->vma;
4518 vm_fault_t ret, tmp;
4520 ret = __do_fault(vmf);
4521 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4525 * Check if the backing address space wants to know that the page is
4526 * about to become writable
4528 if (vma->vm_ops->page_mkwrite) {
4529 unlock_page(vmf->page);
4530 tmp = do_page_mkwrite(vmf);
4531 if (unlikely(!tmp ||
4532 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
4533 put_page(vmf->page);
4538 ret |= finish_fault(vmf);
4539 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
4541 unlock_page(vmf->page);
4542 put_page(vmf->page);
4546 ret |= fault_dirty_shared_page(vmf);
4551 * We enter with non-exclusive mmap_lock (to exclude vma changes,
4552 * but allow concurrent faults).
4553 * The mmap_lock may have been released depending on flags and our
4554 * return value. See filemap_fault() and __folio_lock_or_retry().
4555 * If mmap_lock is released, vma may become invalid (for example
4556 * by other thread calling munmap()).
4558 static vm_fault_t do_fault(struct vm_fault *vmf)
4560 struct vm_area_struct *vma = vmf->vma;
4561 struct mm_struct *vm_mm = vma->vm_mm;
4565 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
4567 if (!vma->vm_ops->fault) {
4569 * If we find a migration pmd entry or a none pmd entry, which
4570 * should never happen, return SIGBUS
4572 if (unlikely(!pmd_present(*vmf->pmd)))
4573 ret = VM_FAULT_SIGBUS;
4575 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
4580 * Make sure this is not a temporary clearing of pte
4581 * by holding ptl and checking again. A R/M/W update
4582 * of pte involves: take ptl, clearing the pte so that
4583 * we don't have concurrent modification by hardware
4584 * followed by an update.
4586 if (unlikely(pte_none(*vmf->pte)))
4587 ret = VM_FAULT_SIGBUS;
4589 ret = VM_FAULT_NOPAGE;
4591 pte_unmap_unlock(vmf->pte, vmf->ptl);
4593 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
4594 ret = do_read_fault(vmf);
4595 else if (!(vma->vm_flags & VM_SHARED))
4596 ret = do_cow_fault(vmf);
4598 ret = do_shared_fault(vmf);
4600 /* preallocated pagetable is unused: free it */
4601 if (vmf->prealloc_pte) {
4602 pte_free(vm_mm, vmf->prealloc_pte);
4603 vmf->prealloc_pte = NULL;
4608 int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
4609 unsigned long addr, int page_nid, int *flags)
4613 count_vm_numa_event(NUMA_HINT_FAULTS);
4614 if (page_nid == numa_node_id()) {
4615 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
4616 *flags |= TNF_FAULT_LOCAL;
4619 return mpol_misplaced(page, vma, addr);
4622 static vm_fault_t do_numa_page(struct vm_fault *vmf)
4624 struct vm_area_struct *vma = vmf->vma;
4625 struct page *page = NULL;
4626 int page_nid = NUMA_NO_NODE;
4630 bool was_writable = pte_savedwrite(vmf->orig_pte);
4634 * The "pte" at this point cannot be used safely without
4635 * validation through pte_unmap_same(). It's of NUMA type but
4636 * the pfn may be screwed if the read is non atomic.
4638 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
4639 spin_lock(vmf->ptl);
4640 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4641 pte_unmap_unlock(vmf->pte, vmf->ptl);
4645 /* Get the normal PTE */
4646 old_pte = ptep_get(vmf->pte);
4647 pte = pte_modify(old_pte, vma->vm_page_prot);
4649 page = vm_normal_page(vma, vmf->address, pte);
4653 /* TODO: handle PTE-mapped THP */
4654 if (PageCompound(page))
4658 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
4659 * much anyway since they can be in shared cache state. This misses
4660 * the case where a mapping is writable but the process never writes
4661 * to it but pte_write gets cleared during protection updates and
4662 * pte_dirty has unpredictable behaviour between PTE scan updates,
4663 * background writeback, dirty balancing and application behaviour.
4666 flags |= TNF_NO_GROUP;
4669 * Flag if the page is shared between multiple address spaces. This
4670 * is later used when determining whether to group tasks together
4672 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
4673 flags |= TNF_SHARED;
4675 last_cpupid = page_cpupid_last(page);
4676 page_nid = page_to_nid(page);
4677 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
4679 if (target_nid == NUMA_NO_NODE) {
4683 pte_unmap_unlock(vmf->pte, vmf->ptl);
4685 /* Migrate to the requested node */
4686 if (migrate_misplaced_page(page, vma, target_nid)) {
4687 page_nid = target_nid;
4688 flags |= TNF_MIGRATED;
4690 flags |= TNF_MIGRATE_FAIL;
4691 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4692 spin_lock(vmf->ptl);
4693 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4694 pte_unmap_unlock(vmf->pte, vmf->ptl);
4701 if (page_nid != NUMA_NO_NODE)
4702 task_numa_fault(last_cpupid, page_nid, 1, flags);
4706 * Make it present again, depending on how arch implements
4707 * non-accessible ptes, some can allow access by kernel mode.
4709 old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte);
4710 pte = pte_modify(old_pte, vma->vm_page_prot);
4711 pte = pte_mkyoung(pte);
4713 pte = pte_mkwrite(pte);
4714 ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte);
4715 update_mmu_cache(vma, vmf->address, vmf->pte);
4716 pte_unmap_unlock(vmf->pte, vmf->ptl);
4720 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4722 if (vma_is_anonymous(vmf->vma))
4723 return do_huge_pmd_anonymous_page(vmf);
4724 if (vmf->vma->vm_ops->huge_fault)
4725 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4726 return VM_FAULT_FALLBACK;
4729 /* `inline' is required to avoid gcc 4.1.2 build error */
4730 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf)
4732 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
4734 if (vma_is_anonymous(vmf->vma)) {
4735 if (likely(!unshare) &&
4736 userfaultfd_huge_pmd_wp(vmf->vma, vmf->orig_pmd))
4737 return handle_userfault(vmf, VM_UFFD_WP);
4738 return do_huge_pmd_wp_page(vmf);
4740 if (vmf->vma->vm_ops->huge_fault) {
4741 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4743 if (!(ret & VM_FAULT_FALLBACK))
4747 /* COW or write-notify handled on pte level: split pmd. */
4748 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4750 return VM_FAULT_FALLBACK;
4753 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4755 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
4756 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4757 /* No support for anonymous transparent PUD pages yet */
4758 if (vma_is_anonymous(vmf->vma))
4760 if (vmf->vma->vm_ops->huge_fault) {
4761 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4763 if (!(ret & VM_FAULT_FALLBACK))
4767 /* COW or write-notify not handled on PUD level: split pud.*/
4768 __split_huge_pud(vmf->vma, vmf->pud, vmf->address);
4769 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4770 return VM_FAULT_FALLBACK;
4773 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4775 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4776 /* No support for anonymous transparent PUD pages yet */
4777 if (vma_is_anonymous(vmf->vma))
4778 return VM_FAULT_FALLBACK;
4779 if (vmf->vma->vm_ops->huge_fault)
4780 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4781 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4782 return VM_FAULT_FALLBACK;
4786 * These routines also need to handle stuff like marking pages dirty
4787 * and/or accessed for architectures that don't do it in hardware (most
4788 * RISC architectures). The early dirtying is also good on the i386.
4790 * There is also a hook called "update_mmu_cache()" that architectures
4791 * with external mmu caches can use to update those (ie the Sparc or
4792 * PowerPC hashed page tables that act as extended TLBs).
4794 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
4795 * concurrent faults).
4797 * The mmap_lock may have been released depending on flags and our return value.
4798 * See filemap_fault() and __folio_lock_or_retry().
4800 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4804 if (unlikely(pmd_none(*vmf->pmd))) {
4806 * Leave __pte_alloc() until later: because vm_ops->fault may
4807 * want to allocate huge page, and if we expose page table
4808 * for an instant, it will be difficult to retract from
4809 * concurrent faults and from rmap lookups.
4812 vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID;
4815 * If a huge pmd materialized under us just retry later. Use
4816 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead
4817 * of pmd_trans_huge() to ensure the pmd didn't become
4818 * pmd_trans_huge under us and then back to pmd_none, as a
4819 * result of MADV_DONTNEED running immediately after a huge pmd
4820 * fault in a different thread of this mm, in turn leading to a
4821 * misleading pmd_trans_huge() retval. All we have to ensure is
4822 * that it is a regular pmd that we can walk with
4823 * pte_offset_map() and we can do that through an atomic read
4824 * in C, which is what pmd_trans_unstable() provides.
4826 if (pmd_devmap_trans_unstable(vmf->pmd))
4829 * A regular pmd is established and it can't morph into a huge
4830 * pmd from under us anymore at this point because we hold the
4831 * mmap_lock read mode and khugepaged takes it in write mode.
4832 * So now it's safe to run pte_offset_map().
4834 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4835 vmf->orig_pte = *vmf->pte;
4836 vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID;
4839 * some architectures can have larger ptes than wordsize,
4840 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4841 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4842 * accesses. The code below just needs a consistent view
4843 * for the ifs and we later double check anyway with the
4844 * ptl lock held. So here a barrier will do.
4847 if (pte_none(vmf->orig_pte)) {
4848 pte_unmap(vmf->pte);
4854 if (vma_is_anonymous(vmf->vma))
4855 return do_anonymous_page(vmf);
4857 return do_fault(vmf);
4860 if (!pte_present(vmf->orig_pte))
4861 return do_swap_page(vmf);
4863 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4864 return do_numa_page(vmf);
4866 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4867 spin_lock(vmf->ptl);
4868 entry = vmf->orig_pte;
4869 if (unlikely(!pte_same(*vmf->pte, entry))) {
4870 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
4873 if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
4874 if (!pte_write(entry))
4875 return do_wp_page(vmf);
4876 else if (likely(vmf->flags & FAULT_FLAG_WRITE))
4877 entry = pte_mkdirty(entry);
4879 entry = pte_mkyoung(entry);
4880 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4881 vmf->flags & FAULT_FLAG_WRITE)) {
4882 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4884 /* Skip spurious TLB flush for retried page fault */
4885 if (vmf->flags & FAULT_FLAG_TRIED)
4888 * This is needed only for protection faults but the arch code
4889 * is not yet telling us if this is a protection fault or not.
4890 * This still avoids useless tlb flushes for .text page faults
4893 if (vmf->flags & FAULT_FLAG_WRITE)
4894 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4897 pte_unmap_unlock(vmf->pte, vmf->ptl);
4902 * By the time we get here, we already hold the mm semaphore
4904 * The mmap_lock may have been released depending on flags and our
4905 * return value. See filemap_fault() and __folio_lock_or_retry().
4907 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
4908 unsigned long address, unsigned int flags)
4910 struct vm_fault vmf = {
4912 .address = address & PAGE_MASK,
4913 .real_address = address,
4915 .pgoff = linear_page_index(vma, address),
4916 .gfp_mask = __get_fault_gfp_mask(vma),
4918 struct mm_struct *mm = vma->vm_mm;
4923 pgd = pgd_offset(mm, address);
4924 p4d = p4d_alloc(mm, pgd, address);
4926 return VM_FAULT_OOM;
4928 vmf.pud = pud_alloc(mm, p4d, address);
4930 return VM_FAULT_OOM;
4932 if (pud_none(*vmf.pud) && __transparent_hugepage_enabled(vma)) {
4933 ret = create_huge_pud(&vmf);
4934 if (!(ret & VM_FAULT_FALLBACK))
4937 pud_t orig_pud = *vmf.pud;
4940 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4943 * TODO once we support anonymous PUDs: NUMA case and
4944 * FAULT_FLAG_UNSHARE handling.
4946 if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) {
4947 ret = wp_huge_pud(&vmf, orig_pud);
4948 if (!(ret & VM_FAULT_FALLBACK))
4951 huge_pud_set_accessed(&vmf, orig_pud);
4957 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4959 return VM_FAULT_OOM;
4961 /* Huge pud page fault raced with pmd_alloc? */
4962 if (pud_trans_unstable(vmf.pud))
4965 if (pmd_none(*vmf.pmd) && __transparent_hugepage_enabled(vma)) {
4966 ret = create_huge_pmd(&vmf);
4967 if (!(ret & VM_FAULT_FALLBACK))
4970 vmf.orig_pmd = *vmf.pmd;
4973 if (unlikely(is_swap_pmd(vmf.orig_pmd))) {
4974 VM_BUG_ON(thp_migration_supported() &&
4975 !is_pmd_migration_entry(vmf.orig_pmd));
4976 if (is_pmd_migration_entry(vmf.orig_pmd))
4977 pmd_migration_entry_wait(mm, vmf.pmd);
4980 if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) {
4981 if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma))
4982 return do_huge_pmd_numa_page(&vmf);
4984 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
4985 !pmd_write(vmf.orig_pmd)) {
4986 ret = wp_huge_pmd(&vmf);
4987 if (!(ret & VM_FAULT_FALLBACK))
4990 huge_pmd_set_accessed(&vmf);
4996 return handle_pte_fault(&vmf);
5000 * mm_account_fault - Do page fault accounting
5002 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting
5003 * of perf event counters, but we'll still do the per-task accounting to
5004 * the task who triggered this page fault.
5005 * @address: the faulted address.
5006 * @flags: the fault flags.
5007 * @ret: the fault retcode.
5009 * This will take care of most of the page fault accounting. Meanwhile, it
5010 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
5011 * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
5012 * still be in per-arch page fault handlers at the entry of page fault.
5014 static inline void mm_account_fault(struct pt_regs *regs,
5015 unsigned long address, unsigned int flags,
5021 * We don't do accounting for some specific faults:
5023 * - Unsuccessful faults (e.g. when the address wasn't valid). That
5024 * includes arch_vma_access_permitted() failing before reaching here.
5025 * So this is not a "this many hardware page faults" counter. We
5026 * should use the hw profiling for that.
5028 * - Incomplete faults (VM_FAULT_RETRY). They will only be counted
5029 * once they're completed.
5031 if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY))
5035 * We define the fault as a major fault when the final successful fault
5036 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
5037 * handle it immediately previously).
5039 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
5047 * If the fault is done for GUP, regs will be NULL. We only do the
5048 * accounting for the per thread fault counters who triggered the
5049 * fault, and we skip the perf event updates.
5055 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
5057 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
5061 * By the time we get here, we already hold the mm semaphore
5063 * The mmap_lock may have been released depending on flags and our
5064 * return value. See filemap_fault() and __folio_lock_or_retry().
5066 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
5067 unsigned int flags, struct pt_regs *regs)
5071 __set_current_state(TASK_RUNNING);
5073 count_vm_event(PGFAULT);
5074 count_memcg_event_mm(vma->vm_mm, PGFAULT);
5076 /* do counter updates before entering really critical section. */
5077 check_sync_rss_stat(current);
5079 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
5080 flags & FAULT_FLAG_INSTRUCTION,
5081 flags & FAULT_FLAG_REMOTE))
5082 return VM_FAULT_SIGSEGV;
5085 * Enable the memcg OOM handling for faults triggered in user
5086 * space. Kernel faults are handled more gracefully.
5088 if (flags & FAULT_FLAG_USER)
5089 mem_cgroup_enter_user_fault();
5091 if (unlikely(is_vm_hugetlb_page(vma)))
5092 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
5094 ret = __handle_mm_fault(vma, address, flags);
5096 if (flags & FAULT_FLAG_USER) {
5097 mem_cgroup_exit_user_fault();
5099 * The task may have entered a memcg OOM situation but
5100 * if the allocation error was handled gracefully (no
5101 * VM_FAULT_OOM), there is no need to kill anything.
5102 * Just clean up the OOM state peacefully.
5104 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
5105 mem_cgroup_oom_synchronize(false);
5108 mm_account_fault(regs, address, flags, ret);
5112 EXPORT_SYMBOL_GPL(handle_mm_fault);
5114 #ifndef __PAGETABLE_P4D_FOLDED
5116 * Allocate p4d page table.
5117 * We've already handled the fast-path in-line.
5119 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
5121 p4d_t *new = p4d_alloc_one(mm, address);
5125 spin_lock(&mm->page_table_lock);
5126 if (pgd_present(*pgd)) { /* Another has populated it */
5129 smp_wmb(); /* See comment in pmd_install() */
5130 pgd_populate(mm, pgd, new);
5132 spin_unlock(&mm->page_table_lock);
5135 #endif /* __PAGETABLE_P4D_FOLDED */
5137 #ifndef __PAGETABLE_PUD_FOLDED
5139 * Allocate page upper directory.
5140 * We've already handled the fast-path in-line.
5142 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
5144 pud_t *new = pud_alloc_one(mm, address);
5148 spin_lock(&mm->page_table_lock);
5149 if (!p4d_present(*p4d)) {
5151 smp_wmb(); /* See comment in pmd_install() */
5152 p4d_populate(mm, p4d, new);
5153 } else /* Another has populated it */
5155 spin_unlock(&mm->page_table_lock);
5158 #endif /* __PAGETABLE_PUD_FOLDED */
5160 #ifndef __PAGETABLE_PMD_FOLDED
5162 * Allocate page middle directory.
5163 * We've already handled the fast-path in-line.
5165 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
5168 pmd_t *new = pmd_alloc_one(mm, address);
5172 ptl = pud_lock(mm, pud);
5173 if (!pud_present(*pud)) {
5175 smp_wmb(); /* See comment in pmd_install() */
5176 pud_populate(mm, pud, new);
5177 } else { /* Another has populated it */
5183 #endif /* __PAGETABLE_PMD_FOLDED */
5186 * follow_pte - look up PTE at a user virtual address
5187 * @mm: the mm_struct of the target address space
5188 * @address: user virtual address
5189 * @ptepp: location to store found PTE
5190 * @ptlp: location to store the lock for the PTE
5192 * On a successful return, the pointer to the PTE is stored in @ptepp;
5193 * the corresponding lock is taken and its location is stored in @ptlp.
5194 * The contents of the PTE are only stable until @ptlp is released;
5195 * any further use, if any, must be protected against invalidation
5196 * with MMU notifiers.
5198 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore
5199 * should be taken for read.
5201 * KVM uses this function. While it is arguably less bad than ``follow_pfn``,
5202 * it is not a good general-purpose API.
5204 * Return: zero on success, -ve otherwise.
5206 int follow_pte(struct mm_struct *mm, unsigned long address,
5207 pte_t **ptepp, spinlock_t **ptlp)
5215 pgd = pgd_offset(mm, address);
5216 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
5219 p4d = p4d_offset(pgd, address);
5220 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
5223 pud = pud_offset(p4d, address);
5224 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
5227 pmd = pmd_offset(pud, address);
5228 VM_BUG_ON(pmd_trans_huge(*pmd));
5230 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
5233 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
5234 if (!pte_present(*ptep))
5239 pte_unmap_unlock(ptep, *ptlp);
5243 EXPORT_SYMBOL_GPL(follow_pte);
5246 * follow_pfn - look up PFN at a user virtual address
5247 * @vma: memory mapping
5248 * @address: user virtual address
5249 * @pfn: location to store found PFN
5251 * Only IO mappings and raw PFN mappings are allowed.
5253 * This function does not allow the caller to read the permissions
5254 * of the PTE. Do not use it.
5256 * Return: zero and the pfn at @pfn on success, -ve otherwise.
5258 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
5265 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5268 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
5271 *pfn = pte_pfn(*ptep);
5272 pte_unmap_unlock(ptep, ptl);
5275 EXPORT_SYMBOL(follow_pfn);
5277 #ifdef CONFIG_HAVE_IOREMAP_PROT
5278 int follow_phys(struct vm_area_struct *vma,
5279 unsigned long address, unsigned int flags,
5280 unsigned long *prot, resource_size_t *phys)
5286 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5289 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
5293 if ((flags & FOLL_WRITE) && !pte_write(pte))
5296 *prot = pgprot_val(pte_pgprot(pte));
5297 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5301 pte_unmap_unlock(ptep, ptl);
5307 * generic_access_phys - generic implementation for iomem mmap access
5308 * @vma: the vma to access
5309 * @addr: userspace address, not relative offset within @vma
5310 * @buf: buffer to read/write
5311 * @len: length of transfer
5312 * @write: set to FOLL_WRITE when writing, otherwise reading
5314 * This is a generic implementation for &vm_operations_struct.access for an
5315 * iomem mapping. This callback is used by access_process_vm() when the @vma is
5318 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
5319 void *buf, int len, int write)
5321 resource_size_t phys_addr;
5322 unsigned long prot = 0;
5323 void __iomem *maddr;
5326 int offset = offset_in_page(addr);
5329 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5333 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl))
5336 pte_unmap_unlock(ptep, ptl);
5338 prot = pgprot_val(pte_pgprot(pte));
5339 phys_addr = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5341 if ((write & FOLL_WRITE) && !pte_write(pte))
5344 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
5348 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl))
5351 if (!pte_same(pte, *ptep)) {
5352 pte_unmap_unlock(ptep, ptl);
5359 memcpy_toio(maddr + offset, buf, len);
5361 memcpy_fromio(buf, maddr + offset, len);
5363 pte_unmap_unlock(ptep, ptl);
5369 EXPORT_SYMBOL_GPL(generic_access_phys);
5373 * Access another process' address space as given in mm.
5375 int __access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf,
5376 int len, unsigned int gup_flags)
5378 struct vm_area_struct *vma;
5379 void *old_buf = buf;
5380 int write = gup_flags & FOLL_WRITE;
5382 if (mmap_read_lock_killable(mm))
5385 /* ignore errors, just check how much was successfully transferred */
5387 int bytes, ret, offset;
5389 struct page *page = NULL;
5391 ret = get_user_pages_remote(mm, addr, 1,
5392 gup_flags, &page, &vma, NULL);
5394 #ifndef CONFIG_HAVE_IOREMAP_PROT
5398 * Check if this is a VM_IO | VM_PFNMAP VMA, which
5399 * we can access using slightly different code.
5401 vma = vma_lookup(mm, addr);
5404 if (vma->vm_ops && vma->vm_ops->access)
5405 ret = vma->vm_ops->access(vma, addr, buf,
5413 offset = addr & (PAGE_SIZE-1);
5414 if (bytes > PAGE_SIZE-offset)
5415 bytes = PAGE_SIZE-offset;
5419 copy_to_user_page(vma, page, addr,
5420 maddr + offset, buf, bytes);
5421 set_page_dirty_lock(page);
5423 copy_from_user_page(vma, page, addr,
5424 buf, maddr + offset, bytes);
5433 mmap_read_unlock(mm);
5435 return buf - old_buf;
5439 * access_remote_vm - access another process' address space
5440 * @mm: the mm_struct of the target address space
5441 * @addr: start address to access
5442 * @buf: source or destination buffer
5443 * @len: number of bytes to transfer
5444 * @gup_flags: flags modifying lookup behaviour
5446 * The caller must hold a reference on @mm.
5448 * Return: number of bytes copied from source to destination.
5450 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
5451 void *buf, int len, unsigned int gup_flags)
5453 return __access_remote_vm(mm, addr, buf, len, gup_flags);
5457 * Access another process' address space.
5458 * Source/target buffer must be kernel space,
5459 * Do not walk the page table directly, use get_user_pages
5461 int access_process_vm(struct task_struct *tsk, unsigned long addr,
5462 void *buf, int len, unsigned int gup_flags)
5464 struct mm_struct *mm;
5467 mm = get_task_mm(tsk);
5471 ret = __access_remote_vm(mm, addr, buf, len, gup_flags);
5477 EXPORT_SYMBOL_GPL(access_process_vm);
5480 * Print the name of a VMA.
5482 void print_vma_addr(char *prefix, unsigned long ip)
5484 struct mm_struct *mm = current->mm;
5485 struct vm_area_struct *vma;
5488 * we might be running from an atomic context so we cannot sleep
5490 if (!mmap_read_trylock(mm))
5493 vma = find_vma(mm, ip);
5494 if (vma && vma->vm_file) {
5495 struct file *f = vma->vm_file;
5496 char *buf = (char *)__get_free_page(GFP_NOWAIT);
5500 p = file_path(f, buf, PAGE_SIZE);
5503 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
5505 vma->vm_end - vma->vm_start);
5506 free_page((unsigned long)buf);
5509 mmap_read_unlock(mm);
5512 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5513 void __might_fault(const char *file, int line)
5515 if (pagefault_disabled())
5517 __might_sleep(file, line);
5518 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5520 might_lock_read(¤t->mm->mmap_lock);
5523 EXPORT_SYMBOL(__might_fault);
5526 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
5528 * Process all subpages of the specified huge page with the specified
5529 * operation. The target subpage will be processed last to keep its
5532 static inline void process_huge_page(
5533 unsigned long addr_hint, unsigned int pages_per_huge_page,
5534 void (*process_subpage)(unsigned long addr, int idx, void *arg),
5538 unsigned long addr = addr_hint &
5539 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5541 /* Process target subpage last to keep its cache lines hot */
5543 n = (addr_hint - addr) / PAGE_SIZE;
5544 if (2 * n <= pages_per_huge_page) {
5545 /* If target subpage in first half of huge page */
5548 /* Process subpages at the end of huge page */
5549 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
5551 process_subpage(addr + i * PAGE_SIZE, i, arg);
5554 /* If target subpage in second half of huge page */
5555 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
5556 l = pages_per_huge_page - n;
5557 /* Process subpages at the begin of huge page */
5558 for (i = 0; i < base; i++) {
5560 process_subpage(addr + i * PAGE_SIZE, i, arg);
5564 * Process remaining subpages in left-right-left-right pattern
5565 * towards the target subpage
5567 for (i = 0; i < l; i++) {
5568 int left_idx = base + i;
5569 int right_idx = base + 2 * l - 1 - i;
5572 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
5574 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
5578 static void clear_gigantic_page(struct page *page,
5580 unsigned int pages_per_huge_page)
5583 struct page *p = page;
5586 for (i = 0; i < pages_per_huge_page;
5587 i++, p = mem_map_next(p, page, i)) {
5589 clear_user_highpage(p, addr + i * PAGE_SIZE);
5593 static void clear_subpage(unsigned long addr, int idx, void *arg)
5595 struct page *page = arg;
5597 clear_user_highpage(page + idx, addr);
5600 void clear_huge_page(struct page *page,
5601 unsigned long addr_hint, unsigned int pages_per_huge_page)
5603 unsigned long addr = addr_hint &
5604 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5606 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5607 clear_gigantic_page(page, addr, pages_per_huge_page);
5611 process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
5614 static void copy_user_gigantic_page(struct page *dst, struct page *src,
5616 struct vm_area_struct *vma,
5617 unsigned int pages_per_huge_page)
5620 struct page *dst_base = dst;
5621 struct page *src_base = src;
5623 for (i = 0; i < pages_per_huge_page; ) {
5625 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
5628 dst = mem_map_next(dst, dst_base, i);
5629 src = mem_map_next(src, src_base, i);
5633 struct copy_subpage_arg {
5636 struct vm_area_struct *vma;
5639 static void copy_subpage(unsigned long addr, int idx, void *arg)
5641 struct copy_subpage_arg *copy_arg = arg;
5643 copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
5644 addr, copy_arg->vma);
5647 void copy_user_huge_page(struct page *dst, struct page *src,
5648 unsigned long addr_hint, struct vm_area_struct *vma,
5649 unsigned int pages_per_huge_page)
5651 unsigned long addr = addr_hint &
5652 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5653 struct copy_subpage_arg arg = {
5659 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5660 copy_user_gigantic_page(dst, src, addr, vma,
5661 pages_per_huge_page);
5665 process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
5668 long copy_huge_page_from_user(struct page *dst_page,
5669 const void __user *usr_src,
5670 unsigned int pages_per_huge_page,
5671 bool allow_pagefault)
5674 unsigned long i, rc = 0;
5675 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
5676 struct page *subpage = dst_page;
5678 for (i = 0; i < pages_per_huge_page;
5679 i++, subpage = mem_map_next(subpage, dst_page, i)) {
5680 if (allow_pagefault)
5681 page_kaddr = kmap(subpage);
5683 page_kaddr = kmap_atomic(subpage);
5684 rc = copy_from_user(page_kaddr,
5685 usr_src + i * PAGE_SIZE, PAGE_SIZE);
5686 if (allow_pagefault)
5689 kunmap_atomic(page_kaddr);
5691 ret_val -= (PAGE_SIZE - rc);
5695 flush_dcache_page(subpage);
5701 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
5703 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
5705 static struct kmem_cache *page_ptl_cachep;
5707 void __init ptlock_cache_init(void)
5709 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
5713 bool ptlock_alloc(struct page *page)
5717 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
5724 void ptlock_free(struct page *page)
5726 kmem_cache_free(page_ptl_cachep, page->ptl);