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/kmsan.h>
56 #include <linux/ksm.h>
57 #include <linux/rmap.h>
58 #include <linux/export.h>
59 #include <linux/delayacct.h>
60 #include <linux/init.h>
61 #include <linux/pfn_t.h>
62 #include <linux/writeback.h>
63 #include <linux/memcontrol.h>
64 #include <linux/mmu_notifier.h>
65 #include <linux/swapops.h>
66 #include <linux/elf.h>
67 #include <linux/gfp.h>
68 #include <linux/migrate.h>
69 #include <linux/string.h>
70 #include <linux/memory-tiers.h>
71 #include <linux/debugfs.h>
72 #include <linux/userfaultfd_k.h>
73 #include <linux/dax.h>
74 #include <linux/oom.h>
75 #include <linux/numa.h>
76 #include <linux/perf_event.h>
77 #include <linux/ptrace.h>
78 #include <linux/vmalloc.h>
79 #include <linux/sched/sysctl.h>
81 #include <trace/events/kmem.h>
84 #include <asm/mmu_context.h>
85 #include <asm/pgalloc.h>
86 #include <linux/uaccess.h>
88 #include <asm/tlbflush.h>
90 #include "pgalloc-track.h"
94 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
95 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
99 unsigned long max_mapnr;
100 EXPORT_SYMBOL(max_mapnr);
102 struct page *mem_map;
103 EXPORT_SYMBOL(mem_map);
106 static vm_fault_t do_fault(struct vm_fault *vmf);
109 * A number of key systems in x86 including ioremap() rely on the assumption
110 * that high_memory defines the upper bound on direct map memory, then end
111 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and
112 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
116 EXPORT_SYMBOL(high_memory);
119 * Randomize the address space (stacks, mmaps, brk, etc.).
121 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
122 * as ancient (libc5 based) binaries can segfault. )
124 int randomize_va_space __read_mostly =
125 #ifdef CONFIG_COMPAT_BRK
131 #ifndef arch_wants_old_prefaulted_pte
132 static inline bool arch_wants_old_prefaulted_pte(void)
135 * Transitioning a PTE from 'old' to 'young' can be expensive on
136 * some architectures, even if it's performed in hardware. By
137 * default, "false" means prefaulted entries will be 'young'.
143 static int __init disable_randmaps(char *s)
145 randomize_va_space = 0;
148 __setup("norandmaps", disable_randmaps);
150 unsigned long zero_pfn __read_mostly;
151 EXPORT_SYMBOL(zero_pfn);
153 unsigned long highest_memmap_pfn __read_mostly;
156 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
158 static int __init init_zero_pfn(void)
160 zero_pfn = page_to_pfn(ZERO_PAGE(0));
163 early_initcall(init_zero_pfn);
165 void mm_trace_rss_stat(struct mm_struct *mm, int member, long count)
167 trace_rss_stat(mm, member, count);
170 #if defined(SPLIT_RSS_COUNTING)
172 void sync_mm_rss(struct mm_struct *mm)
176 for (i = 0; i < NR_MM_COUNTERS; i++) {
177 if (current->rss_stat.count[i]) {
178 add_mm_counter(mm, i, current->rss_stat.count[i]);
179 current->rss_stat.count[i] = 0;
182 current->rss_stat.events = 0;
185 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
187 struct task_struct *task = current;
189 if (likely(task->mm == mm))
190 task->rss_stat.count[member] += val;
192 add_mm_counter(mm, member, val);
194 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
195 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
197 /* sync counter once per 64 page faults */
198 #define TASK_RSS_EVENTS_THRESH (64)
199 static void check_sync_rss_stat(struct task_struct *task)
201 if (unlikely(task != current))
203 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
204 sync_mm_rss(task->mm);
206 #else /* SPLIT_RSS_COUNTING */
208 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
209 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
211 static void check_sync_rss_stat(struct task_struct *task)
215 #endif /* SPLIT_RSS_COUNTING */
218 * Note: this doesn't free the actual pages themselves. That
219 * has been handled earlier when unmapping all the memory regions.
221 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
224 pgtable_t token = pmd_pgtable(*pmd);
226 pte_free_tlb(tlb, token, addr);
227 mm_dec_nr_ptes(tlb->mm);
230 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
231 unsigned long addr, unsigned long end,
232 unsigned long floor, unsigned long ceiling)
239 pmd = pmd_offset(pud, addr);
241 next = pmd_addr_end(addr, end);
242 if (pmd_none_or_clear_bad(pmd))
244 free_pte_range(tlb, pmd, addr);
245 } while (pmd++, addr = next, addr != end);
255 if (end - 1 > ceiling - 1)
258 pmd = pmd_offset(pud, start);
260 pmd_free_tlb(tlb, pmd, start);
261 mm_dec_nr_pmds(tlb->mm);
264 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
265 unsigned long addr, unsigned long end,
266 unsigned long floor, unsigned long ceiling)
273 pud = pud_offset(p4d, addr);
275 next = pud_addr_end(addr, end);
276 if (pud_none_or_clear_bad(pud))
278 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
279 } while (pud++, addr = next, addr != end);
289 if (end - 1 > ceiling - 1)
292 pud = pud_offset(p4d, start);
294 pud_free_tlb(tlb, pud, start);
295 mm_dec_nr_puds(tlb->mm);
298 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
299 unsigned long addr, unsigned long end,
300 unsigned long floor, unsigned long ceiling)
307 p4d = p4d_offset(pgd, addr);
309 next = p4d_addr_end(addr, end);
310 if (p4d_none_or_clear_bad(p4d))
312 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
313 } while (p4d++, addr = next, addr != end);
319 ceiling &= PGDIR_MASK;
323 if (end - 1 > ceiling - 1)
326 p4d = p4d_offset(pgd, start);
328 p4d_free_tlb(tlb, p4d, start);
332 * This function frees user-level page tables of a process.
334 void free_pgd_range(struct mmu_gather *tlb,
335 unsigned long addr, unsigned long end,
336 unsigned long floor, unsigned long ceiling)
342 * The next few lines have given us lots of grief...
344 * Why are we testing PMD* at this top level? Because often
345 * there will be no work to do at all, and we'd prefer not to
346 * go all the way down to the bottom just to discover that.
348 * Why all these "- 1"s? Because 0 represents both the bottom
349 * of the address space and the top of it (using -1 for the
350 * top wouldn't help much: the masks would do the wrong thing).
351 * The rule is that addr 0 and floor 0 refer to the bottom of
352 * the address space, but end 0 and ceiling 0 refer to the top
353 * Comparisons need to use "end - 1" and "ceiling - 1" (though
354 * that end 0 case should be mythical).
356 * Wherever addr is brought up or ceiling brought down, we must
357 * be careful to reject "the opposite 0" before it confuses the
358 * subsequent tests. But what about where end is brought down
359 * by PMD_SIZE below? no, end can't go down to 0 there.
361 * Whereas we round start (addr) and ceiling down, by different
362 * masks at different levels, in order to test whether a table
363 * now has no other vmas using it, so can be freed, we don't
364 * bother to round floor or end up - the tests don't need that.
378 if (end - 1 > ceiling - 1)
383 * We add page table cache pages with PAGE_SIZE,
384 * (see pte_free_tlb()), flush the tlb if we need
386 tlb_change_page_size(tlb, PAGE_SIZE);
387 pgd = pgd_offset(tlb->mm, addr);
389 next = pgd_addr_end(addr, end);
390 if (pgd_none_or_clear_bad(pgd))
392 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
393 } while (pgd++, addr = next, addr != end);
396 void free_pgtables(struct mmu_gather *tlb, struct maple_tree *mt,
397 struct vm_area_struct *vma, unsigned long floor,
398 unsigned long ceiling)
400 MA_STATE(mas, mt, vma->vm_end, vma->vm_end);
403 unsigned long addr = vma->vm_start;
404 struct vm_area_struct *next;
407 * Note: USER_PGTABLES_CEILING may be passed as ceiling and may
408 * be 0. This will underflow and is okay.
410 next = mas_find(&mas, ceiling - 1);
413 * Hide vma from rmap and truncate_pagecache before freeing
416 unlink_anon_vmas(vma);
417 unlink_file_vma(vma);
419 if (is_vm_hugetlb_page(vma)) {
420 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
421 floor, next ? next->vm_start : ceiling);
424 * Optimization: gather nearby vmas into one call down
426 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
427 && !is_vm_hugetlb_page(next)) {
429 next = mas_find(&mas, ceiling - 1);
430 unlink_anon_vmas(vma);
431 unlink_file_vma(vma);
433 free_pgd_range(tlb, addr, vma->vm_end,
434 floor, next ? next->vm_start : ceiling);
440 void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte)
442 spinlock_t *ptl = pmd_lock(mm, pmd);
444 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
447 * Ensure all pte setup (eg. pte page lock and page clearing) are
448 * visible before the pte is made visible to other CPUs by being
449 * put into page tables.
451 * The other side of the story is the pointer chasing in the page
452 * table walking code (when walking the page table without locking;
453 * ie. most of the time). Fortunately, these data accesses consist
454 * of a chain of data-dependent loads, meaning most CPUs (alpha
455 * being the notable exception) will already guarantee loads are
456 * seen in-order. See the alpha page table accessors for the
457 * smp_rmb() barriers in page table walking code.
459 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
460 pmd_populate(mm, pmd, *pte);
466 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
468 pgtable_t new = pte_alloc_one(mm);
472 pmd_install(mm, pmd, &new);
478 int __pte_alloc_kernel(pmd_t *pmd)
480 pte_t *new = pte_alloc_one_kernel(&init_mm);
484 spin_lock(&init_mm.page_table_lock);
485 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
486 smp_wmb(); /* See comment in pmd_install() */
487 pmd_populate_kernel(&init_mm, pmd, new);
490 spin_unlock(&init_mm.page_table_lock);
492 pte_free_kernel(&init_mm, new);
496 static inline void init_rss_vec(int *rss)
498 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
501 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
505 if (current->mm == mm)
507 for (i = 0; i < NR_MM_COUNTERS; i++)
509 add_mm_counter(mm, i, rss[i]);
513 * This function is called to print an error when a bad pte
514 * is found. For example, we might have a PFN-mapped pte in
515 * a region that doesn't allow it.
517 * The calling function must still handle the error.
519 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
520 pte_t pte, struct page *page)
522 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
523 p4d_t *p4d = p4d_offset(pgd, addr);
524 pud_t *pud = pud_offset(p4d, addr);
525 pmd_t *pmd = pmd_offset(pud, addr);
526 struct address_space *mapping;
528 static unsigned long resume;
529 static unsigned long nr_shown;
530 static unsigned long nr_unshown;
533 * Allow a burst of 60 reports, then keep quiet for that minute;
534 * or allow a steady drip of one report per second.
536 if (nr_shown == 60) {
537 if (time_before(jiffies, resume)) {
542 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
549 resume = jiffies + 60 * HZ;
551 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
552 index = linear_page_index(vma, addr);
554 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
556 (long long)pte_val(pte), (long long)pmd_val(*pmd));
558 dump_page(page, "bad pte");
559 pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n",
560 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
561 pr_alert("file:%pD fault:%ps mmap:%ps read_folio:%ps\n",
563 vma->vm_ops ? vma->vm_ops->fault : NULL,
564 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
565 mapping ? mapping->a_ops->read_folio : NULL);
567 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
571 * vm_normal_page -- This function gets the "struct page" associated with a pte.
573 * "Special" mappings do not wish to be associated with a "struct page" (either
574 * it doesn't exist, or it exists but they don't want to touch it). In this
575 * case, NULL is returned here. "Normal" mappings do have a struct page.
577 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
578 * pte bit, in which case this function is trivial. Secondly, an architecture
579 * may not have a spare pte bit, which requires a more complicated scheme,
582 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
583 * special mapping (even if there are underlying and valid "struct pages").
584 * COWed pages of a VM_PFNMAP are always normal.
586 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
587 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
588 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
589 * mapping will always honor the rule
591 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
593 * And for normal mappings this is false.
595 * This restricts such mappings to be a linear translation from virtual address
596 * to pfn. To get around this restriction, we allow arbitrary mappings so long
597 * as the vma is not a COW mapping; in that case, we know that all ptes are
598 * special (because none can have been COWed).
601 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
603 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
604 * page" backing, however the difference is that _all_ pages with a struct
605 * page (that is, those where pfn_valid is true) are refcounted and considered
606 * normal pages by the VM. The disadvantage is that pages are refcounted
607 * (which can be slower and simply not an option for some PFNMAP users). The
608 * advantage is that we don't have to follow the strict linearity rule of
609 * PFNMAP mappings in order to support COWable mappings.
612 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
615 unsigned long pfn = pte_pfn(pte);
617 if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
618 if (likely(!pte_special(pte)))
620 if (vma->vm_ops && vma->vm_ops->find_special_page)
621 return vma->vm_ops->find_special_page(vma, addr);
622 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
624 if (is_zero_pfn(pfn))
628 * NOTE: New users of ZONE_DEVICE will not set pte_devmap()
629 * and will have refcounts incremented on their struct pages
630 * when they are inserted into PTEs, thus they are safe to
631 * return here. Legacy ZONE_DEVICE pages that set pte_devmap()
632 * do not have refcounts. Example of legacy ZONE_DEVICE is
633 * MEMORY_DEVICE_FS_DAX type in pmem or virtio_fs drivers.
637 print_bad_pte(vma, addr, pte, NULL);
641 /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
643 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
644 if (vma->vm_flags & VM_MIXEDMAP) {
650 off = (addr - vma->vm_start) >> PAGE_SHIFT;
651 if (pfn == vma->vm_pgoff + off)
653 if (!is_cow_mapping(vma->vm_flags))
658 if (is_zero_pfn(pfn))
662 if (unlikely(pfn > highest_memmap_pfn)) {
663 print_bad_pte(vma, addr, pte, NULL);
668 * NOTE! We still have PageReserved() pages in the page tables.
669 * eg. VDSO mappings can cause them to exist.
672 return pfn_to_page(pfn);
675 struct folio *vm_normal_folio(struct vm_area_struct *vma, unsigned long addr,
678 struct page *page = vm_normal_page(vma, addr, pte);
681 return page_folio(page);
685 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
686 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
689 unsigned long pfn = pmd_pfn(pmd);
692 * There is no pmd_special() but there may be special pmds, e.g.
693 * in a direct-access (dax) mapping, so let's just replicate the
694 * !CONFIG_ARCH_HAS_PTE_SPECIAL case from vm_normal_page() here.
696 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
697 if (vma->vm_flags & VM_MIXEDMAP) {
703 off = (addr - vma->vm_start) >> PAGE_SHIFT;
704 if (pfn == vma->vm_pgoff + off)
706 if (!is_cow_mapping(vma->vm_flags))
713 if (is_huge_zero_pmd(pmd))
715 if (unlikely(pfn > highest_memmap_pfn))
719 * NOTE! We still have PageReserved() pages in the page tables.
720 * eg. VDSO mappings can cause them to exist.
723 return pfn_to_page(pfn);
727 static void restore_exclusive_pte(struct vm_area_struct *vma,
728 struct page *page, unsigned long address,
734 pte = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot)));
735 if (pte_swp_soft_dirty(*ptep))
736 pte = pte_mksoft_dirty(pte);
738 entry = pte_to_swp_entry(*ptep);
739 if (pte_swp_uffd_wp(*ptep))
740 pte = pte_mkuffd_wp(pte);
741 else if (is_writable_device_exclusive_entry(entry))
742 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
744 VM_BUG_ON(pte_write(pte) && !(PageAnon(page) && PageAnonExclusive(page)));
747 * No need to take a page reference as one was already
748 * created when the swap entry was made.
751 page_add_anon_rmap(page, vma, address, RMAP_NONE);
754 * Currently device exclusive access only supports anonymous
755 * memory so the entry shouldn't point to a filebacked page.
759 set_pte_at(vma->vm_mm, address, ptep, pte);
762 * No need to invalidate - it was non-present before. However
763 * secondary CPUs may have mappings that need invalidating.
765 update_mmu_cache(vma, address, ptep);
769 * Tries to restore an exclusive pte if the page lock can be acquired without
773 try_restore_exclusive_pte(pte_t *src_pte, struct vm_area_struct *vma,
776 swp_entry_t entry = pte_to_swp_entry(*src_pte);
777 struct page *page = pfn_swap_entry_to_page(entry);
779 if (trylock_page(page)) {
780 restore_exclusive_pte(vma, page, addr, src_pte);
789 * copy one vm_area from one task to the other. Assumes the page tables
790 * already present in the new task to be cleared in the whole range
791 * covered by this vma.
795 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
796 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *dst_vma,
797 struct vm_area_struct *src_vma, unsigned long addr, int *rss)
799 unsigned long vm_flags = dst_vma->vm_flags;
800 pte_t pte = *src_pte;
802 swp_entry_t entry = pte_to_swp_entry(pte);
804 if (likely(!non_swap_entry(entry))) {
805 if (swap_duplicate(entry) < 0)
808 /* make sure dst_mm is on swapoff's mmlist. */
809 if (unlikely(list_empty(&dst_mm->mmlist))) {
810 spin_lock(&mmlist_lock);
811 if (list_empty(&dst_mm->mmlist))
812 list_add(&dst_mm->mmlist,
814 spin_unlock(&mmlist_lock);
816 /* Mark the swap entry as shared. */
817 if (pte_swp_exclusive(*src_pte)) {
818 pte = pte_swp_clear_exclusive(*src_pte);
819 set_pte_at(src_mm, addr, src_pte, pte);
822 } else if (is_migration_entry(entry)) {
823 page = pfn_swap_entry_to_page(entry);
825 rss[mm_counter(page)]++;
827 if (!is_readable_migration_entry(entry) &&
828 is_cow_mapping(vm_flags)) {
830 * COW mappings require pages in both parent and child
831 * to be set to read. A previously exclusive entry is
834 entry = make_readable_migration_entry(
836 pte = swp_entry_to_pte(entry);
837 if (pte_swp_soft_dirty(*src_pte))
838 pte = pte_swp_mksoft_dirty(pte);
839 if (pte_swp_uffd_wp(*src_pte))
840 pte = pte_swp_mkuffd_wp(pte);
841 set_pte_at(src_mm, addr, src_pte, pte);
843 } else if (is_device_private_entry(entry)) {
844 page = pfn_swap_entry_to_page(entry);
847 * Update rss count even for unaddressable pages, as
848 * they should treated just like normal pages in this
851 * We will likely want to have some new rss counters
852 * for unaddressable pages, at some point. But for now
853 * keep things as they are.
856 rss[mm_counter(page)]++;
857 /* Cannot fail as these pages cannot get pinned. */
858 BUG_ON(page_try_dup_anon_rmap(page, false, src_vma));
861 * We do not preserve soft-dirty information, because so
862 * far, checkpoint/restore is the only feature that
863 * requires that. And checkpoint/restore does not work
864 * when a device driver is involved (you cannot easily
865 * save and restore device driver state).
867 if (is_writable_device_private_entry(entry) &&
868 is_cow_mapping(vm_flags)) {
869 entry = make_readable_device_private_entry(
871 pte = swp_entry_to_pte(entry);
872 if (pte_swp_uffd_wp(*src_pte))
873 pte = pte_swp_mkuffd_wp(pte);
874 set_pte_at(src_mm, addr, src_pte, pte);
876 } else if (is_device_exclusive_entry(entry)) {
878 * Make device exclusive entries present by restoring the
879 * original entry then copying as for a present pte. Device
880 * exclusive entries currently only support private writable
881 * (ie. COW) mappings.
883 VM_BUG_ON(!is_cow_mapping(src_vma->vm_flags));
884 if (try_restore_exclusive_pte(src_pte, src_vma, addr))
887 } else if (is_pte_marker_entry(entry)) {
888 if (userfaultfd_wp(dst_vma))
889 set_pte_at(dst_mm, addr, dst_pte, pte);
892 if (!userfaultfd_wp(dst_vma))
893 pte = pte_swp_clear_uffd_wp(pte);
894 set_pte_at(dst_mm, addr, dst_pte, pte);
899 * Copy a present and normal page.
901 * NOTE! The usual case is that this isn't required;
902 * instead, the caller can just increase the page refcount
903 * and re-use the pte the traditional way.
905 * And if we need a pre-allocated page but don't yet have
906 * one, return a negative error to let the preallocation
907 * code know so that it can do so outside the page table
911 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
912 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
913 struct page **prealloc, struct page *page)
915 struct page *new_page;
918 new_page = *prealloc;
923 * We have a prealloc page, all good! Take it
924 * over and copy the page & arm it.
927 copy_user_highpage(new_page, page, addr, src_vma);
928 __SetPageUptodate(new_page);
929 page_add_new_anon_rmap(new_page, dst_vma, addr);
930 lru_cache_add_inactive_or_unevictable(new_page, dst_vma);
931 rss[mm_counter(new_page)]++;
933 /* All done, just insert the new page copy in the child */
934 pte = mk_pte(new_page, dst_vma->vm_page_prot);
935 pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
936 if (userfaultfd_pte_wp(dst_vma, *src_pte))
937 /* Uffd-wp needs to be delivered to dest pte as well */
938 pte = pte_wrprotect(pte_mkuffd_wp(pte));
939 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
944 * Copy one pte. Returns 0 if succeeded, or -EAGAIN if one preallocated page
945 * is required to copy this pte.
948 copy_present_pte(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
949 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
950 struct page **prealloc)
952 struct mm_struct *src_mm = src_vma->vm_mm;
953 unsigned long vm_flags = src_vma->vm_flags;
954 pte_t pte = *src_pte;
957 page = vm_normal_page(src_vma, addr, pte);
958 if (page && PageAnon(page)) {
960 * If this page may have been pinned by the parent process,
961 * copy the page immediately for the child so that we'll always
962 * guarantee the pinned page won't be randomly replaced in the
966 if (unlikely(page_try_dup_anon_rmap(page, false, src_vma))) {
967 /* Page maybe pinned, we have to copy. */
969 return copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
970 addr, rss, prealloc, page);
972 rss[mm_counter(page)]++;
975 page_dup_file_rmap(page, false);
976 rss[mm_counter(page)]++;
980 * If it's a COW mapping, write protect it both
981 * in the parent and the child
983 if (is_cow_mapping(vm_flags) && pte_write(pte)) {
984 ptep_set_wrprotect(src_mm, addr, src_pte);
985 pte = pte_wrprotect(pte);
987 VM_BUG_ON(page && PageAnon(page) && PageAnonExclusive(page));
990 * If it's a shared mapping, mark it clean in
993 if (vm_flags & VM_SHARED)
994 pte = pte_mkclean(pte);
995 pte = pte_mkold(pte);
997 if (!userfaultfd_wp(dst_vma))
998 pte = pte_clear_uffd_wp(pte);
1000 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
1004 static inline struct page *
1005 page_copy_prealloc(struct mm_struct *src_mm, struct vm_area_struct *vma,
1008 struct page *new_page;
1010 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, addr);
1014 if (mem_cgroup_charge(page_folio(new_page), src_mm, GFP_KERNEL)) {
1018 cgroup_throttle_swaprate(new_page, GFP_KERNEL);
1024 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1025 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1028 struct mm_struct *dst_mm = dst_vma->vm_mm;
1029 struct mm_struct *src_mm = src_vma->vm_mm;
1030 pte_t *orig_src_pte, *orig_dst_pte;
1031 pte_t *src_pte, *dst_pte;
1032 spinlock_t *src_ptl, *dst_ptl;
1033 int progress, ret = 0;
1034 int rss[NR_MM_COUNTERS];
1035 swp_entry_t entry = (swp_entry_t){0};
1036 struct page *prealloc = NULL;
1042 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
1047 src_pte = pte_offset_map(src_pmd, addr);
1048 src_ptl = pte_lockptr(src_mm, src_pmd);
1049 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1050 orig_src_pte = src_pte;
1051 orig_dst_pte = dst_pte;
1052 arch_enter_lazy_mmu_mode();
1056 * We are holding two locks at this point - either of them
1057 * could generate latencies in another task on another CPU.
1059 if (progress >= 32) {
1061 if (need_resched() ||
1062 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
1065 if (pte_none(*src_pte)) {
1069 if (unlikely(!pte_present(*src_pte))) {
1070 ret = copy_nonpresent_pte(dst_mm, src_mm,
1075 entry = pte_to_swp_entry(*src_pte);
1077 } else if (ret == -EBUSY) {
1085 * Device exclusive entry restored, continue by copying
1086 * the now present pte.
1088 WARN_ON_ONCE(ret != -ENOENT);
1090 /* copy_present_pte() will clear `*prealloc' if consumed */
1091 ret = copy_present_pte(dst_vma, src_vma, dst_pte, src_pte,
1092 addr, rss, &prealloc);
1094 * If we need a pre-allocated page for this pte, drop the
1095 * locks, allocate, and try again.
1097 if (unlikely(ret == -EAGAIN))
1099 if (unlikely(prealloc)) {
1101 * pre-alloc page cannot be reused by next time so as
1102 * to strictly follow mempolicy (e.g., alloc_page_vma()
1103 * will allocate page according to address). This
1104 * could only happen if one pinned pte changed.
1110 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
1112 arch_leave_lazy_mmu_mode();
1113 spin_unlock(src_ptl);
1114 pte_unmap(orig_src_pte);
1115 add_mm_rss_vec(dst_mm, rss);
1116 pte_unmap_unlock(orig_dst_pte, dst_ptl);
1120 VM_WARN_ON_ONCE(!entry.val);
1121 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
1126 } else if (ret == -EBUSY) {
1128 } else if (ret == -EAGAIN) {
1129 prealloc = page_copy_prealloc(src_mm, src_vma, addr);
1136 /* We've captured and resolved the error. Reset, try again. */
1142 if (unlikely(prealloc))
1148 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1149 pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1152 struct mm_struct *dst_mm = dst_vma->vm_mm;
1153 struct mm_struct *src_mm = src_vma->vm_mm;
1154 pmd_t *src_pmd, *dst_pmd;
1157 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1160 src_pmd = pmd_offset(src_pud, addr);
1162 next = pmd_addr_end(addr, end);
1163 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1164 || pmd_devmap(*src_pmd)) {
1166 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
1167 err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd,
1168 addr, dst_vma, src_vma);
1175 if (pmd_none_or_clear_bad(src_pmd))
1177 if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
1180 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1185 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1186 p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
1189 struct mm_struct *dst_mm = dst_vma->vm_mm;
1190 struct mm_struct *src_mm = src_vma->vm_mm;
1191 pud_t *src_pud, *dst_pud;
1194 dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1197 src_pud = pud_offset(src_p4d, addr);
1199 next = pud_addr_end(addr, end);
1200 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1203 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
1204 err = copy_huge_pud(dst_mm, src_mm,
1205 dst_pud, src_pud, addr, src_vma);
1212 if (pud_none_or_clear_bad(src_pud))
1214 if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
1217 } while (dst_pud++, src_pud++, addr = next, addr != end);
1222 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1223 pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
1226 struct mm_struct *dst_mm = dst_vma->vm_mm;
1227 p4d_t *src_p4d, *dst_p4d;
1230 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1233 src_p4d = p4d_offset(src_pgd, addr);
1235 next = p4d_addr_end(addr, end);
1236 if (p4d_none_or_clear_bad(src_p4d))
1238 if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
1241 } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1246 * Return true if the vma needs to copy the pgtable during this fork(). Return
1247 * false when we can speed up fork() by allowing lazy page faults later until
1248 * when the child accesses the memory range.
1251 vma_needs_copy(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1254 * Always copy pgtables when dst_vma has uffd-wp enabled even if it's
1255 * file-backed (e.g. shmem). Because when uffd-wp is enabled, pgtable
1256 * contains uffd-wp protection information, that's something we can't
1257 * retrieve from page cache, and skip copying will lose those info.
1259 if (userfaultfd_wp(dst_vma))
1262 if (src_vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
1265 if (src_vma->anon_vma)
1269 * Don't copy ptes where a page fault will fill them correctly. Fork
1270 * becomes much lighter when there are big shared or private readonly
1271 * mappings. The tradeoff is that copy_page_range is more efficient
1278 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1280 pgd_t *src_pgd, *dst_pgd;
1282 unsigned long addr = src_vma->vm_start;
1283 unsigned long end = src_vma->vm_end;
1284 struct mm_struct *dst_mm = dst_vma->vm_mm;
1285 struct mm_struct *src_mm = src_vma->vm_mm;
1286 struct mmu_notifier_range range;
1290 if (!vma_needs_copy(dst_vma, src_vma))
1293 if (is_vm_hugetlb_page(src_vma))
1294 return copy_hugetlb_page_range(dst_mm, src_mm, dst_vma, src_vma);
1296 if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
1298 * We do not free on error cases below as remove_vma
1299 * gets called on error from higher level routine
1301 ret = track_pfn_copy(src_vma);
1307 * We need to invalidate the secondary MMU mappings only when
1308 * there could be a permission downgrade on the ptes of the
1309 * parent mm. And a permission downgrade will only happen if
1310 * is_cow_mapping() returns true.
1312 is_cow = is_cow_mapping(src_vma->vm_flags);
1315 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
1316 0, src_vma, src_mm, addr, end);
1317 mmu_notifier_invalidate_range_start(&range);
1319 * Disabling preemption is not needed for the write side, as
1320 * the read side doesn't spin, but goes to the mmap_lock.
1322 * Use the raw variant of the seqcount_t write API to avoid
1323 * lockdep complaining about preemptibility.
1325 mmap_assert_write_locked(src_mm);
1326 raw_write_seqcount_begin(&src_mm->write_protect_seq);
1330 dst_pgd = pgd_offset(dst_mm, addr);
1331 src_pgd = pgd_offset(src_mm, addr);
1333 next = pgd_addr_end(addr, end);
1334 if (pgd_none_or_clear_bad(src_pgd))
1336 if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
1341 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1344 raw_write_seqcount_end(&src_mm->write_protect_seq);
1345 mmu_notifier_invalidate_range_end(&range);
1350 /* Whether we should zap all COWed (private) pages too */
1351 static inline bool should_zap_cows(struct zap_details *details)
1353 /* By default, zap all pages */
1357 /* Or, we zap COWed pages only if the caller wants to */
1358 return details->even_cows;
1361 /* Decides whether we should zap this page with the page pointer specified */
1362 static inline bool should_zap_page(struct zap_details *details, struct page *page)
1364 /* If we can make a decision without *page.. */
1365 if (should_zap_cows(details))
1368 /* E.g. the caller passes NULL for the case of a zero page */
1372 /* Otherwise we should only zap non-anon pages */
1373 return !PageAnon(page);
1376 static inline bool zap_drop_file_uffd_wp(struct zap_details *details)
1381 return details->zap_flags & ZAP_FLAG_DROP_MARKER;
1385 * This function makes sure that we'll replace the none pte with an uffd-wp
1386 * swap special pte marker when necessary. Must be with the pgtable lock held.
1389 zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
1390 unsigned long addr, pte_t *pte,
1391 struct zap_details *details, pte_t pteval)
1393 #ifdef CONFIG_PTE_MARKER_UFFD_WP
1394 if (zap_drop_file_uffd_wp(details))
1397 pte_install_uffd_wp_if_needed(vma, addr, pte, pteval);
1401 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1402 struct vm_area_struct *vma, pmd_t *pmd,
1403 unsigned long addr, unsigned long end,
1404 struct zap_details *details)
1406 struct mm_struct *mm = tlb->mm;
1407 int force_flush = 0;
1408 int rss[NR_MM_COUNTERS];
1414 tlb_change_page_size(tlb, PAGE_SIZE);
1417 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1419 flush_tlb_batched_pending(mm);
1420 arch_enter_lazy_mmu_mode();
1425 if (pte_none(ptent))
1431 if (pte_present(ptent)) {
1432 page = vm_normal_page(vma, addr, ptent);
1433 if (unlikely(!should_zap_page(details, page)))
1435 ptent = ptep_get_and_clear_full(mm, addr, pte,
1437 tlb_remove_tlb_entry(tlb, pte, addr);
1438 zap_install_uffd_wp_if_needed(vma, addr, pte, details,
1440 if (unlikely(!page))
1443 if (!PageAnon(page)) {
1444 if (pte_dirty(ptent)) {
1446 set_page_dirty(page);
1448 if (pte_young(ptent) &&
1449 likely(!(vma->vm_flags & VM_SEQ_READ)))
1450 mark_page_accessed(page);
1452 rss[mm_counter(page)]--;
1453 page_remove_rmap(page, vma, false);
1454 if (unlikely(page_mapcount(page) < 0))
1455 print_bad_pte(vma, addr, ptent, page);
1456 if (unlikely(__tlb_remove_page(tlb, page))) {
1464 entry = pte_to_swp_entry(ptent);
1465 if (is_device_private_entry(entry) ||
1466 is_device_exclusive_entry(entry)) {
1467 page = pfn_swap_entry_to_page(entry);
1468 if (unlikely(!should_zap_page(details, page)))
1471 * Both device private/exclusive mappings should only
1472 * work with anonymous page so far, so we don't need to
1473 * consider uffd-wp bit when zap. For more information,
1474 * see zap_install_uffd_wp_if_needed().
1476 WARN_ON_ONCE(!vma_is_anonymous(vma));
1477 rss[mm_counter(page)]--;
1478 if (is_device_private_entry(entry))
1479 page_remove_rmap(page, vma, false);
1481 } else if (!non_swap_entry(entry)) {
1482 /* Genuine swap entry, hence a private anon page */
1483 if (!should_zap_cows(details))
1486 if (unlikely(!free_swap_and_cache(entry)))
1487 print_bad_pte(vma, addr, ptent, NULL);
1488 } else if (is_migration_entry(entry)) {
1489 page = pfn_swap_entry_to_page(entry);
1490 if (!should_zap_page(details, page))
1492 rss[mm_counter(page)]--;
1493 } else if (pte_marker_entry_uffd_wp(entry)) {
1494 /* Only drop the uffd-wp marker if explicitly requested */
1495 if (!zap_drop_file_uffd_wp(details))
1497 } else if (is_hwpoison_entry(entry) ||
1498 is_swapin_error_entry(entry)) {
1499 if (!should_zap_cows(details))
1502 /* We should have covered all the swap entry types */
1505 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1506 zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
1507 } while (pte++, addr += PAGE_SIZE, addr != end);
1509 add_mm_rss_vec(mm, rss);
1510 arch_leave_lazy_mmu_mode();
1512 /* Do the actual TLB flush before dropping ptl */
1514 tlb_flush_mmu_tlbonly(tlb);
1515 pte_unmap_unlock(start_pte, ptl);
1518 * If we forced a TLB flush (either due to running out of
1519 * batch buffers or because we needed to flush dirty TLB
1520 * entries before releasing the ptl), free the batched
1521 * memory too. Restart if we didn't do everything.
1536 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1537 struct vm_area_struct *vma, pud_t *pud,
1538 unsigned long addr, unsigned long end,
1539 struct zap_details *details)
1544 pmd = pmd_offset(pud, addr);
1546 next = pmd_addr_end(addr, end);
1547 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1548 if (next - addr != HPAGE_PMD_SIZE)
1549 __split_huge_pmd(vma, pmd, addr, false, NULL);
1550 else if (zap_huge_pmd(tlb, vma, pmd, addr))
1553 } else if (details && details->single_folio &&
1554 folio_test_pmd_mappable(details->single_folio) &&
1555 next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) {
1556 spinlock_t *ptl = pmd_lock(tlb->mm, pmd);
1558 * Take and drop THP pmd lock so that we cannot return
1559 * prematurely, while zap_huge_pmd() has cleared *pmd,
1560 * but not yet decremented compound_mapcount().
1566 * Here there can be other concurrent MADV_DONTNEED or
1567 * trans huge page faults running, and if the pmd is
1568 * none or trans huge it can change under us. This is
1569 * because MADV_DONTNEED holds the mmap_lock in read
1572 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1574 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1577 } while (pmd++, addr = next, addr != end);
1582 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1583 struct vm_area_struct *vma, p4d_t *p4d,
1584 unsigned long addr, unsigned long end,
1585 struct zap_details *details)
1590 pud = pud_offset(p4d, addr);
1592 next = pud_addr_end(addr, end);
1593 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1594 if (next - addr != HPAGE_PUD_SIZE) {
1595 mmap_assert_locked(tlb->mm);
1596 split_huge_pud(vma, pud, addr);
1597 } else if (zap_huge_pud(tlb, vma, pud, addr))
1601 if (pud_none_or_clear_bad(pud))
1603 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1606 } while (pud++, addr = next, addr != end);
1611 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1612 struct vm_area_struct *vma, pgd_t *pgd,
1613 unsigned long addr, unsigned long end,
1614 struct zap_details *details)
1619 p4d = p4d_offset(pgd, addr);
1621 next = p4d_addr_end(addr, end);
1622 if (p4d_none_or_clear_bad(p4d))
1624 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1625 } while (p4d++, addr = next, addr != end);
1630 void unmap_page_range(struct mmu_gather *tlb,
1631 struct vm_area_struct *vma,
1632 unsigned long addr, unsigned long end,
1633 struct zap_details *details)
1638 BUG_ON(addr >= end);
1639 tlb_start_vma(tlb, vma);
1640 pgd = pgd_offset(vma->vm_mm, addr);
1642 next = pgd_addr_end(addr, end);
1643 if (pgd_none_or_clear_bad(pgd))
1645 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1646 } while (pgd++, addr = next, addr != end);
1647 tlb_end_vma(tlb, vma);
1651 static void unmap_single_vma(struct mmu_gather *tlb,
1652 struct vm_area_struct *vma, unsigned long start_addr,
1653 unsigned long end_addr,
1654 struct zap_details *details)
1656 unsigned long start = max(vma->vm_start, start_addr);
1659 if (start >= vma->vm_end)
1661 end = min(vma->vm_end, end_addr);
1662 if (end <= vma->vm_start)
1666 uprobe_munmap(vma, start, end);
1668 if (unlikely(vma->vm_flags & VM_PFNMAP))
1669 untrack_pfn(vma, 0, 0);
1672 if (unlikely(is_vm_hugetlb_page(vma))) {
1674 * It is undesirable to test vma->vm_file as it
1675 * should be non-null for valid hugetlb area.
1676 * However, vm_file will be NULL in the error
1677 * cleanup path of mmap_region. When
1678 * hugetlbfs ->mmap method fails,
1679 * mmap_region() nullifies vma->vm_file
1680 * before calling this function to clean up.
1681 * Since no pte has actually been setup, it is
1682 * safe to do nothing in this case.
1685 zap_flags_t zap_flags = details ?
1686 details->zap_flags : 0;
1687 __unmap_hugepage_range_final(tlb, vma, start, end,
1691 unmap_page_range(tlb, vma, start, end, details);
1696 * unmap_vmas - unmap a range of memory covered by a list of vma's
1697 * @tlb: address of the caller's struct mmu_gather
1698 * @mt: the maple tree
1699 * @vma: the starting vma
1700 * @start_addr: virtual address at which to start unmapping
1701 * @end_addr: virtual address at which to end unmapping
1703 * Unmap all pages in the vma list.
1705 * Only addresses between `start' and `end' will be unmapped.
1707 * The VMA list must be sorted in ascending virtual address order.
1709 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1710 * range after unmap_vmas() returns. So the only responsibility here is to
1711 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1712 * drops the lock and schedules.
1714 void unmap_vmas(struct mmu_gather *tlb, struct maple_tree *mt,
1715 struct vm_area_struct *vma, unsigned long start_addr,
1716 unsigned long end_addr)
1718 struct mmu_notifier_range range;
1719 struct zap_details details = {
1720 .zap_flags = ZAP_FLAG_DROP_MARKER | ZAP_FLAG_UNMAP,
1721 /* Careful - we need to zap private pages too! */
1724 MA_STATE(mas, mt, vma->vm_end, vma->vm_end);
1726 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
1727 start_addr, end_addr);
1728 mmu_notifier_invalidate_range_start(&range);
1730 unmap_single_vma(tlb, vma, start_addr, end_addr, &details);
1731 } while ((vma = mas_find(&mas, end_addr - 1)) != NULL);
1732 mmu_notifier_invalidate_range_end(&range);
1736 * zap_page_range - remove user pages in a given range
1737 * @vma: vm_area_struct holding the applicable pages
1738 * @start: starting address of pages to zap
1739 * @size: number of bytes to zap
1741 * Caller must protect the VMA list
1743 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1746 struct maple_tree *mt = &vma->vm_mm->mm_mt;
1747 unsigned long end = start + size;
1748 struct mmu_notifier_range range;
1749 struct mmu_gather tlb;
1750 MA_STATE(mas, mt, vma->vm_end, vma->vm_end);
1753 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1754 start, start + size);
1755 tlb_gather_mmu(&tlb, vma->vm_mm);
1756 update_hiwater_rss(vma->vm_mm);
1757 mmu_notifier_invalidate_range_start(&range);
1759 unmap_single_vma(&tlb, vma, start, range.end, NULL);
1760 } while ((vma = mas_find(&mas, end - 1)) != NULL);
1761 mmu_notifier_invalidate_range_end(&range);
1762 tlb_finish_mmu(&tlb);
1766 * zap_page_range_single - remove user pages in a given range
1767 * @vma: vm_area_struct holding the applicable pages
1768 * @address: starting address of pages to zap
1769 * @size: number of bytes to zap
1770 * @details: details of shared cache invalidation
1772 * The range must fit into one VMA.
1774 void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1775 unsigned long size, struct zap_details *details)
1777 const unsigned long end = address + size;
1778 struct mmu_notifier_range range;
1779 struct mmu_gather tlb;
1782 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1784 if (is_vm_hugetlb_page(vma))
1785 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1787 tlb_gather_mmu(&tlb, vma->vm_mm);
1788 update_hiwater_rss(vma->vm_mm);
1789 mmu_notifier_invalidate_range_start(&range);
1791 * unmap 'address-end' not 'range.start-range.end' as range
1792 * could have been expanded for hugetlb pmd sharing.
1794 unmap_single_vma(&tlb, vma, address, end, details);
1795 mmu_notifier_invalidate_range_end(&range);
1796 tlb_finish_mmu(&tlb);
1800 * zap_vma_ptes - remove ptes mapping the vma
1801 * @vma: vm_area_struct holding ptes to be zapped
1802 * @address: starting address of pages to zap
1803 * @size: number of bytes to zap
1805 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1807 * The entire address range must be fully contained within the vma.
1810 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1813 if (!range_in_vma(vma, address, address + size) ||
1814 !(vma->vm_flags & VM_PFNMAP))
1817 zap_page_range_single(vma, address, size, NULL);
1819 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1821 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
1828 pgd = pgd_offset(mm, addr);
1829 p4d = p4d_alloc(mm, pgd, addr);
1832 pud = pud_alloc(mm, p4d, addr);
1835 pmd = pmd_alloc(mm, pud, addr);
1839 VM_BUG_ON(pmd_trans_huge(*pmd));
1843 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1846 pmd_t *pmd = walk_to_pmd(mm, addr);
1850 return pte_alloc_map_lock(mm, pmd, addr, ptl);
1853 static int validate_page_before_insert(struct page *page)
1855 if (PageAnon(page) || PageSlab(page) || page_has_type(page))
1857 flush_dcache_page(page);
1861 static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
1862 unsigned long addr, struct page *page, pgprot_t prot)
1864 if (!pte_none(*pte))
1866 /* Ok, finally just insert the thing.. */
1868 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
1869 page_add_file_rmap(page, vma, false);
1870 set_pte_at(vma->vm_mm, addr, pte, mk_pte(page, prot));
1875 * This is the old fallback for page remapping.
1877 * For historical reasons, it only allows reserved pages. Only
1878 * old drivers should use this, and they needed to mark their
1879 * pages reserved for the old functions anyway.
1881 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1882 struct page *page, pgprot_t prot)
1888 retval = validate_page_before_insert(page);
1892 pte = get_locked_pte(vma->vm_mm, addr, &ptl);
1895 retval = insert_page_into_pte_locked(vma, pte, addr, page, prot);
1896 pte_unmap_unlock(pte, ptl);
1902 static int insert_page_in_batch_locked(struct vm_area_struct *vma, pte_t *pte,
1903 unsigned long addr, struct page *page, pgprot_t prot)
1907 if (!page_count(page))
1909 err = validate_page_before_insert(page);
1912 return insert_page_into_pte_locked(vma, pte, addr, page, prot);
1915 /* insert_pages() amortizes the cost of spinlock operations
1916 * when inserting pages in a loop. Arch *must* define pte_index.
1918 static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
1919 struct page **pages, unsigned long *num, pgprot_t prot)
1922 pte_t *start_pte, *pte;
1923 spinlock_t *pte_lock;
1924 struct mm_struct *const mm = vma->vm_mm;
1925 unsigned long curr_page_idx = 0;
1926 unsigned long remaining_pages_total = *num;
1927 unsigned long pages_to_write_in_pmd;
1931 pmd = walk_to_pmd(mm, addr);
1935 pages_to_write_in_pmd = min_t(unsigned long,
1936 remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
1938 /* Allocate the PTE if necessary; takes PMD lock once only. */
1940 if (pte_alloc(mm, pmd))
1943 while (pages_to_write_in_pmd) {
1945 const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
1947 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
1948 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
1949 int err = insert_page_in_batch_locked(vma, pte,
1950 addr, pages[curr_page_idx], prot);
1951 if (unlikely(err)) {
1952 pte_unmap_unlock(start_pte, pte_lock);
1954 remaining_pages_total -= pte_idx;
1960 pte_unmap_unlock(start_pte, pte_lock);
1961 pages_to_write_in_pmd -= batch_size;
1962 remaining_pages_total -= batch_size;
1964 if (remaining_pages_total)
1968 *num = remaining_pages_total;
1971 #endif /* ifdef pte_index */
1974 * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
1975 * @vma: user vma to map to
1976 * @addr: target start user address of these pages
1977 * @pages: source kernel pages
1978 * @num: in: number of pages to map. out: number of pages that were *not*
1979 * mapped. (0 means all pages were successfully mapped).
1981 * Preferred over vm_insert_page() when inserting multiple pages.
1983 * In case of error, we may have mapped a subset of the provided
1984 * pages. It is the caller's responsibility to account for this case.
1986 * The same restrictions apply as in vm_insert_page().
1988 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
1989 struct page **pages, unsigned long *num)
1992 const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
1994 if (addr < vma->vm_start || end_addr >= vma->vm_end)
1996 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1997 BUG_ON(mmap_read_trylock(vma->vm_mm));
1998 BUG_ON(vma->vm_flags & VM_PFNMAP);
1999 vma->vm_flags |= VM_MIXEDMAP;
2001 /* Defer page refcount checking till we're about to map that page. */
2002 return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
2004 unsigned long idx = 0, pgcount = *num;
2007 for (; idx < pgcount; ++idx) {
2008 err = vm_insert_page(vma, addr + (PAGE_SIZE * idx), pages[idx]);
2012 *num = pgcount - idx;
2014 #endif /* ifdef pte_index */
2016 EXPORT_SYMBOL(vm_insert_pages);
2019 * vm_insert_page - insert single page into user vma
2020 * @vma: user vma to map to
2021 * @addr: target user address of this page
2022 * @page: source kernel page
2024 * This allows drivers to insert individual pages they've allocated
2027 * The page has to be a nice clean _individual_ kernel allocation.
2028 * If you allocate a compound page, you need to have marked it as
2029 * such (__GFP_COMP), or manually just split the page up yourself
2030 * (see split_page()).
2032 * NOTE! Traditionally this was done with "remap_pfn_range()" which
2033 * took an arbitrary page protection parameter. This doesn't allow
2034 * that. Your vma protection will have to be set up correctly, which
2035 * means that if you want a shared writable mapping, you'd better
2036 * ask for a shared writable mapping!
2038 * The page does not need to be reserved.
2040 * Usually this function is called from f_op->mmap() handler
2041 * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
2042 * Caller must set VM_MIXEDMAP on vma if it wants to call this
2043 * function from other places, for example from page-fault handler.
2045 * Return: %0 on success, negative error code otherwise.
2047 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
2050 if (addr < vma->vm_start || addr >= vma->vm_end)
2052 if (!page_count(page))
2054 if (!(vma->vm_flags & VM_MIXEDMAP)) {
2055 BUG_ON(mmap_read_trylock(vma->vm_mm));
2056 BUG_ON(vma->vm_flags & VM_PFNMAP);
2057 vma->vm_flags |= VM_MIXEDMAP;
2059 return insert_page(vma, addr, page, vma->vm_page_prot);
2061 EXPORT_SYMBOL(vm_insert_page);
2064 * __vm_map_pages - maps range of kernel pages into user vma
2065 * @vma: user vma to map to
2066 * @pages: pointer to array of source kernel pages
2067 * @num: number of pages in page array
2068 * @offset: user's requested vm_pgoff
2070 * This allows drivers to map range of kernel pages into a user vma.
2072 * Return: 0 on success and error code otherwise.
2074 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2075 unsigned long num, unsigned long offset)
2077 unsigned long count = vma_pages(vma);
2078 unsigned long uaddr = vma->vm_start;
2081 /* Fail if the user requested offset is beyond the end of the object */
2085 /* Fail if the user requested size exceeds available object size */
2086 if (count > num - offset)
2089 for (i = 0; i < count; i++) {
2090 ret = vm_insert_page(vma, uaddr, pages[offset + i]);
2100 * vm_map_pages - maps range of kernel pages starts with non zero offset
2101 * @vma: user vma to map to
2102 * @pages: pointer to array of source kernel pages
2103 * @num: number of pages in page array
2105 * Maps an object consisting of @num pages, catering for the user's
2106 * requested vm_pgoff
2108 * If we fail to insert any page into the vma, the function will return
2109 * immediately leaving any previously inserted pages present. Callers
2110 * from the mmap handler may immediately return the error as their caller
2111 * will destroy the vma, removing any successfully inserted pages. Other
2112 * callers should make their own arrangements for calling unmap_region().
2114 * Context: Process context. Called by mmap handlers.
2115 * Return: 0 on success and error code otherwise.
2117 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2120 return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
2122 EXPORT_SYMBOL(vm_map_pages);
2125 * vm_map_pages_zero - map range of kernel pages starts with zero offset
2126 * @vma: user vma to map to
2127 * @pages: pointer to array of source kernel pages
2128 * @num: number of pages in page array
2130 * Similar to vm_map_pages(), except that it explicitly sets the offset
2131 * to 0. This function is intended for the drivers that did not consider
2134 * Context: Process context. Called by mmap handlers.
2135 * Return: 0 on success and error code otherwise.
2137 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
2140 return __vm_map_pages(vma, pages, num, 0);
2142 EXPORT_SYMBOL(vm_map_pages_zero);
2144 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2145 pfn_t pfn, pgprot_t prot, bool mkwrite)
2147 struct mm_struct *mm = vma->vm_mm;
2151 pte = get_locked_pte(mm, addr, &ptl);
2153 return VM_FAULT_OOM;
2154 if (!pte_none(*pte)) {
2157 * For read faults on private mappings the PFN passed
2158 * in may not match the PFN we have mapped if the
2159 * mapped PFN is a writeable COW page. In the mkwrite
2160 * case we are creating a writable PTE for a shared
2161 * mapping and we expect the PFNs to match. If they
2162 * don't match, we are likely racing with block
2163 * allocation and mapping invalidation so just skip the
2166 if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
2167 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
2170 entry = pte_mkyoung(*pte);
2171 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2172 if (ptep_set_access_flags(vma, addr, pte, entry, 1))
2173 update_mmu_cache(vma, addr, pte);
2178 /* Ok, finally just insert the thing.. */
2179 if (pfn_t_devmap(pfn))
2180 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
2182 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
2185 entry = pte_mkyoung(entry);
2186 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2189 set_pte_at(mm, addr, pte, entry);
2190 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2193 pte_unmap_unlock(pte, ptl);
2194 return VM_FAULT_NOPAGE;
2198 * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
2199 * @vma: user vma to map to
2200 * @addr: target user address of this page
2201 * @pfn: source kernel pfn
2202 * @pgprot: pgprot flags for the inserted page
2204 * This is exactly like vmf_insert_pfn(), except that it allows drivers
2205 * to override pgprot on a per-page basis.
2207 * This only makes sense for IO mappings, and it makes no sense for
2208 * COW mappings. In general, using multiple vmas is preferable;
2209 * vmf_insert_pfn_prot should only be used if using multiple VMAs is
2212 * See vmf_insert_mixed_prot() for a discussion of the implication of using
2213 * a value of @pgprot different from that of @vma->vm_page_prot.
2215 * Context: Process context. May allocate using %GFP_KERNEL.
2216 * Return: vm_fault_t value.
2218 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
2219 unsigned long pfn, pgprot_t pgprot)
2222 * Technically, architectures with pte_special can avoid all these
2223 * restrictions (same for remap_pfn_range). However we would like
2224 * consistency in testing and feature parity among all, so we should
2225 * try to keep these invariants in place for everybody.
2227 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2228 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2229 (VM_PFNMAP|VM_MIXEDMAP));
2230 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2231 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2233 if (addr < vma->vm_start || addr >= vma->vm_end)
2234 return VM_FAULT_SIGBUS;
2236 if (!pfn_modify_allowed(pfn, pgprot))
2237 return VM_FAULT_SIGBUS;
2239 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
2241 return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
2244 EXPORT_SYMBOL(vmf_insert_pfn_prot);
2247 * vmf_insert_pfn - insert single pfn into user vma
2248 * @vma: user vma to map to
2249 * @addr: target user address of this page
2250 * @pfn: source kernel pfn
2252 * Similar to vm_insert_page, this allows drivers to insert individual pages
2253 * they've allocated into a user vma. Same comments apply.
2255 * This function should only be called from a vm_ops->fault handler, and
2256 * in that case the handler should return the result of this function.
2258 * vma cannot be a COW mapping.
2260 * As this is called only for pages that do not currently exist, we
2261 * do not need to flush old virtual caches or the TLB.
2263 * Context: Process context. May allocate using %GFP_KERNEL.
2264 * Return: vm_fault_t value.
2266 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2269 return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
2271 EXPORT_SYMBOL(vmf_insert_pfn);
2273 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn)
2275 /* these checks mirror the abort conditions in vm_normal_page */
2276 if (vma->vm_flags & VM_MIXEDMAP)
2278 if (pfn_t_devmap(pfn))
2280 if (pfn_t_special(pfn))
2282 if (is_zero_pfn(pfn_t_to_pfn(pfn)))
2287 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
2288 unsigned long addr, pfn_t pfn, pgprot_t pgprot,
2293 BUG_ON(!vm_mixed_ok(vma, pfn));
2295 if (addr < vma->vm_start || addr >= vma->vm_end)
2296 return VM_FAULT_SIGBUS;
2298 track_pfn_insert(vma, &pgprot, pfn);
2300 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
2301 return VM_FAULT_SIGBUS;
2304 * If we don't have pte special, then we have to use the pfn_valid()
2305 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2306 * refcount the page if pfn_valid is true (hence insert_page rather
2307 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
2308 * without pte special, it would there be refcounted as a normal page.
2310 if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
2311 !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
2315 * At this point we are committed to insert_page()
2316 * regardless of whether the caller specified flags that
2317 * result in pfn_t_has_page() == false.
2319 page = pfn_to_page(pfn_t_to_pfn(pfn));
2320 err = insert_page(vma, addr, page, pgprot);
2322 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2326 return VM_FAULT_OOM;
2327 if (err < 0 && err != -EBUSY)
2328 return VM_FAULT_SIGBUS;
2330 return VM_FAULT_NOPAGE;
2334 * vmf_insert_mixed_prot - insert single pfn into user vma with specified pgprot
2335 * @vma: user vma to map to
2336 * @addr: target user address of this page
2337 * @pfn: source kernel pfn
2338 * @pgprot: pgprot flags for the inserted page
2340 * This is exactly like vmf_insert_mixed(), except that it allows drivers
2341 * to override pgprot on a per-page basis.
2343 * Typically this function should be used by drivers to set caching- and
2344 * encryption bits different than those of @vma->vm_page_prot, because
2345 * the caching- or encryption mode may not be known at mmap() time.
2346 * This is ok as long as @vma->vm_page_prot is not used by the core vm
2347 * to set caching and encryption bits for those vmas (except for COW pages).
2348 * This is ensured by core vm only modifying these page table entries using
2349 * functions that don't touch caching- or encryption bits, using pte_modify()
2350 * if needed. (See for example mprotect()).
2351 * Also when new page-table entries are created, this is only done using the
2352 * fault() callback, and never using the value of vma->vm_page_prot,
2353 * except for page-table entries that point to anonymous pages as the result
2356 * Context: Process context. May allocate using %GFP_KERNEL.
2357 * Return: vm_fault_t value.
2359 vm_fault_t vmf_insert_mixed_prot(struct vm_area_struct *vma, unsigned long addr,
2360 pfn_t pfn, pgprot_t pgprot)
2362 return __vm_insert_mixed(vma, addr, pfn, pgprot, false);
2364 EXPORT_SYMBOL(vmf_insert_mixed_prot);
2366 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2369 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, false);
2371 EXPORT_SYMBOL(vmf_insert_mixed);
2374 * If the insertion of PTE failed because someone else already added a
2375 * different entry in the mean time, we treat that as success as we assume
2376 * the same entry was actually inserted.
2378 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2379 unsigned long addr, pfn_t pfn)
2381 return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, true);
2383 EXPORT_SYMBOL(vmf_insert_mixed_mkwrite);
2386 * maps a range of physical memory into the requested pages. the old
2387 * mappings are removed. any references to nonexistent pages results
2388 * in null mappings (currently treated as "copy-on-access")
2390 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2391 unsigned long addr, unsigned long end,
2392 unsigned long pfn, pgprot_t prot)
2394 pte_t *pte, *mapped_pte;
2398 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2401 arch_enter_lazy_mmu_mode();
2403 BUG_ON(!pte_none(*pte));
2404 if (!pfn_modify_allowed(pfn, prot)) {
2408 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2410 } while (pte++, addr += PAGE_SIZE, addr != end);
2411 arch_leave_lazy_mmu_mode();
2412 pte_unmap_unlock(mapped_pte, ptl);
2416 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2417 unsigned long addr, unsigned long end,
2418 unsigned long pfn, pgprot_t prot)
2424 pfn -= addr >> PAGE_SHIFT;
2425 pmd = pmd_alloc(mm, pud, addr);
2428 VM_BUG_ON(pmd_trans_huge(*pmd));
2430 next = pmd_addr_end(addr, end);
2431 err = remap_pte_range(mm, pmd, addr, next,
2432 pfn + (addr >> PAGE_SHIFT), prot);
2435 } while (pmd++, addr = next, addr != end);
2439 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2440 unsigned long addr, unsigned long end,
2441 unsigned long pfn, pgprot_t prot)
2447 pfn -= addr >> PAGE_SHIFT;
2448 pud = pud_alloc(mm, p4d, addr);
2452 next = pud_addr_end(addr, end);
2453 err = remap_pmd_range(mm, pud, addr, next,
2454 pfn + (addr >> PAGE_SHIFT), prot);
2457 } while (pud++, addr = next, addr != end);
2461 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2462 unsigned long addr, unsigned long end,
2463 unsigned long pfn, pgprot_t prot)
2469 pfn -= addr >> PAGE_SHIFT;
2470 p4d = p4d_alloc(mm, pgd, addr);
2474 next = p4d_addr_end(addr, end);
2475 err = remap_pud_range(mm, p4d, addr, next,
2476 pfn + (addr >> PAGE_SHIFT), prot);
2479 } while (p4d++, addr = next, addr != end);
2484 * Variant of remap_pfn_range that does not call track_pfn_remap. The caller
2485 * must have pre-validated the caching bits of the pgprot_t.
2487 int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr,
2488 unsigned long pfn, unsigned long size, pgprot_t prot)
2492 unsigned long end = addr + PAGE_ALIGN(size);
2493 struct mm_struct *mm = vma->vm_mm;
2496 if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
2500 * Physically remapped pages are special. Tell the
2501 * rest of the world about it:
2502 * VM_IO tells people not to look at these pages
2503 * (accesses can have side effects).
2504 * VM_PFNMAP tells the core MM that the base pages are just
2505 * raw PFN mappings, and do not have a "struct page" associated
2508 * Disable vma merging and expanding with mremap().
2510 * Omit vma from core dump, even when VM_IO turned off.
2512 * There's a horrible special case to handle copy-on-write
2513 * behaviour that some programs depend on. We mark the "original"
2514 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2515 * See vm_normal_page() for details.
2517 if (is_cow_mapping(vma->vm_flags)) {
2518 if (addr != vma->vm_start || end != vma->vm_end)
2520 vma->vm_pgoff = pfn;
2523 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2525 BUG_ON(addr >= end);
2526 pfn -= addr >> PAGE_SHIFT;
2527 pgd = pgd_offset(mm, addr);
2528 flush_cache_range(vma, addr, end);
2530 next = pgd_addr_end(addr, end);
2531 err = remap_p4d_range(mm, pgd, addr, next,
2532 pfn + (addr >> PAGE_SHIFT), prot);
2535 } while (pgd++, addr = next, addr != end);
2541 * remap_pfn_range - remap kernel memory to userspace
2542 * @vma: user vma to map to
2543 * @addr: target page aligned user address to start at
2544 * @pfn: page frame number of kernel physical memory address
2545 * @size: size of mapping area
2546 * @prot: page protection flags for this mapping
2548 * Note: this is only safe if the mm semaphore is held when called.
2550 * Return: %0 on success, negative error code otherwise.
2552 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2553 unsigned long pfn, unsigned long size, pgprot_t prot)
2557 err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2561 err = remap_pfn_range_notrack(vma, addr, pfn, size, prot);
2563 untrack_pfn(vma, pfn, PAGE_ALIGN(size));
2566 EXPORT_SYMBOL(remap_pfn_range);
2569 * vm_iomap_memory - remap memory to userspace
2570 * @vma: user vma to map to
2571 * @start: start of the physical memory to be mapped
2572 * @len: size of area
2574 * This is a simplified io_remap_pfn_range() for common driver use. The
2575 * driver just needs to give us the physical memory range to be mapped,
2576 * we'll figure out the rest from the vma information.
2578 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2579 * whatever write-combining details or similar.
2581 * Return: %0 on success, negative error code otherwise.
2583 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2585 unsigned long vm_len, pfn, pages;
2587 /* Check that the physical memory area passed in looks valid */
2588 if (start + len < start)
2591 * You *really* shouldn't map things that aren't page-aligned,
2592 * but we've historically allowed it because IO memory might
2593 * just have smaller alignment.
2595 len += start & ~PAGE_MASK;
2596 pfn = start >> PAGE_SHIFT;
2597 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2598 if (pfn + pages < pfn)
2601 /* We start the mapping 'vm_pgoff' pages into the area */
2602 if (vma->vm_pgoff > pages)
2604 pfn += vma->vm_pgoff;
2605 pages -= vma->vm_pgoff;
2607 /* Can we fit all of the mapping? */
2608 vm_len = vma->vm_end - vma->vm_start;
2609 if (vm_len >> PAGE_SHIFT > pages)
2612 /* Ok, let it rip */
2613 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2615 EXPORT_SYMBOL(vm_iomap_memory);
2617 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2618 unsigned long addr, unsigned long end,
2619 pte_fn_t fn, void *data, bool create,
2620 pgtbl_mod_mask *mask)
2622 pte_t *pte, *mapped_pte;
2627 mapped_pte = pte = (mm == &init_mm) ?
2628 pte_alloc_kernel_track(pmd, addr, mask) :
2629 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2633 mapped_pte = pte = (mm == &init_mm) ?
2634 pte_offset_kernel(pmd, addr) :
2635 pte_offset_map_lock(mm, pmd, addr, &ptl);
2638 BUG_ON(pmd_huge(*pmd));
2640 arch_enter_lazy_mmu_mode();
2644 if (create || !pte_none(*pte)) {
2645 err = fn(pte++, addr, data);
2649 } while (addr += PAGE_SIZE, addr != end);
2651 *mask |= PGTBL_PTE_MODIFIED;
2653 arch_leave_lazy_mmu_mode();
2656 pte_unmap_unlock(mapped_pte, ptl);
2660 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2661 unsigned long addr, unsigned long end,
2662 pte_fn_t fn, void *data, bool create,
2663 pgtbl_mod_mask *mask)
2669 BUG_ON(pud_huge(*pud));
2672 pmd = pmd_alloc_track(mm, pud, addr, mask);
2676 pmd = pmd_offset(pud, addr);
2679 next = pmd_addr_end(addr, end);
2680 if (pmd_none(*pmd) && !create)
2682 if (WARN_ON_ONCE(pmd_leaf(*pmd)))
2684 if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) {
2689 err = apply_to_pte_range(mm, pmd, addr, next,
2690 fn, data, create, mask);
2693 } while (pmd++, addr = next, addr != end);
2698 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2699 unsigned long addr, unsigned long end,
2700 pte_fn_t fn, void *data, bool create,
2701 pgtbl_mod_mask *mask)
2708 pud = pud_alloc_track(mm, p4d, addr, mask);
2712 pud = pud_offset(p4d, addr);
2715 next = pud_addr_end(addr, end);
2716 if (pud_none(*pud) && !create)
2718 if (WARN_ON_ONCE(pud_leaf(*pud)))
2720 if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) {
2725 err = apply_to_pmd_range(mm, pud, addr, next,
2726 fn, data, create, mask);
2729 } while (pud++, addr = next, addr != end);
2734 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2735 unsigned long addr, unsigned long end,
2736 pte_fn_t fn, void *data, bool create,
2737 pgtbl_mod_mask *mask)
2744 p4d = p4d_alloc_track(mm, pgd, addr, mask);
2748 p4d = p4d_offset(pgd, addr);
2751 next = p4d_addr_end(addr, end);
2752 if (p4d_none(*p4d) && !create)
2754 if (WARN_ON_ONCE(p4d_leaf(*p4d)))
2756 if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) {
2761 err = apply_to_pud_range(mm, p4d, addr, next,
2762 fn, data, create, mask);
2765 } while (p4d++, addr = next, addr != end);
2770 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2771 unsigned long size, pte_fn_t fn,
2772 void *data, bool create)
2775 unsigned long start = addr, next;
2776 unsigned long end = addr + size;
2777 pgtbl_mod_mask mask = 0;
2780 if (WARN_ON(addr >= end))
2783 pgd = pgd_offset(mm, addr);
2785 next = pgd_addr_end(addr, end);
2786 if (pgd_none(*pgd) && !create)
2788 if (WARN_ON_ONCE(pgd_leaf(*pgd)))
2790 if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) {
2795 err = apply_to_p4d_range(mm, pgd, addr, next,
2796 fn, data, create, &mask);
2799 } while (pgd++, addr = next, addr != end);
2801 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
2802 arch_sync_kernel_mappings(start, start + size);
2808 * Scan a region of virtual memory, filling in page tables as necessary
2809 * and calling a provided function on each leaf page table.
2811 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2812 unsigned long size, pte_fn_t fn, void *data)
2814 return __apply_to_page_range(mm, addr, size, fn, data, true);
2816 EXPORT_SYMBOL_GPL(apply_to_page_range);
2819 * Scan a region of virtual memory, calling a provided function on
2820 * each leaf page table where it exists.
2822 * Unlike apply_to_page_range, this does _not_ fill in page tables
2823 * where they are absent.
2825 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
2826 unsigned long size, pte_fn_t fn, void *data)
2828 return __apply_to_page_range(mm, addr, size, fn, data, false);
2830 EXPORT_SYMBOL_GPL(apply_to_existing_page_range);
2833 * handle_pte_fault chooses page fault handler according to an entry which was
2834 * read non-atomically. Before making any commitment, on those architectures
2835 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2836 * parts, do_swap_page must check under lock before unmapping the pte and
2837 * proceeding (but do_wp_page is only called after already making such a check;
2838 * and do_anonymous_page can safely check later on).
2840 static inline int pte_unmap_same(struct vm_fault *vmf)
2843 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
2844 if (sizeof(pte_t) > sizeof(unsigned long)) {
2845 spinlock_t *ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
2847 same = pte_same(*vmf->pte, vmf->orig_pte);
2851 pte_unmap(vmf->pte);
2858 * 0: copied succeeded
2859 * -EHWPOISON: copy failed due to hwpoison in source page
2860 * -EAGAIN: copied failed (some other reason)
2862 static inline int __wp_page_copy_user(struct page *dst, struct page *src,
2863 struct vm_fault *vmf)
2868 bool locked = false;
2869 struct vm_area_struct *vma = vmf->vma;
2870 struct mm_struct *mm = vma->vm_mm;
2871 unsigned long addr = vmf->address;
2874 if (copy_mc_user_highpage(dst, src, addr, vma)) {
2875 memory_failure_queue(page_to_pfn(src), 0);
2882 * If the source page was a PFN mapping, we don't have
2883 * a "struct page" for it. We do a best-effort copy by
2884 * just copying from the original user address. If that
2885 * fails, we just zero-fill it. Live with it.
2887 kaddr = kmap_atomic(dst);
2888 uaddr = (void __user *)(addr & PAGE_MASK);
2891 * On architectures with software "accessed" bits, we would
2892 * take a double page fault, so mark it accessed here.
2894 if (!arch_has_hw_pte_young() && !pte_young(vmf->orig_pte)) {
2897 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2899 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2901 * Other thread has already handled the fault
2902 * and update local tlb only
2904 update_mmu_tlb(vma, addr, vmf->pte);
2909 entry = pte_mkyoung(vmf->orig_pte);
2910 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2911 update_mmu_cache(vma, addr, vmf->pte);
2915 * This really shouldn't fail, because the page is there
2916 * in the page tables. But it might just be unreadable,
2917 * in which case we just give up and fill the result with
2920 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2924 /* Re-validate under PTL if the page is still mapped */
2925 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2927 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2928 /* The PTE changed under us, update local tlb */
2929 update_mmu_tlb(vma, addr, vmf->pte);
2935 * The same page can be mapped back since last copy attempt.
2936 * Try to copy again under PTL.
2938 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2940 * Give a warn in case there can be some obscure
2953 pte_unmap_unlock(vmf->pte, vmf->ptl);
2954 kunmap_atomic(kaddr);
2955 flush_dcache_page(dst);
2960 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2962 struct file *vm_file = vma->vm_file;
2965 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2968 * Special mappings (e.g. VDSO) do not have any file so fake
2969 * a default GFP_KERNEL for them.
2975 * Notify the address space that the page is about to become writable so that
2976 * it can prohibit this or wait for the page to get into an appropriate state.
2978 * We do this without the lock held, so that it can sleep if it needs to.
2980 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf)
2983 struct page *page = vmf->page;
2984 unsigned int old_flags = vmf->flags;
2986 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2988 if (vmf->vma->vm_file &&
2989 IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
2990 return VM_FAULT_SIGBUS;
2992 ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2993 /* Restore original flags so that caller is not surprised */
2994 vmf->flags = old_flags;
2995 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2997 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2999 if (!page->mapping) {
3001 return 0; /* retry */
3003 ret |= VM_FAULT_LOCKED;
3005 VM_BUG_ON_PAGE(!PageLocked(page), page);
3010 * Handle dirtying of a page in shared file mapping on a write fault.
3012 * The function expects the page to be locked and unlocks it.
3014 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
3016 struct vm_area_struct *vma = vmf->vma;
3017 struct address_space *mapping;
3018 struct page *page = vmf->page;
3020 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
3022 dirtied = set_page_dirty(page);
3023 VM_BUG_ON_PAGE(PageAnon(page), page);
3025 * Take a local copy of the address_space - page.mapping may be zeroed
3026 * by truncate after unlock_page(). The address_space itself remains
3027 * pinned by vma->vm_file's reference. We rely on unlock_page()'s
3028 * release semantics to prevent the compiler from undoing this copying.
3030 mapping = page_rmapping(page);
3034 file_update_time(vma->vm_file);
3037 * Throttle page dirtying rate down to writeback speed.
3039 * mapping may be NULL here because some device drivers do not
3040 * set page.mapping but still dirty their pages
3042 * Drop the mmap_lock before waiting on IO, if we can. The file
3043 * is pinning the mapping, as per above.
3045 if ((dirtied || page_mkwrite) && mapping) {
3048 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
3049 balance_dirty_pages_ratelimited(mapping);
3052 return VM_FAULT_COMPLETED;
3060 * Handle write page faults for pages that can be reused in the current vma
3062 * This can happen either due to the mapping being with the VM_SHARED flag,
3063 * or due to us being the last reference standing to the page. In either
3064 * case, all we need to do here is to mark the page as writable and update
3065 * any related book-keeping.
3067 static inline void wp_page_reuse(struct vm_fault *vmf)
3068 __releases(vmf->ptl)
3070 struct vm_area_struct *vma = vmf->vma;
3071 struct page *page = vmf->page;
3074 VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE));
3075 VM_BUG_ON(page && PageAnon(page) && !PageAnonExclusive(page));
3078 * Clear the pages cpupid information as the existing
3079 * information potentially belongs to a now completely
3080 * unrelated process.
3083 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
3085 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3086 entry = pte_mkyoung(vmf->orig_pte);
3087 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3088 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
3089 update_mmu_cache(vma, vmf->address, vmf->pte);
3090 pte_unmap_unlock(vmf->pte, vmf->ptl);
3091 count_vm_event(PGREUSE);
3095 * Handle the case of a page which we actually need to copy to a new page,
3096 * either due to COW or unsharing.
3098 * Called with mmap_lock locked and the old page referenced, but
3099 * without the ptl held.
3101 * High level logic flow:
3103 * - Allocate a page, copy the content of the old page to the new one.
3104 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
3105 * - Take the PTL. If the pte changed, bail out and release the allocated page
3106 * - If the pte is still the way we remember it, update the page table and all
3107 * relevant references. This includes dropping the reference the page-table
3108 * held to the old page, as well as updating the rmap.
3109 * - In any case, unlock the PTL and drop the reference we took to the old page.
3111 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
3113 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3114 struct vm_area_struct *vma = vmf->vma;
3115 struct mm_struct *mm = vma->vm_mm;
3116 struct page *old_page = vmf->page;
3117 struct page *new_page = NULL;
3119 int page_copied = 0;
3120 struct mmu_notifier_range range;
3123 delayacct_wpcopy_start();
3125 if (unlikely(anon_vma_prepare(vma)))
3128 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
3129 new_page = alloc_zeroed_user_highpage_movable(vma,
3134 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3139 ret = __wp_page_copy_user(new_page, old_page, vmf);
3142 * COW failed, if the fault was solved by other,
3143 * it's fine. If not, userspace would re-fault on
3144 * the same address and we will handle the fault
3145 * from the second attempt.
3146 * The -EHWPOISON case will not be retried.
3152 delayacct_wpcopy_end();
3153 return ret == -EHWPOISON ? VM_FAULT_HWPOISON : 0;
3155 kmsan_copy_page_meta(new_page, old_page);
3158 if (mem_cgroup_charge(page_folio(new_page), mm, GFP_KERNEL))
3160 cgroup_throttle_swaprate(new_page, GFP_KERNEL);
3162 __SetPageUptodate(new_page);
3164 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
3165 vmf->address & PAGE_MASK,
3166 (vmf->address & PAGE_MASK) + PAGE_SIZE);
3167 mmu_notifier_invalidate_range_start(&range);
3170 * Re-check the pte - we dropped the lock
3172 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
3173 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
3175 if (!PageAnon(old_page)) {
3176 dec_mm_counter_fast(mm,
3177 mm_counter_file(old_page));
3178 inc_mm_counter_fast(mm, MM_ANONPAGES);
3181 inc_mm_counter_fast(mm, MM_ANONPAGES);
3183 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3184 entry = mk_pte(new_page, vma->vm_page_prot);
3185 entry = pte_sw_mkyoung(entry);
3186 if (unlikely(unshare)) {
3187 if (pte_soft_dirty(vmf->orig_pte))
3188 entry = pte_mksoft_dirty(entry);
3189 if (pte_uffd_wp(vmf->orig_pte))
3190 entry = pte_mkuffd_wp(entry);
3192 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3196 * Clear the pte entry and flush it first, before updating the
3197 * pte with the new entry, to keep TLBs on different CPUs in
3198 * sync. This code used to set the new PTE then flush TLBs, but
3199 * that left a window where the new PTE could be loaded into
3200 * some TLBs while the old PTE remains in others.
3202 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
3203 page_add_new_anon_rmap(new_page, vma, vmf->address);
3204 lru_cache_add_inactive_or_unevictable(new_page, vma);
3206 * We call the notify macro here because, when using secondary
3207 * mmu page tables (such as kvm shadow page tables), we want the
3208 * new page to be mapped directly into the secondary page table.
3210 BUG_ON(unshare && pte_write(entry));
3211 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
3212 update_mmu_cache(vma, vmf->address, vmf->pte);
3215 * Only after switching the pte to the new page may
3216 * we remove the mapcount here. Otherwise another
3217 * process may come and find the rmap count decremented
3218 * before the pte is switched to the new page, and
3219 * "reuse" the old page writing into it while our pte
3220 * here still points into it and can be read by other
3223 * The critical issue is to order this
3224 * page_remove_rmap with the ptp_clear_flush above.
3225 * Those stores are ordered by (if nothing else,)
3226 * the barrier present in the atomic_add_negative
3227 * in page_remove_rmap.
3229 * Then the TLB flush in ptep_clear_flush ensures that
3230 * no process can access the old page before the
3231 * decremented mapcount is visible. And the old page
3232 * cannot be reused until after the decremented
3233 * mapcount is visible. So transitively, TLBs to
3234 * old page will be flushed before it can be reused.
3236 page_remove_rmap(old_page, vma, false);
3239 /* Free the old page.. */
3240 new_page = old_page;
3243 update_mmu_tlb(vma, vmf->address, vmf->pte);
3249 pte_unmap_unlock(vmf->pte, vmf->ptl);
3251 * No need to double call mmu_notifier->invalidate_range() callback as
3252 * the above ptep_clear_flush_notify() did already call it.
3254 mmu_notifier_invalidate_range_only_end(&range);
3257 free_swap_cache(old_page);
3261 delayacct_wpcopy_end();
3262 return (page_copied && !unshare) ? VM_FAULT_WRITE : 0;
3269 delayacct_wpcopy_end();
3270 return VM_FAULT_OOM;
3274 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
3275 * writeable once the page is prepared
3277 * @vmf: structure describing the fault
3279 * This function handles all that is needed to finish a write page fault in a
3280 * shared mapping due to PTE being read-only once the mapped page is prepared.
3281 * It handles locking of PTE and modifying it.
3283 * The function expects the page to be locked or other protection against
3284 * concurrent faults / writeback (such as DAX radix tree locks).
3286 * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before
3287 * we acquired PTE lock.
3289 vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf)
3291 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
3292 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
3295 * We might have raced with another page fault while we released the
3296 * pte_offset_map_lock.
3298 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
3299 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
3300 pte_unmap_unlock(vmf->pte, vmf->ptl);
3301 return VM_FAULT_NOPAGE;
3308 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
3311 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
3313 struct vm_area_struct *vma = vmf->vma;
3315 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
3318 pte_unmap_unlock(vmf->pte, vmf->ptl);
3319 vmf->flags |= FAULT_FLAG_MKWRITE;
3320 ret = vma->vm_ops->pfn_mkwrite(vmf);
3321 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
3323 return finish_mkwrite_fault(vmf);
3326 return VM_FAULT_WRITE;
3329 static vm_fault_t wp_page_shared(struct vm_fault *vmf)
3330 __releases(vmf->ptl)
3332 struct vm_area_struct *vma = vmf->vma;
3333 vm_fault_t ret = VM_FAULT_WRITE;
3335 get_page(vmf->page);
3337 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
3340 pte_unmap_unlock(vmf->pte, vmf->ptl);
3341 tmp = do_page_mkwrite(vmf);
3342 if (unlikely(!tmp || (tmp &
3343 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3344 put_page(vmf->page);
3347 tmp = finish_mkwrite_fault(vmf);
3348 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3349 unlock_page(vmf->page);
3350 put_page(vmf->page);
3355 lock_page(vmf->page);
3357 ret |= fault_dirty_shared_page(vmf);
3358 put_page(vmf->page);
3364 * This routine handles present pages, when
3365 * * users try to write to a shared page (FAULT_FLAG_WRITE)
3366 * * GUP wants to take a R/O pin on a possibly shared anonymous page
3367 * (FAULT_FLAG_UNSHARE)
3369 * It is done by copying the page to a new address and decrementing the
3370 * shared-page counter for the old page.
3372 * Note that this routine assumes that the protection checks have been
3373 * done by the caller (the low-level page fault routine in most cases).
3374 * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've
3375 * done any necessary COW.
3377 * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even
3378 * though the page will change only once the write actually happens. This
3379 * avoids a few races, and potentially makes it more efficient.
3381 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3382 * but allow concurrent faults), with pte both mapped and locked.
3383 * We return with mmap_lock still held, but pte unmapped and unlocked.
3385 static vm_fault_t do_wp_page(struct vm_fault *vmf)
3386 __releases(vmf->ptl)
3388 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3389 struct vm_area_struct *vma = vmf->vma;
3390 struct folio *folio;
3392 VM_BUG_ON(unshare && (vmf->flags & FAULT_FLAG_WRITE));
3393 VM_BUG_ON(!unshare && !(vmf->flags & FAULT_FLAG_WRITE));
3395 if (likely(!unshare)) {
3396 if (userfaultfd_pte_wp(vma, *vmf->pte)) {
3397 pte_unmap_unlock(vmf->pte, vmf->ptl);
3398 return handle_userfault(vmf, VM_UFFD_WP);
3402 * Userfaultfd write-protect can defer flushes. Ensure the TLB
3403 * is flushed in this case before copying.
3405 if (unlikely(userfaultfd_wp(vmf->vma) &&
3406 mm_tlb_flush_pending(vmf->vma->vm_mm)))
3407 flush_tlb_page(vmf->vma, vmf->address);
3410 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
3412 if (unlikely(unshare)) {
3413 /* No anonymous page -> nothing to do. */
3414 pte_unmap_unlock(vmf->pte, vmf->ptl);
3419 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
3422 * We should not cow pages in a shared writeable mapping.
3423 * Just mark the pages writable and/or call ops->pfn_mkwrite.
3425 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3426 (VM_WRITE|VM_SHARED))
3427 return wp_pfn_shared(vmf);
3429 pte_unmap_unlock(vmf->pte, vmf->ptl);
3430 return wp_page_copy(vmf);
3434 * Take out anonymous pages first, anonymous shared vmas are
3435 * not dirty accountable.
3437 folio = page_folio(vmf->page);
3438 if (folio_test_anon(folio)) {
3440 * If the page is exclusive to this process we must reuse the
3441 * page without further checks.
3443 if (PageAnonExclusive(vmf->page))
3447 * We have to verify under folio lock: these early checks are
3448 * just an optimization to avoid locking the folio and freeing
3449 * the swapcache if there is little hope that we can reuse.
3451 * KSM doesn't necessarily raise the folio refcount.
3453 if (folio_test_ksm(folio) || folio_ref_count(folio) > 3)
3455 if (!folio_test_lru(folio))
3457 * Note: We cannot easily detect+handle references from
3458 * remote LRU pagevecs or references to LRU folios.
3461 if (folio_ref_count(folio) > 1 + folio_test_swapcache(folio))
3463 if (!folio_trylock(folio))
3465 if (folio_test_swapcache(folio))
3466 folio_free_swap(folio);
3467 if (folio_test_ksm(folio) || folio_ref_count(folio) != 1) {
3468 folio_unlock(folio);
3472 * Ok, we've got the only folio reference from our mapping
3473 * and the folio is locked, it's dark out, and we're wearing
3474 * sunglasses. Hit it.
3476 page_move_anon_rmap(vmf->page, vma);
3477 folio_unlock(folio);
3479 if (unlikely(unshare)) {
3480 pte_unmap_unlock(vmf->pte, vmf->ptl);
3484 return VM_FAULT_WRITE;
3485 } else if (unshare) {
3486 /* No anonymous page -> nothing to do. */
3487 pte_unmap_unlock(vmf->pte, vmf->ptl);
3489 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3490 (VM_WRITE|VM_SHARED))) {
3491 return wp_page_shared(vmf);
3495 * Ok, we need to copy. Oh, well..
3497 get_page(vmf->page);
3499 pte_unmap_unlock(vmf->pte, vmf->ptl);
3501 if (PageKsm(vmf->page))
3502 count_vm_event(COW_KSM);
3504 return wp_page_copy(vmf);
3507 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
3508 unsigned long start_addr, unsigned long end_addr,
3509 struct zap_details *details)
3511 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
3514 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
3515 pgoff_t first_index,
3517 struct zap_details *details)
3519 struct vm_area_struct *vma;
3520 pgoff_t vba, vea, zba, zea;
3522 vma_interval_tree_foreach(vma, root, first_index, last_index) {
3523 vba = vma->vm_pgoff;
3524 vea = vba + vma_pages(vma) - 1;
3525 zba = max(first_index, vba);
3526 zea = min(last_index, vea);
3528 unmap_mapping_range_vma(vma,
3529 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
3530 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3536 * unmap_mapping_folio() - Unmap single folio from processes.
3537 * @folio: The locked folio to be unmapped.
3539 * Unmap this folio from any userspace process which still has it mmaped.
3540 * Typically, for efficiency, the range of nearby pages has already been
3541 * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once
3542 * truncation or invalidation holds the lock on a folio, it may find that
3543 * the page has been remapped again: and then uses unmap_mapping_folio()
3544 * to unmap it finally.
3546 void unmap_mapping_folio(struct folio *folio)
3548 struct address_space *mapping = folio->mapping;
3549 struct zap_details details = { };
3550 pgoff_t first_index;
3553 VM_BUG_ON(!folio_test_locked(folio));
3555 first_index = folio->index;
3556 last_index = folio->index + folio_nr_pages(folio) - 1;
3558 details.even_cows = false;
3559 details.single_folio = folio;
3560 details.zap_flags = ZAP_FLAG_DROP_MARKER;
3562 i_mmap_lock_read(mapping);
3563 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3564 unmap_mapping_range_tree(&mapping->i_mmap, first_index,
3565 last_index, &details);
3566 i_mmap_unlock_read(mapping);
3570 * unmap_mapping_pages() - Unmap pages from processes.
3571 * @mapping: The address space containing pages to be unmapped.
3572 * @start: Index of first page to be unmapped.
3573 * @nr: Number of pages to be unmapped. 0 to unmap to end of file.
3574 * @even_cows: Whether to unmap even private COWed pages.
3576 * Unmap the pages in this address space from any userspace process which
3577 * has them mmaped. Generally, you want to remove COWed pages as well when
3578 * a file is being truncated, but not when invalidating pages from the page
3581 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
3582 pgoff_t nr, bool even_cows)
3584 struct zap_details details = { };
3585 pgoff_t first_index = start;
3586 pgoff_t last_index = start + nr - 1;
3588 details.even_cows = even_cows;
3589 if (last_index < first_index)
3590 last_index = ULONG_MAX;
3592 i_mmap_lock_read(mapping);
3593 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3594 unmap_mapping_range_tree(&mapping->i_mmap, first_index,
3595 last_index, &details);
3596 i_mmap_unlock_read(mapping);
3598 EXPORT_SYMBOL_GPL(unmap_mapping_pages);
3601 * unmap_mapping_range - unmap the portion of all mmaps in the specified
3602 * address_space corresponding to the specified byte range in the underlying
3605 * @mapping: the address space containing mmaps to be unmapped.
3606 * @holebegin: byte in first page to unmap, relative to the start of
3607 * the underlying file. This will be rounded down to a PAGE_SIZE
3608 * boundary. Note that this is different from truncate_pagecache(), which
3609 * must keep the partial page. In contrast, we must get rid of
3611 * @holelen: size of prospective hole in bytes. This will be rounded
3612 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
3614 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3615 * but 0 when invalidating pagecache, don't throw away private data.
3617 void unmap_mapping_range(struct address_space *mapping,
3618 loff_t const holebegin, loff_t const holelen, int even_cows)
3620 pgoff_t hba = holebegin >> PAGE_SHIFT;
3621 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3623 /* Check for overflow. */
3624 if (sizeof(holelen) > sizeof(hlen)) {
3626 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3627 if (holeend & ~(long long)ULONG_MAX)
3628 hlen = ULONG_MAX - hba + 1;
3631 unmap_mapping_pages(mapping, hba, hlen, even_cows);
3633 EXPORT_SYMBOL(unmap_mapping_range);
3636 * Restore a potential device exclusive pte to a working pte entry
3638 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf)
3640 struct folio *folio = page_folio(vmf->page);
3641 struct vm_area_struct *vma = vmf->vma;
3642 struct mmu_notifier_range range;
3645 * We need a reference to lock the folio because we don't hold
3646 * the PTL so a racing thread can remove the device-exclusive
3647 * entry and unmap it. If the folio is free the entry must
3648 * have been removed already. If it happens to have already
3649 * been re-allocated after being freed all we do is lock and
3652 if (!folio_try_get(folio))
3655 if (!folio_lock_or_retry(folio, vma->vm_mm, vmf->flags)) {
3657 return VM_FAULT_RETRY;
3659 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma,
3660 vma->vm_mm, vmf->address & PAGE_MASK,
3661 (vmf->address & PAGE_MASK) + PAGE_SIZE, NULL);
3662 mmu_notifier_invalidate_range_start(&range);
3664 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3666 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3667 restore_exclusive_pte(vma, vmf->page, vmf->address, vmf->pte);
3669 pte_unmap_unlock(vmf->pte, vmf->ptl);
3670 folio_unlock(folio);
3673 mmu_notifier_invalidate_range_end(&range);
3677 static inline bool should_try_to_free_swap(struct folio *folio,
3678 struct vm_area_struct *vma,
3679 unsigned int fault_flags)
3681 if (!folio_test_swapcache(folio))
3683 if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
3684 folio_test_mlocked(folio))
3687 * If we want to map a page that's in the swapcache writable, we
3688 * have to detect via the refcount if we're really the exclusive
3689 * user. Try freeing the swapcache to get rid of the swapcache
3690 * reference only in case it's likely that we'll be the exlusive user.
3692 return (fault_flags & FAULT_FLAG_WRITE) && !folio_test_ksm(folio) &&
3693 folio_ref_count(folio) == 2;
3696 static vm_fault_t pte_marker_clear(struct vm_fault *vmf)
3698 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
3699 vmf->address, &vmf->ptl);
3701 * Be careful so that we will only recover a special uffd-wp pte into a
3702 * none pte. Otherwise it means the pte could have changed, so retry.
3704 if (is_pte_marker(*vmf->pte))
3705 pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte);
3706 pte_unmap_unlock(vmf->pte, vmf->ptl);
3711 * This is actually a page-missing access, but with uffd-wp special pte
3712 * installed. It means this pte was wr-protected before being unmapped.
3714 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf)
3717 * Just in case there're leftover special ptes even after the region
3718 * got unregistered - we can simply clear them. We can also do that
3719 * proactively when e.g. when we do UFFDIO_UNREGISTER upon some uffd-wp
3720 * ranges, but it should be more efficient to be done lazily here.
3722 if (unlikely(!userfaultfd_wp(vmf->vma) || vma_is_anonymous(vmf->vma)))
3723 return pte_marker_clear(vmf);
3725 /* do_fault() can handle pte markers too like none pte */
3726 return do_fault(vmf);
3729 static vm_fault_t handle_pte_marker(struct vm_fault *vmf)
3731 swp_entry_t entry = pte_to_swp_entry(vmf->orig_pte);
3732 unsigned long marker = pte_marker_get(entry);
3735 * PTE markers should always be with file-backed memories, and the
3736 * marker should never be empty. If anything weird happened, the best
3737 * thing to do is to kill the process along with its mm.
3739 if (WARN_ON_ONCE(vma_is_anonymous(vmf->vma) || !marker))
3740 return VM_FAULT_SIGBUS;
3742 if (pte_marker_entry_uffd_wp(entry))
3743 return pte_marker_handle_uffd_wp(vmf);
3745 /* This is an unknown pte marker */
3746 return VM_FAULT_SIGBUS;
3750 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3751 * but allow concurrent faults), and pte mapped but not yet locked.
3752 * We return with pte unmapped and unlocked.
3754 * We return with the mmap_lock locked or unlocked in the same cases
3755 * as does filemap_fault().
3757 vm_fault_t do_swap_page(struct vm_fault *vmf)
3759 struct vm_area_struct *vma = vmf->vma;
3760 struct folio *swapcache, *folio = NULL;
3762 struct swap_info_struct *si = NULL;
3763 rmap_t rmap_flags = RMAP_NONE;
3764 bool exclusive = false;
3769 void *shadow = NULL;
3771 if (!pte_unmap_same(vmf))
3774 entry = pte_to_swp_entry(vmf->orig_pte);
3775 if (unlikely(non_swap_entry(entry))) {
3776 if (is_migration_entry(entry)) {
3777 migration_entry_wait(vma->vm_mm, vmf->pmd,
3779 } else if (is_device_exclusive_entry(entry)) {
3780 vmf->page = pfn_swap_entry_to_page(entry);
3781 ret = remove_device_exclusive_entry(vmf);
3782 } else if (is_device_private_entry(entry)) {
3783 vmf->page = pfn_swap_entry_to_page(entry);
3784 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3785 vmf->address, &vmf->ptl);
3786 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
3787 spin_unlock(vmf->ptl);
3792 * Get a page reference while we know the page can't be
3795 get_page(vmf->page);
3796 pte_unmap_unlock(vmf->pte, vmf->ptl);
3797 ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
3798 put_page(vmf->page);
3799 } else if (is_hwpoison_entry(entry)) {
3800 ret = VM_FAULT_HWPOISON;
3801 } else if (is_swapin_error_entry(entry)) {
3802 ret = VM_FAULT_SIGBUS;
3803 } else if (is_pte_marker_entry(entry)) {
3804 ret = handle_pte_marker(vmf);
3806 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3807 ret = VM_FAULT_SIGBUS;
3812 /* Prevent swapoff from happening to us. */
3813 si = get_swap_device(entry);
3817 folio = swap_cache_get_folio(entry, vma, vmf->address);
3819 page = folio_file_page(folio, swp_offset(entry));
3823 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
3824 __swap_count(entry) == 1) {
3825 /* skip swapcache */
3826 folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0,
3827 vma, vmf->address, false);
3828 page = &folio->page;
3830 __folio_set_locked(folio);
3831 __folio_set_swapbacked(folio);
3833 if (mem_cgroup_swapin_charge_folio(folio,
3834 vma->vm_mm, GFP_KERNEL,
3839 mem_cgroup_swapin_uncharge_swap(entry);
3841 shadow = get_shadow_from_swap_cache(entry);
3843 workingset_refault(folio, shadow);
3845 folio_add_lru(folio);
3847 /* To provide entry to swap_readpage() */
3848 folio_set_swap_entry(folio, entry);
3849 swap_readpage(page, true, NULL);
3850 folio->private = NULL;
3853 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3856 folio = page_folio(page);
3862 * Back out if somebody else faulted in this pte
3863 * while we released the pte lock.
3865 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3866 vmf->address, &vmf->ptl);
3867 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3872 /* Had to read the page from swap area: Major fault */
3873 ret = VM_FAULT_MAJOR;
3874 count_vm_event(PGMAJFAULT);
3875 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3876 } else if (PageHWPoison(page)) {
3878 * hwpoisoned dirty swapcache pages are kept for killing
3879 * owner processes (which may be unknown at hwpoison time)
3881 ret = VM_FAULT_HWPOISON;
3885 locked = folio_lock_or_retry(folio, vma->vm_mm, vmf->flags);
3888 ret |= VM_FAULT_RETRY;
3894 * Make sure folio_free_swap() or swapoff did not release the
3895 * swapcache from under us. The page pin, and pte_same test
3896 * below, are not enough to exclude that. Even if it is still
3897 * swapcache, we need to check that the page's swap has not
3900 if (unlikely(!folio_test_swapcache(folio) ||
3901 page_private(page) != entry.val))
3905 * KSM sometimes has to copy on read faults, for example, if
3906 * page->index of !PageKSM() pages would be nonlinear inside the
3907 * anon VMA -- PageKSM() is lost on actual swapout.
3909 page = ksm_might_need_to_copy(page, vma, vmf->address);
3910 if (unlikely(!page)) {
3914 folio = page_folio(page);
3917 * If we want to map a page that's in the swapcache writable, we
3918 * have to detect via the refcount if we're really the exclusive
3919 * owner. Try removing the extra reference from the local LRU
3920 * pagevecs if required.
3922 if ((vmf->flags & FAULT_FLAG_WRITE) && folio == swapcache &&
3923 !folio_test_ksm(folio) && !folio_test_lru(folio))
3927 cgroup_throttle_swaprate(page, GFP_KERNEL);
3930 * Back out if somebody else already faulted in this pte.
3932 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3934 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3937 if (unlikely(!folio_test_uptodate(folio))) {
3938 ret = VM_FAULT_SIGBUS;
3943 * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte
3944 * must never point at an anonymous page in the swapcache that is
3945 * PG_anon_exclusive. Sanity check that this holds and especially, that
3946 * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity
3947 * check after taking the PT lock and making sure that nobody
3948 * concurrently faulted in this page and set PG_anon_exclusive.
3950 BUG_ON(!folio_test_anon(folio) && folio_test_mappedtodisk(folio));
3951 BUG_ON(folio_test_anon(folio) && PageAnonExclusive(page));
3954 * Check under PT lock (to protect against concurrent fork() sharing
3955 * the swap entry concurrently) for certainly exclusive pages.
3957 if (!folio_test_ksm(folio)) {
3959 * Note that pte_swp_exclusive() == false for architectures
3960 * without __HAVE_ARCH_PTE_SWP_EXCLUSIVE.
3962 exclusive = pte_swp_exclusive(vmf->orig_pte);
3963 if (folio != swapcache) {
3965 * We have a fresh page that is not exposed to the
3966 * swapcache -> certainly exclusive.
3969 } else if (exclusive && folio_test_writeback(folio) &&
3970 data_race(si->flags & SWP_STABLE_WRITES)) {
3972 * This is tricky: not all swap backends support
3973 * concurrent page modifications while under writeback.
3975 * So if we stumble over such a page in the swapcache
3976 * we must not set the page exclusive, otherwise we can
3977 * map it writable without further checks and modify it
3978 * while still under writeback.
3980 * For these problematic swap backends, simply drop the
3981 * exclusive marker: this is perfectly fine as we start
3982 * writeback only if we fully unmapped the page and
3983 * there are no unexpected references on the page after
3984 * unmapping succeeded. After fully unmapped, no
3985 * further GUP references (FOLL_GET and FOLL_PIN) can
3986 * appear, so dropping the exclusive marker and mapping
3987 * it only R/O is fine.
3994 * Some architectures may have to restore extra metadata to the page
3995 * when reading from swap. This metadata may be indexed by swap entry
3996 * so this must be called before swap_free().
3998 arch_swap_restore(entry, folio);
4001 * Remove the swap entry and conditionally try to free up the swapcache.
4002 * We're already holding a reference on the page but haven't mapped it
4006 if (should_try_to_free_swap(folio, vma, vmf->flags))
4007 folio_free_swap(folio);
4009 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
4010 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
4011 pte = mk_pte(page, vma->vm_page_prot);
4014 * Same logic as in do_wp_page(); however, optimize for pages that are
4015 * certainly not shared either because we just allocated them without
4016 * exposing them to the swapcache or because the swap entry indicates
4019 if (!folio_test_ksm(folio) &&
4020 (exclusive || folio_ref_count(folio) == 1)) {
4021 if (vmf->flags & FAULT_FLAG_WRITE) {
4022 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
4023 vmf->flags &= ~FAULT_FLAG_WRITE;
4024 ret |= VM_FAULT_WRITE;
4026 rmap_flags |= RMAP_EXCLUSIVE;
4028 flush_icache_page(vma, page);
4029 if (pte_swp_soft_dirty(vmf->orig_pte))
4030 pte = pte_mksoft_dirty(pte);
4031 if (pte_swp_uffd_wp(vmf->orig_pte)) {
4032 pte = pte_mkuffd_wp(pte);
4033 pte = pte_wrprotect(pte);
4035 vmf->orig_pte = pte;
4037 /* ksm created a completely new copy */
4038 if (unlikely(folio != swapcache && swapcache)) {
4039 page_add_new_anon_rmap(page, vma, vmf->address);
4040 folio_add_lru_vma(folio, vma);
4042 page_add_anon_rmap(page, vma, vmf->address, rmap_flags);
4045 VM_BUG_ON(!folio_test_anon(folio) ||
4046 (pte_write(pte) && !PageAnonExclusive(page)));
4047 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
4048 arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
4050 folio_unlock(folio);
4051 if (folio != swapcache && swapcache) {
4053 * Hold the lock to avoid the swap entry to be reused
4054 * until we take the PT lock for the pte_same() check
4055 * (to avoid false positives from pte_same). For
4056 * further safety release the lock after the swap_free
4057 * so that the swap count won't change under a
4058 * parallel locked swapcache.
4060 folio_unlock(swapcache);
4061 folio_put(swapcache);
4064 if (vmf->flags & FAULT_FLAG_WRITE) {
4065 ret |= do_wp_page(vmf);
4066 if (ret & VM_FAULT_ERROR)
4067 ret &= VM_FAULT_ERROR;
4071 /* No need to invalidate - it was non-present before */
4072 update_mmu_cache(vma, vmf->address, vmf->pte);
4074 pte_unmap_unlock(vmf->pte, vmf->ptl);
4077 put_swap_device(si);
4080 pte_unmap_unlock(vmf->pte, vmf->ptl);
4082 folio_unlock(folio);
4085 if (folio != swapcache && swapcache) {
4086 folio_unlock(swapcache);
4087 folio_put(swapcache);
4090 put_swap_device(si);
4095 * We enter with non-exclusive mmap_lock (to exclude vma changes,
4096 * but allow concurrent faults), and pte mapped but not yet locked.
4097 * We return with mmap_lock still held, but pte unmapped and unlocked.
4099 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
4101 struct vm_area_struct *vma = vmf->vma;
4106 /* File mapping without ->vm_ops ? */
4107 if (vma->vm_flags & VM_SHARED)
4108 return VM_FAULT_SIGBUS;
4111 * Use pte_alloc() instead of pte_alloc_map(). We can't run
4112 * pte_offset_map() on pmds where a huge pmd might be created
4113 * from a different thread.
4115 * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
4116 * parallel threads are excluded by other means.
4118 * Here we only have mmap_read_lock(mm).
4120 if (pte_alloc(vma->vm_mm, vmf->pmd))
4121 return VM_FAULT_OOM;
4123 /* See comment in handle_pte_fault() */
4124 if (unlikely(pmd_trans_unstable(vmf->pmd)))
4127 /* Use the zero-page for reads */
4128 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
4129 !mm_forbids_zeropage(vma->vm_mm)) {
4130 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
4131 vma->vm_page_prot));
4132 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4133 vmf->address, &vmf->ptl);
4134 if (!pte_none(*vmf->pte)) {
4135 update_mmu_tlb(vma, vmf->address, vmf->pte);
4138 ret = check_stable_address_space(vma->vm_mm);
4141 /* Deliver the page fault to userland, check inside PT lock */
4142 if (userfaultfd_missing(vma)) {
4143 pte_unmap_unlock(vmf->pte, vmf->ptl);
4144 return handle_userfault(vmf, VM_UFFD_MISSING);
4149 /* Allocate our own private page. */
4150 if (unlikely(anon_vma_prepare(vma)))
4152 page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
4156 if (mem_cgroup_charge(page_folio(page), vma->vm_mm, GFP_KERNEL))
4158 cgroup_throttle_swaprate(page, GFP_KERNEL);
4161 * The memory barrier inside __SetPageUptodate makes sure that
4162 * preceding stores to the page contents become visible before
4163 * the set_pte_at() write.
4165 __SetPageUptodate(page);
4167 entry = mk_pte(page, vma->vm_page_prot);
4168 entry = pte_sw_mkyoung(entry);
4169 if (vma->vm_flags & VM_WRITE)
4170 entry = pte_mkwrite(pte_mkdirty(entry));
4172 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
4174 if (!pte_none(*vmf->pte)) {
4175 update_mmu_tlb(vma, vmf->address, vmf->pte);
4179 ret = check_stable_address_space(vma->vm_mm);
4183 /* Deliver the page fault to userland, check inside PT lock */
4184 if (userfaultfd_missing(vma)) {
4185 pte_unmap_unlock(vmf->pte, vmf->ptl);
4187 return handle_userfault(vmf, VM_UFFD_MISSING);
4190 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
4191 page_add_new_anon_rmap(page, vma, vmf->address);
4192 lru_cache_add_inactive_or_unevictable(page, vma);
4194 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
4196 /* No need to invalidate - it was non-present before */
4197 update_mmu_cache(vma, vmf->address, vmf->pte);
4199 pte_unmap_unlock(vmf->pte, vmf->ptl);
4207 return VM_FAULT_OOM;
4211 * The mmap_lock must have been held on entry, and may have been
4212 * released depending on flags and vma->vm_ops->fault() return value.
4213 * See filemap_fault() and __lock_page_retry().
4215 static vm_fault_t __do_fault(struct vm_fault *vmf)
4217 struct vm_area_struct *vma = vmf->vma;
4221 * Preallocate pte before we take page_lock because this might lead to
4222 * deadlocks for memcg reclaim which waits for pages under writeback:
4224 * SetPageWriteback(A)
4230 * wait_on_page_writeback(A)
4231 * SetPageWriteback(B)
4233 * # flush A, B to clear the writeback
4235 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
4236 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
4237 if (!vmf->prealloc_pte)
4238 return VM_FAULT_OOM;
4241 ret = vma->vm_ops->fault(vmf);
4242 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
4243 VM_FAULT_DONE_COW)))
4246 if (unlikely(PageHWPoison(vmf->page))) {
4247 struct page *page = vmf->page;
4248 vm_fault_t poisonret = VM_FAULT_HWPOISON;
4249 if (ret & VM_FAULT_LOCKED) {
4250 if (page_mapped(page))
4251 unmap_mapping_pages(page_mapping(page),
4252 page->index, 1, false);
4253 /* Retry if a clean page was removed from the cache. */
4254 if (invalidate_inode_page(page))
4255 poisonret = VM_FAULT_NOPAGE;
4263 if (unlikely(!(ret & VM_FAULT_LOCKED)))
4264 lock_page(vmf->page);
4266 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
4271 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4272 static void deposit_prealloc_pte(struct vm_fault *vmf)
4274 struct vm_area_struct *vma = vmf->vma;
4276 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
4278 * We are going to consume the prealloc table,
4279 * count that as nr_ptes.
4281 mm_inc_nr_ptes(vma->vm_mm);
4282 vmf->prealloc_pte = NULL;
4285 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
4287 struct vm_area_struct *vma = vmf->vma;
4288 bool write = vmf->flags & FAULT_FLAG_WRITE;
4289 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
4292 vm_fault_t ret = VM_FAULT_FALLBACK;
4294 if (!transhuge_vma_suitable(vma, haddr))
4297 page = compound_head(page);
4298 if (compound_order(page) != HPAGE_PMD_ORDER)
4302 * Just backoff if any subpage of a THP is corrupted otherwise
4303 * the corrupted page may mapped by PMD silently to escape the
4304 * check. This kind of THP just can be PTE mapped. Access to
4305 * the corrupted subpage should trigger SIGBUS as expected.
4307 if (unlikely(PageHasHWPoisoned(page)))
4311 * Archs like ppc64 need additional space to store information
4312 * related to pte entry. Use the preallocated table for that.
4314 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
4315 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
4316 if (!vmf->prealloc_pte)
4317 return VM_FAULT_OOM;
4320 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
4321 if (unlikely(!pmd_none(*vmf->pmd)))
4324 for (i = 0; i < HPAGE_PMD_NR; i++)
4325 flush_icache_page(vma, page + i);
4327 entry = mk_huge_pmd(page, vma->vm_page_prot);
4329 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
4331 add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
4332 page_add_file_rmap(page, vma, true);
4335 * deposit and withdraw with pmd lock held
4337 if (arch_needs_pgtable_deposit())
4338 deposit_prealloc_pte(vmf);
4340 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
4342 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
4344 /* fault is handled */
4346 count_vm_event(THP_FILE_MAPPED);
4348 spin_unlock(vmf->ptl);
4352 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
4354 return VM_FAULT_FALLBACK;
4358 void do_set_pte(struct vm_fault *vmf, struct page *page, unsigned long addr)
4360 struct vm_area_struct *vma = vmf->vma;
4361 bool uffd_wp = pte_marker_uffd_wp(vmf->orig_pte);
4362 bool write = vmf->flags & FAULT_FLAG_WRITE;
4363 bool prefault = vmf->address != addr;
4366 flush_icache_page(vma, page);
4367 entry = mk_pte(page, vma->vm_page_prot);
4369 if (prefault && arch_wants_old_prefaulted_pte())
4370 entry = pte_mkold(entry);
4372 entry = pte_sw_mkyoung(entry);
4375 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
4376 if (unlikely(uffd_wp))
4377 entry = pte_mkuffd_wp(pte_wrprotect(entry));
4378 /* copy-on-write page */
4379 if (write && !(vma->vm_flags & VM_SHARED)) {
4380 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
4381 page_add_new_anon_rmap(page, vma, addr);
4382 lru_cache_add_inactive_or_unevictable(page, vma);
4384 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
4385 page_add_file_rmap(page, vma, false);
4387 set_pte_at(vma->vm_mm, addr, vmf->pte, entry);
4390 static bool vmf_pte_changed(struct vm_fault *vmf)
4392 if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)
4393 return !pte_same(*vmf->pte, vmf->orig_pte);
4395 return !pte_none(*vmf->pte);
4399 * finish_fault - finish page fault once we have prepared the page to fault
4401 * @vmf: structure describing the fault
4403 * This function handles all that is needed to finish a page fault once the
4404 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
4405 * given page, adds reverse page mapping, handles memcg charges and LRU
4408 * The function expects the page to be locked and on success it consumes a
4409 * reference of a page being mapped (for the PTE which maps it).
4411 * Return: %0 on success, %VM_FAULT_ code in case of error.
4413 vm_fault_t finish_fault(struct vm_fault *vmf)
4415 struct vm_area_struct *vma = vmf->vma;
4419 /* Did we COW the page? */
4420 if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED))
4421 page = vmf->cow_page;
4426 * check even for read faults because we might have lost our CoWed
4429 if (!(vma->vm_flags & VM_SHARED)) {
4430 ret = check_stable_address_space(vma->vm_mm);
4435 if (pmd_none(*vmf->pmd)) {
4436 if (PageTransCompound(page)) {
4437 ret = do_set_pmd(vmf, page);
4438 if (ret != VM_FAULT_FALLBACK)
4442 if (vmf->prealloc_pte)
4443 pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte);
4444 else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd)))
4445 return VM_FAULT_OOM;
4449 * See comment in handle_pte_fault() for how this scenario happens, we
4450 * need to return NOPAGE so that we drop this page.
4452 if (pmd_devmap_trans_unstable(vmf->pmd))
4453 return VM_FAULT_NOPAGE;
4455 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4456 vmf->address, &vmf->ptl);
4458 /* Re-check under ptl */
4459 if (likely(!vmf_pte_changed(vmf))) {
4460 do_set_pte(vmf, page, vmf->address);
4462 /* no need to invalidate: a not-present page won't be cached */
4463 update_mmu_cache(vma, vmf->address, vmf->pte);
4467 update_mmu_tlb(vma, vmf->address, vmf->pte);
4468 ret = VM_FAULT_NOPAGE;
4471 pte_unmap_unlock(vmf->pte, vmf->ptl);
4475 static unsigned long fault_around_bytes __read_mostly =
4476 rounddown_pow_of_two(65536);
4478 #ifdef CONFIG_DEBUG_FS
4479 static int fault_around_bytes_get(void *data, u64 *val)
4481 *val = fault_around_bytes;
4486 * fault_around_bytes must be rounded down to the nearest page order as it's
4487 * what do_fault_around() expects to see.
4489 static int fault_around_bytes_set(void *data, u64 val)
4491 if (val / PAGE_SIZE > PTRS_PER_PTE)
4493 if (val > PAGE_SIZE)
4494 fault_around_bytes = rounddown_pow_of_two(val);
4496 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
4499 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
4500 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
4502 static int __init fault_around_debugfs(void)
4504 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
4505 &fault_around_bytes_fops);
4508 late_initcall(fault_around_debugfs);
4512 * do_fault_around() tries to map few pages around the fault address. The hope
4513 * is that the pages will be needed soon and this will lower the number of
4516 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
4517 * not ready to be mapped: not up-to-date, locked, etc.
4519 * This function doesn't cross the VMA boundaries, in order to call map_pages()
4522 * fault_around_bytes defines how many bytes we'll try to map.
4523 * do_fault_around() expects it to be set to a power of two less than or equal
4526 * The virtual address of the area that we map is naturally aligned to
4527 * fault_around_bytes rounded down to the machine page size
4528 * (and therefore to page order). This way it's easier to guarantee
4529 * that we don't cross page table boundaries.
4531 static vm_fault_t do_fault_around(struct vm_fault *vmf)
4533 unsigned long address = vmf->address, nr_pages, mask;
4534 pgoff_t start_pgoff = vmf->pgoff;
4538 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
4539 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
4541 address = max(address & mask, vmf->vma->vm_start);
4542 off = ((vmf->address - address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
4546 * end_pgoff is either the end of the page table, the end of
4547 * the vma or nr_pages from start_pgoff, depending what is nearest.
4549 end_pgoff = start_pgoff -
4550 ((address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
4552 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
4553 start_pgoff + nr_pages - 1);
4555 if (pmd_none(*vmf->pmd)) {
4556 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
4557 if (!vmf->prealloc_pte)
4558 return VM_FAULT_OOM;
4561 return vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
4564 /* Return true if we should do read fault-around, false otherwise */
4565 static inline bool should_fault_around(struct vm_fault *vmf)
4567 /* No ->map_pages? No way to fault around... */
4568 if (!vmf->vma->vm_ops->map_pages)
4571 if (uffd_disable_fault_around(vmf->vma))
4574 return fault_around_bytes >> PAGE_SHIFT > 1;
4577 static vm_fault_t do_read_fault(struct vm_fault *vmf)
4582 * Let's call ->map_pages() first and use ->fault() as fallback
4583 * if page by the offset is not ready to be mapped (cold cache or
4586 if (should_fault_around(vmf)) {
4587 ret = do_fault_around(vmf);
4592 ret = __do_fault(vmf);
4593 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4596 ret |= finish_fault(vmf);
4597 unlock_page(vmf->page);
4598 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4599 put_page(vmf->page);
4603 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
4605 struct vm_area_struct *vma = vmf->vma;
4608 if (unlikely(anon_vma_prepare(vma)))
4609 return VM_FAULT_OOM;
4611 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
4613 return VM_FAULT_OOM;
4615 if (mem_cgroup_charge(page_folio(vmf->cow_page), vma->vm_mm,
4617 put_page(vmf->cow_page);
4618 return VM_FAULT_OOM;
4620 cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL);
4622 ret = __do_fault(vmf);
4623 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4625 if (ret & VM_FAULT_DONE_COW)
4628 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
4629 __SetPageUptodate(vmf->cow_page);
4631 ret |= finish_fault(vmf);
4632 unlock_page(vmf->page);
4633 put_page(vmf->page);
4634 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4638 put_page(vmf->cow_page);
4642 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
4644 struct vm_area_struct *vma = vmf->vma;
4645 vm_fault_t ret, tmp;
4647 ret = __do_fault(vmf);
4648 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4652 * Check if the backing address space wants to know that the page is
4653 * about to become writable
4655 if (vma->vm_ops->page_mkwrite) {
4656 unlock_page(vmf->page);
4657 tmp = do_page_mkwrite(vmf);
4658 if (unlikely(!tmp ||
4659 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
4660 put_page(vmf->page);
4665 ret |= finish_fault(vmf);
4666 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
4668 unlock_page(vmf->page);
4669 put_page(vmf->page);
4673 ret |= fault_dirty_shared_page(vmf);
4678 * We enter with non-exclusive mmap_lock (to exclude vma changes,
4679 * but allow concurrent faults).
4680 * The mmap_lock may have been released depending on flags and our
4681 * return value. See filemap_fault() and __folio_lock_or_retry().
4682 * If mmap_lock is released, vma may become invalid (for example
4683 * by other thread calling munmap()).
4685 static vm_fault_t do_fault(struct vm_fault *vmf)
4687 struct vm_area_struct *vma = vmf->vma;
4688 struct mm_struct *vm_mm = vma->vm_mm;
4692 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
4694 if (!vma->vm_ops->fault) {
4696 * If we find a migration pmd entry or a none pmd entry, which
4697 * should never happen, return SIGBUS
4699 if (unlikely(!pmd_present(*vmf->pmd)))
4700 ret = VM_FAULT_SIGBUS;
4702 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
4707 * Make sure this is not a temporary clearing of pte
4708 * by holding ptl and checking again. A R/M/W update
4709 * of pte involves: take ptl, clearing the pte so that
4710 * we don't have concurrent modification by hardware
4711 * followed by an update.
4713 if (unlikely(pte_none(*vmf->pte)))
4714 ret = VM_FAULT_SIGBUS;
4716 ret = VM_FAULT_NOPAGE;
4718 pte_unmap_unlock(vmf->pte, vmf->ptl);
4720 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
4721 ret = do_read_fault(vmf);
4722 else if (!(vma->vm_flags & VM_SHARED))
4723 ret = do_cow_fault(vmf);
4725 ret = do_shared_fault(vmf);
4727 /* preallocated pagetable is unused: free it */
4728 if (vmf->prealloc_pte) {
4729 pte_free(vm_mm, vmf->prealloc_pte);
4730 vmf->prealloc_pte = NULL;
4735 int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
4736 unsigned long addr, int page_nid, int *flags)
4740 count_vm_numa_event(NUMA_HINT_FAULTS);
4741 if (page_nid == numa_node_id()) {
4742 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
4743 *flags |= TNF_FAULT_LOCAL;
4746 return mpol_misplaced(page, vma, addr);
4749 static vm_fault_t do_numa_page(struct vm_fault *vmf)
4751 struct vm_area_struct *vma = vmf->vma;
4752 struct page *page = NULL;
4753 int page_nid = NUMA_NO_NODE;
4757 bool was_writable = pte_savedwrite(vmf->orig_pte);
4761 * The "pte" at this point cannot be used safely without
4762 * validation through pte_unmap_same(). It's of NUMA type but
4763 * the pfn may be screwed if the read is non atomic.
4765 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
4766 spin_lock(vmf->ptl);
4767 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4768 pte_unmap_unlock(vmf->pte, vmf->ptl);
4772 /* Get the normal PTE */
4773 old_pte = ptep_get(vmf->pte);
4774 pte = pte_modify(old_pte, vma->vm_page_prot);
4776 page = vm_normal_page(vma, vmf->address, pte);
4777 if (!page || is_zone_device_page(page))
4780 /* TODO: handle PTE-mapped THP */
4781 if (PageCompound(page))
4785 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
4786 * much anyway since they can be in shared cache state. This misses
4787 * the case where a mapping is writable but the process never writes
4788 * to it but pte_write gets cleared during protection updates and
4789 * pte_dirty has unpredictable behaviour between PTE scan updates,
4790 * background writeback, dirty balancing and application behaviour.
4793 flags |= TNF_NO_GROUP;
4796 * Flag if the page is shared between multiple address spaces. This
4797 * is later used when determining whether to group tasks together
4799 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
4800 flags |= TNF_SHARED;
4802 page_nid = page_to_nid(page);
4804 * For memory tiering mode, cpupid of slow memory page is used
4805 * to record page access time. So use default value.
4807 if ((sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
4808 !node_is_toptier(page_nid))
4809 last_cpupid = (-1 & LAST_CPUPID_MASK);
4811 last_cpupid = page_cpupid_last(page);
4812 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
4814 if (target_nid == NUMA_NO_NODE) {
4818 pte_unmap_unlock(vmf->pte, vmf->ptl);
4820 /* Migrate to the requested node */
4821 if (migrate_misplaced_page(page, vma, target_nid)) {
4822 page_nid = target_nid;
4823 flags |= TNF_MIGRATED;
4825 flags |= TNF_MIGRATE_FAIL;
4826 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4827 spin_lock(vmf->ptl);
4828 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4829 pte_unmap_unlock(vmf->pte, vmf->ptl);
4836 if (page_nid != NUMA_NO_NODE)
4837 task_numa_fault(last_cpupid, page_nid, 1, flags);
4841 * Make it present again, depending on how arch implements
4842 * non-accessible ptes, some can allow access by kernel mode.
4844 old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte);
4845 pte = pte_modify(old_pte, vma->vm_page_prot);
4846 pte = pte_mkyoung(pte);
4848 pte = pte_mkwrite(pte);
4849 ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte);
4850 update_mmu_cache(vma, vmf->address, vmf->pte);
4851 pte_unmap_unlock(vmf->pte, vmf->ptl);
4855 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4857 if (vma_is_anonymous(vmf->vma))
4858 return do_huge_pmd_anonymous_page(vmf);
4859 if (vmf->vma->vm_ops->huge_fault)
4860 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4861 return VM_FAULT_FALLBACK;
4864 /* `inline' is required to avoid gcc 4.1.2 build error */
4865 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf)
4867 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
4869 if (vma_is_anonymous(vmf->vma)) {
4870 if (likely(!unshare) &&
4871 userfaultfd_huge_pmd_wp(vmf->vma, vmf->orig_pmd))
4872 return handle_userfault(vmf, VM_UFFD_WP);
4873 return do_huge_pmd_wp_page(vmf);
4875 if (vmf->vma->vm_ops->huge_fault) {
4876 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4878 if (!(ret & VM_FAULT_FALLBACK))
4882 /* COW or write-notify handled on pte level: split pmd. */
4883 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4885 return VM_FAULT_FALLBACK;
4888 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4890 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
4891 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4892 /* No support for anonymous transparent PUD pages yet */
4893 if (vma_is_anonymous(vmf->vma))
4894 return VM_FAULT_FALLBACK;
4895 if (vmf->vma->vm_ops->huge_fault)
4896 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4897 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4898 return VM_FAULT_FALLBACK;
4901 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4903 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
4904 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4905 /* No support for anonymous transparent PUD pages yet */
4906 if (vma_is_anonymous(vmf->vma))
4908 if (vmf->vma->vm_ops->huge_fault) {
4909 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4911 if (!(ret & VM_FAULT_FALLBACK))
4915 /* COW or write-notify not handled on PUD level: split pud.*/
4916 __split_huge_pud(vmf->vma, vmf->pud, vmf->address);
4917 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
4918 return VM_FAULT_FALLBACK;
4922 * These routines also need to handle stuff like marking pages dirty
4923 * and/or accessed for architectures that don't do it in hardware (most
4924 * RISC architectures). The early dirtying is also good on the i386.
4926 * There is also a hook called "update_mmu_cache()" that architectures
4927 * with external mmu caches can use to update those (ie the Sparc or
4928 * PowerPC hashed page tables that act as extended TLBs).
4930 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
4931 * concurrent faults).
4933 * The mmap_lock may have been released depending on flags and our return value.
4934 * See filemap_fault() and __folio_lock_or_retry().
4936 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4940 if (unlikely(pmd_none(*vmf->pmd))) {
4942 * Leave __pte_alloc() until later: because vm_ops->fault may
4943 * want to allocate huge page, and if we expose page table
4944 * for an instant, it will be difficult to retract from
4945 * concurrent faults and from rmap lookups.
4948 vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID;
4951 * If a huge pmd materialized under us just retry later. Use
4952 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead
4953 * of pmd_trans_huge() to ensure the pmd didn't become
4954 * pmd_trans_huge under us and then back to pmd_none, as a
4955 * result of MADV_DONTNEED running immediately after a huge pmd
4956 * fault in a different thread of this mm, in turn leading to a
4957 * misleading pmd_trans_huge() retval. All we have to ensure is
4958 * that it is a regular pmd that we can walk with
4959 * pte_offset_map() and we can do that through an atomic read
4960 * in C, which is what pmd_trans_unstable() provides.
4962 if (pmd_devmap_trans_unstable(vmf->pmd))
4965 * A regular pmd is established and it can't morph into a huge
4966 * pmd from under us anymore at this point because we hold the
4967 * mmap_lock read mode and khugepaged takes it in write mode.
4968 * So now it's safe to run pte_offset_map().
4970 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4971 vmf->orig_pte = *vmf->pte;
4972 vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID;
4975 * some architectures can have larger ptes than wordsize,
4976 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4977 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4978 * accesses. The code below just needs a consistent view
4979 * for the ifs and we later double check anyway with the
4980 * ptl lock held. So here a barrier will do.
4983 if (pte_none(vmf->orig_pte)) {
4984 pte_unmap(vmf->pte);
4990 if (vma_is_anonymous(vmf->vma))
4991 return do_anonymous_page(vmf);
4993 return do_fault(vmf);
4996 if (!pte_present(vmf->orig_pte))
4997 return do_swap_page(vmf);
4999 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
5000 return do_numa_page(vmf);
5002 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
5003 spin_lock(vmf->ptl);
5004 entry = vmf->orig_pte;
5005 if (unlikely(!pte_same(*vmf->pte, entry))) {
5006 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
5009 if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
5010 if (!pte_write(entry))
5011 return do_wp_page(vmf);
5012 else if (likely(vmf->flags & FAULT_FLAG_WRITE))
5013 entry = pte_mkdirty(entry);
5015 entry = pte_mkyoung(entry);
5016 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
5017 vmf->flags & FAULT_FLAG_WRITE)) {
5018 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
5020 /* Skip spurious TLB flush for retried page fault */
5021 if (vmf->flags & FAULT_FLAG_TRIED)
5024 * This is needed only for protection faults but the arch code
5025 * is not yet telling us if this is a protection fault or not.
5026 * This still avoids useless tlb flushes for .text page faults
5029 if (vmf->flags & FAULT_FLAG_WRITE)
5030 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
5033 pte_unmap_unlock(vmf->pte, vmf->ptl);
5038 * By the time we get here, we already hold the mm semaphore
5040 * The mmap_lock may have been released depending on flags and our
5041 * return value. See filemap_fault() and __folio_lock_or_retry().
5043 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
5044 unsigned long address, unsigned int flags)
5046 struct vm_fault vmf = {
5048 .address = address & PAGE_MASK,
5049 .real_address = address,
5051 .pgoff = linear_page_index(vma, address),
5052 .gfp_mask = __get_fault_gfp_mask(vma),
5054 struct mm_struct *mm = vma->vm_mm;
5055 unsigned long vm_flags = vma->vm_flags;
5060 pgd = pgd_offset(mm, address);
5061 p4d = p4d_alloc(mm, pgd, address);
5063 return VM_FAULT_OOM;
5065 vmf.pud = pud_alloc(mm, p4d, address);
5067 return VM_FAULT_OOM;
5069 if (pud_none(*vmf.pud) &&
5070 hugepage_vma_check(vma, vm_flags, false, true, true)) {
5071 ret = create_huge_pud(&vmf);
5072 if (!(ret & VM_FAULT_FALLBACK))
5075 pud_t orig_pud = *vmf.pud;
5078 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
5081 * TODO once we support anonymous PUDs: NUMA case and
5082 * FAULT_FLAG_UNSHARE handling.
5084 if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) {
5085 ret = wp_huge_pud(&vmf, orig_pud);
5086 if (!(ret & VM_FAULT_FALLBACK))
5089 huge_pud_set_accessed(&vmf, orig_pud);
5095 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
5097 return VM_FAULT_OOM;
5099 /* Huge pud page fault raced with pmd_alloc? */
5100 if (pud_trans_unstable(vmf.pud))
5103 if (pmd_none(*vmf.pmd) &&
5104 hugepage_vma_check(vma, vm_flags, false, true, true)) {
5105 ret = create_huge_pmd(&vmf);
5106 if (!(ret & VM_FAULT_FALLBACK))
5109 vmf.orig_pmd = *vmf.pmd;
5112 if (unlikely(is_swap_pmd(vmf.orig_pmd))) {
5113 VM_BUG_ON(thp_migration_supported() &&
5114 !is_pmd_migration_entry(vmf.orig_pmd));
5115 if (is_pmd_migration_entry(vmf.orig_pmd))
5116 pmd_migration_entry_wait(mm, vmf.pmd);
5119 if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) {
5120 if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma))
5121 return do_huge_pmd_numa_page(&vmf);
5123 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
5124 !pmd_write(vmf.orig_pmd)) {
5125 ret = wp_huge_pmd(&vmf);
5126 if (!(ret & VM_FAULT_FALLBACK))
5129 huge_pmd_set_accessed(&vmf);
5135 return handle_pte_fault(&vmf);
5139 * mm_account_fault - Do page fault accounting
5141 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting
5142 * of perf event counters, but we'll still do the per-task accounting to
5143 * the task who triggered this page fault.
5144 * @address: the faulted address.
5145 * @flags: the fault flags.
5146 * @ret: the fault retcode.
5148 * This will take care of most of the page fault accounting. Meanwhile, it
5149 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
5150 * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
5151 * still be in per-arch page fault handlers at the entry of page fault.
5153 static inline void mm_account_fault(struct pt_regs *regs,
5154 unsigned long address, unsigned int flags,
5160 * We don't do accounting for some specific faults:
5162 * - Unsuccessful faults (e.g. when the address wasn't valid). That
5163 * includes arch_vma_access_permitted() failing before reaching here.
5164 * So this is not a "this many hardware page faults" counter. We
5165 * should use the hw profiling for that.
5167 * - Incomplete faults (VM_FAULT_RETRY). They will only be counted
5168 * once they're completed.
5170 if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY))
5174 * We define the fault as a major fault when the final successful fault
5175 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
5176 * handle it immediately previously).
5178 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
5186 * If the fault is done for GUP, regs will be NULL. We only do the
5187 * accounting for the per thread fault counters who triggered the
5188 * fault, and we skip the perf event updates.
5194 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
5196 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
5199 #ifdef CONFIG_LRU_GEN
5200 static void lru_gen_enter_fault(struct vm_area_struct *vma)
5202 /* the LRU algorithm doesn't apply to sequential or random reads */
5203 current->in_lru_fault = !(vma->vm_flags & (VM_SEQ_READ | VM_RAND_READ));
5206 static void lru_gen_exit_fault(void)
5208 current->in_lru_fault = false;
5211 static void lru_gen_enter_fault(struct vm_area_struct *vma)
5215 static void lru_gen_exit_fault(void)
5218 #endif /* CONFIG_LRU_GEN */
5221 * By the time we get here, we already hold the mm semaphore
5223 * The mmap_lock may have been released depending on flags and our
5224 * return value. See filemap_fault() and __folio_lock_or_retry().
5226 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
5227 unsigned int flags, struct pt_regs *regs)
5231 __set_current_state(TASK_RUNNING);
5233 count_vm_event(PGFAULT);
5234 count_memcg_event_mm(vma->vm_mm, PGFAULT);
5236 /* do counter updates before entering really critical section. */
5237 check_sync_rss_stat(current);
5239 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
5240 flags & FAULT_FLAG_INSTRUCTION,
5241 flags & FAULT_FLAG_REMOTE))
5242 return VM_FAULT_SIGSEGV;
5245 * Enable the memcg OOM handling for faults triggered in user
5246 * space. Kernel faults are handled more gracefully.
5248 if (flags & FAULT_FLAG_USER)
5249 mem_cgroup_enter_user_fault();
5251 lru_gen_enter_fault(vma);
5253 if (unlikely(is_vm_hugetlb_page(vma)))
5254 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
5256 ret = __handle_mm_fault(vma, address, flags);
5258 lru_gen_exit_fault();
5260 if (flags & FAULT_FLAG_USER) {
5261 mem_cgroup_exit_user_fault();
5263 * The task may have entered a memcg OOM situation but
5264 * if the allocation error was handled gracefully (no
5265 * VM_FAULT_OOM), there is no need to kill anything.
5266 * Just clean up the OOM state peacefully.
5268 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
5269 mem_cgroup_oom_synchronize(false);
5272 mm_account_fault(regs, address, flags, ret);
5276 EXPORT_SYMBOL_GPL(handle_mm_fault);
5278 #ifdef CONFIG_LOCK_MM_AND_FIND_VMA
5279 #include <linux/extable.h>
5281 static inline bool get_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs)
5283 /* Even if this succeeds, make it clear we *might* have slept */
5284 if (likely(mmap_read_trylock(mm))) {
5289 if (regs && !user_mode(regs)) {
5290 unsigned long ip = instruction_pointer(regs);
5291 if (!search_exception_tables(ip))
5295 return !mmap_read_lock_killable(mm);
5298 static inline bool mmap_upgrade_trylock(struct mm_struct *mm)
5301 * We don't have this operation yet.
5303 * It should be easy enough to do: it's basically a
5304 * atomic_long_try_cmpxchg_acquire()
5305 * from RWSEM_READER_BIAS -> RWSEM_WRITER_LOCKED, but
5306 * it also needs the proper lockdep magic etc.
5311 static inline bool upgrade_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs)
5313 mmap_read_unlock(mm);
5314 if (regs && !user_mode(regs)) {
5315 unsigned long ip = instruction_pointer(regs);
5316 if (!search_exception_tables(ip))
5319 return !mmap_write_lock_killable(mm);
5323 * Helper for page fault handling.
5325 * This is kind of equivalend to "mmap_read_lock()" followed
5326 * by "find_extend_vma()", except it's a lot more careful about
5327 * the locking (and will drop the lock on failure).
5329 * For example, if we have a kernel bug that causes a page
5330 * fault, we don't want to just use mmap_read_lock() to get
5331 * the mm lock, because that would deadlock if the bug were
5332 * to happen while we're holding the mm lock for writing.
5334 * So this checks the exception tables on kernel faults in
5335 * order to only do this all for instructions that are actually
5336 * expected to fault.
5338 * We can also actually take the mm lock for writing if we
5339 * need to extend the vma, which helps the VM layer a lot.
5341 struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm,
5342 unsigned long addr, struct pt_regs *regs)
5344 struct vm_area_struct *vma;
5346 if (!get_mmap_lock_carefully(mm, regs))
5349 vma = find_vma(mm, addr);
5350 if (likely(vma && (vma->vm_start <= addr)))
5354 * Well, dang. We might still be successful, but only
5355 * if we can extend a vma to do so.
5357 if (!vma || !(vma->vm_flags & VM_GROWSDOWN)) {
5358 mmap_read_unlock(mm);
5363 * We can try to upgrade the mmap lock atomically,
5364 * in which case we can continue to use the vma
5365 * we already looked up.
5367 * Otherwise we'll have to drop the mmap lock and
5368 * re-take it, and also look up the vma again,
5371 if (!mmap_upgrade_trylock(mm)) {
5372 if (!upgrade_mmap_lock_carefully(mm, regs))
5375 vma = find_vma(mm, addr);
5378 if (vma->vm_start <= addr)
5380 if (!(vma->vm_flags & VM_GROWSDOWN))
5384 if (expand_stack_locked(vma, addr))
5388 mmap_write_downgrade(mm);
5392 mmap_write_unlock(mm);
5397 #ifndef __PAGETABLE_P4D_FOLDED
5399 * Allocate p4d page table.
5400 * We've already handled the fast-path in-line.
5402 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
5404 p4d_t *new = p4d_alloc_one(mm, address);
5408 spin_lock(&mm->page_table_lock);
5409 if (pgd_present(*pgd)) { /* Another has populated it */
5412 smp_wmb(); /* See comment in pmd_install() */
5413 pgd_populate(mm, pgd, new);
5415 spin_unlock(&mm->page_table_lock);
5418 #endif /* __PAGETABLE_P4D_FOLDED */
5420 #ifndef __PAGETABLE_PUD_FOLDED
5422 * Allocate page upper directory.
5423 * We've already handled the fast-path in-line.
5425 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
5427 pud_t *new = pud_alloc_one(mm, address);
5431 spin_lock(&mm->page_table_lock);
5432 if (!p4d_present(*p4d)) {
5434 smp_wmb(); /* See comment in pmd_install() */
5435 p4d_populate(mm, p4d, new);
5436 } else /* Another has populated it */
5438 spin_unlock(&mm->page_table_lock);
5441 #endif /* __PAGETABLE_PUD_FOLDED */
5443 #ifndef __PAGETABLE_PMD_FOLDED
5445 * Allocate page middle directory.
5446 * We've already handled the fast-path in-line.
5448 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
5451 pmd_t *new = pmd_alloc_one(mm, address);
5455 ptl = pud_lock(mm, pud);
5456 if (!pud_present(*pud)) {
5458 smp_wmb(); /* See comment in pmd_install() */
5459 pud_populate(mm, pud, new);
5460 } else { /* Another has populated it */
5466 #endif /* __PAGETABLE_PMD_FOLDED */
5469 * follow_pte - look up PTE at a user virtual address
5470 * @mm: the mm_struct of the target address space
5471 * @address: user virtual address
5472 * @ptepp: location to store found PTE
5473 * @ptlp: location to store the lock for the PTE
5475 * On a successful return, the pointer to the PTE is stored in @ptepp;
5476 * the corresponding lock is taken and its location is stored in @ptlp.
5477 * The contents of the PTE are only stable until @ptlp is released;
5478 * any further use, if any, must be protected against invalidation
5479 * with MMU notifiers.
5481 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore
5482 * should be taken for read.
5484 * KVM uses this function. While it is arguably less bad than ``follow_pfn``,
5485 * it is not a good general-purpose API.
5487 * Return: zero on success, -ve otherwise.
5489 int follow_pte(struct mm_struct *mm, unsigned long address,
5490 pte_t **ptepp, spinlock_t **ptlp)
5498 pgd = pgd_offset(mm, address);
5499 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
5502 p4d = p4d_offset(pgd, address);
5503 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
5506 pud = pud_offset(p4d, address);
5507 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
5510 pmd = pmd_offset(pud, address);
5511 VM_BUG_ON(pmd_trans_huge(*pmd));
5513 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
5516 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
5517 if (!pte_present(*ptep))
5522 pte_unmap_unlock(ptep, *ptlp);
5526 EXPORT_SYMBOL_GPL(follow_pte);
5529 * follow_pfn - look up PFN at a user virtual address
5530 * @vma: memory mapping
5531 * @address: user virtual address
5532 * @pfn: location to store found PFN
5534 * Only IO mappings and raw PFN mappings are allowed.
5536 * This function does not allow the caller to read the permissions
5537 * of the PTE. Do not use it.
5539 * Return: zero and the pfn at @pfn on success, -ve otherwise.
5541 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
5548 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5551 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
5554 *pfn = pte_pfn(*ptep);
5555 pte_unmap_unlock(ptep, ptl);
5558 EXPORT_SYMBOL(follow_pfn);
5560 #ifdef CONFIG_HAVE_IOREMAP_PROT
5561 int follow_phys(struct vm_area_struct *vma,
5562 unsigned long address, unsigned int flags,
5563 unsigned long *prot, resource_size_t *phys)
5569 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5572 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
5576 if ((flags & FOLL_WRITE) && !pte_write(pte))
5579 *prot = pgprot_val(pte_pgprot(pte));
5580 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5584 pte_unmap_unlock(ptep, ptl);
5590 * generic_access_phys - generic implementation for iomem mmap access
5591 * @vma: the vma to access
5592 * @addr: userspace address, not relative offset within @vma
5593 * @buf: buffer to read/write
5594 * @len: length of transfer
5595 * @write: set to FOLL_WRITE when writing, otherwise reading
5597 * This is a generic implementation for &vm_operations_struct.access for an
5598 * iomem mapping. This callback is used by access_process_vm() when the @vma is
5601 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
5602 void *buf, int len, int write)
5604 resource_size_t phys_addr;
5605 unsigned long prot = 0;
5606 void __iomem *maddr;
5609 int offset = offset_in_page(addr);
5612 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5616 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl))
5619 pte_unmap_unlock(ptep, ptl);
5621 prot = pgprot_val(pte_pgprot(pte));
5622 phys_addr = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5624 if ((write & FOLL_WRITE) && !pte_write(pte))
5627 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
5631 if (follow_pte(vma->vm_mm, addr, &ptep, &ptl))
5634 if (!pte_same(pte, *ptep)) {
5635 pte_unmap_unlock(ptep, ptl);
5642 memcpy_toio(maddr + offset, buf, len);
5644 memcpy_fromio(buf, maddr + offset, len);
5646 pte_unmap_unlock(ptep, ptl);
5652 EXPORT_SYMBOL_GPL(generic_access_phys);
5656 * Access another process' address space as given in mm.
5658 int __access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf,
5659 int len, unsigned int gup_flags)
5661 struct vm_area_struct *vma;
5662 void *old_buf = buf;
5663 int write = gup_flags & FOLL_WRITE;
5665 if (mmap_read_lock_killable(mm))
5668 /* We might need to expand the stack to access it */
5669 vma = vma_lookup(mm, addr);
5671 vma = expand_stack(mm, addr);
5676 /* ignore errors, just check how much was successfully transferred */
5678 int bytes, ret, offset;
5680 struct page *page = NULL;
5682 ret = get_user_pages_remote(mm, addr, 1,
5683 gup_flags, &page, &vma, NULL);
5685 #ifndef CONFIG_HAVE_IOREMAP_PROT
5689 * Check if this is a VM_IO | VM_PFNMAP VMA, which
5690 * we can access using slightly different code.
5692 vma = vma_lookup(mm, addr);
5695 if (vma->vm_ops && vma->vm_ops->access)
5696 ret = vma->vm_ops->access(vma, addr, buf,
5704 offset = addr & (PAGE_SIZE-1);
5705 if (bytes > PAGE_SIZE-offset)
5706 bytes = PAGE_SIZE-offset;
5710 copy_to_user_page(vma, page, addr,
5711 maddr + offset, buf, bytes);
5712 set_page_dirty_lock(page);
5714 copy_from_user_page(vma, page, addr,
5715 buf, maddr + offset, bytes);
5724 mmap_read_unlock(mm);
5726 return buf - old_buf;
5730 * access_remote_vm - access another process' address space
5731 * @mm: the mm_struct of the target address space
5732 * @addr: start address to access
5733 * @buf: source or destination buffer
5734 * @len: number of bytes to transfer
5735 * @gup_flags: flags modifying lookup behaviour
5737 * The caller must hold a reference on @mm.
5739 * Return: number of bytes copied from source to destination.
5741 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
5742 void *buf, int len, unsigned int gup_flags)
5744 return __access_remote_vm(mm, addr, buf, len, gup_flags);
5748 * Access another process' address space.
5749 * Source/target buffer must be kernel space,
5750 * Do not walk the page table directly, use get_user_pages
5752 int access_process_vm(struct task_struct *tsk, unsigned long addr,
5753 void *buf, int len, unsigned int gup_flags)
5755 struct mm_struct *mm;
5758 mm = get_task_mm(tsk);
5762 ret = __access_remote_vm(mm, addr, buf, len, gup_flags);
5768 EXPORT_SYMBOL_GPL(access_process_vm);
5771 * Print the name of a VMA.
5773 void print_vma_addr(char *prefix, unsigned long ip)
5775 struct mm_struct *mm = current->mm;
5776 struct vm_area_struct *vma;
5779 * we might be running from an atomic context so we cannot sleep
5781 if (!mmap_read_trylock(mm))
5784 vma = find_vma(mm, ip);
5785 if (vma && vma->vm_file) {
5786 struct file *f = vma->vm_file;
5787 char *buf = (char *)__get_free_page(GFP_NOWAIT);
5791 p = file_path(f, buf, PAGE_SIZE);
5794 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
5796 vma->vm_end - vma->vm_start);
5797 free_page((unsigned long)buf);
5800 mmap_read_unlock(mm);
5803 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5804 void __might_fault(const char *file, int line)
5806 if (pagefault_disabled())
5808 __might_sleep(file, line);
5809 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5811 might_lock_read(¤t->mm->mmap_lock);
5814 EXPORT_SYMBOL(__might_fault);
5817 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
5819 * Process all subpages of the specified huge page with the specified
5820 * operation. The target subpage will be processed last to keep its
5823 static inline void process_huge_page(
5824 unsigned long addr_hint, unsigned int pages_per_huge_page,
5825 void (*process_subpage)(unsigned long addr, int idx, void *arg),
5829 unsigned long addr = addr_hint &
5830 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5832 /* Process target subpage last to keep its cache lines hot */
5834 n = (addr_hint - addr) / PAGE_SIZE;
5835 if (2 * n <= pages_per_huge_page) {
5836 /* If target subpage in first half of huge page */
5839 /* Process subpages at the end of huge page */
5840 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
5842 process_subpage(addr + i * PAGE_SIZE, i, arg);
5845 /* If target subpage in second half of huge page */
5846 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
5847 l = pages_per_huge_page - n;
5848 /* Process subpages at the begin of huge page */
5849 for (i = 0; i < base; i++) {
5851 process_subpage(addr + i * PAGE_SIZE, i, arg);
5855 * Process remaining subpages in left-right-left-right pattern
5856 * towards the target subpage
5858 for (i = 0; i < l; i++) {
5859 int left_idx = base + i;
5860 int right_idx = base + 2 * l - 1 - i;
5863 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
5865 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
5869 static void clear_gigantic_page(struct page *page,
5871 unsigned int pages_per_huge_page)
5877 for (i = 0; i < pages_per_huge_page; i++) {
5878 p = nth_page(page, i);
5880 clear_user_highpage(p, addr + i * PAGE_SIZE);
5884 static void clear_subpage(unsigned long addr, int idx, void *arg)
5886 struct page *page = arg;
5888 clear_user_highpage(page + idx, addr);
5891 void clear_huge_page(struct page *page,
5892 unsigned long addr_hint, unsigned int pages_per_huge_page)
5894 unsigned long addr = addr_hint &
5895 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5897 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5898 clear_gigantic_page(page, addr, pages_per_huge_page);
5902 process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
5905 static void copy_user_gigantic_page(struct page *dst, struct page *src,
5907 struct vm_area_struct *vma,
5908 unsigned int pages_per_huge_page)
5911 struct page *dst_base = dst;
5912 struct page *src_base = src;
5914 for (i = 0; i < pages_per_huge_page; i++) {
5915 dst = nth_page(dst_base, i);
5916 src = nth_page(src_base, i);
5919 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
5923 struct copy_subpage_arg {
5926 struct vm_area_struct *vma;
5929 static void copy_subpage(unsigned long addr, int idx, void *arg)
5931 struct copy_subpage_arg *copy_arg = arg;
5933 copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
5934 addr, copy_arg->vma);
5937 void copy_user_huge_page(struct page *dst, struct page *src,
5938 unsigned long addr_hint, struct vm_area_struct *vma,
5939 unsigned int pages_per_huge_page)
5941 unsigned long addr = addr_hint &
5942 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5943 struct copy_subpage_arg arg = {
5949 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5950 copy_user_gigantic_page(dst, src, addr, vma,
5951 pages_per_huge_page);
5955 process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
5958 long copy_huge_page_from_user(struct page *dst_page,
5959 const void __user *usr_src,
5960 unsigned int pages_per_huge_page,
5961 bool allow_pagefault)
5964 unsigned long i, rc = 0;
5965 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
5966 struct page *subpage;
5968 for (i = 0; i < pages_per_huge_page; i++) {
5969 subpage = nth_page(dst_page, i);
5970 if (allow_pagefault)
5971 page_kaddr = kmap(subpage);
5973 page_kaddr = kmap_atomic(subpage);
5974 rc = copy_from_user(page_kaddr,
5975 usr_src + i * PAGE_SIZE, PAGE_SIZE);
5976 if (allow_pagefault)
5979 kunmap_atomic(page_kaddr);
5981 ret_val -= (PAGE_SIZE - rc);
5985 flush_dcache_page(subpage);
5991 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
5993 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
5995 static struct kmem_cache *page_ptl_cachep;
5997 void __init ptlock_cache_init(void)
5999 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
6003 bool ptlock_alloc(struct page *page)
6007 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
6014 void ptlock_free(struct page *page)
6016 kmem_cache_free(page_ptl_cachep, page->ptl);