4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * demand-loading started 01.12.91 - seems it is high on the list of
9 * things wanted, and it should be easy to implement. - Linus
13 * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
14 * pages started 02.12.91, seems to work. - Linus.
16 * Tested sharing by executing about 30 /bin/sh: under the old kernel it
17 * would have taken more than the 6M I have free, but it worked well as
20 * Also corrected some "invalidate()"s - I wasn't doing enough of them.
24 * Real VM (paging to/from disk) started 18.12.91. Much more work and
25 * thought has to go into this. Oh, well..
26 * 19.12.91 - works, somewhat. Sometimes I get faults, don't know why.
27 * Found it. Everything seems to work now.
28 * 20.12.91 - Ok, making the swap-device changeable like the root.
32 * 05.04.94 - Multi-page memory management added for v1.1.
33 * Idea by Alex Bligh (alex@cconcepts.co.uk)
35 * 16.07.99 - Support of BIGMEM added by Gerhard Wichert, Siemens AG
36 * (Gerhard.Wichert@pdb.siemens.de)
38 * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
41 #include <linux/kernel_stat.h>
43 #include <linux/sched/mm.h>
44 #include <linux/sched/coredump.h>
45 #include <linux/sched/numa_balancing.h>
46 #include <linux/sched/task.h>
47 #include <linux/hugetlb.h>
48 #include <linux/mman.h>
49 #include <linux/swap.h>
50 #include <linux/highmem.h>
51 #include <linux/pagemap.h>
52 #include <linux/memremap.h>
53 #include <linux/ksm.h>
54 #include <linux/rmap.h>
55 #include <linux/export.h>
56 #include <linux/delayacct.h>
57 #include <linux/init.h>
58 #include <linux/pfn_t.h>
59 #include <linux/writeback.h>
60 #include <linux/memcontrol.h>
61 #include <linux/mmu_notifier.h>
62 #include <linux/kallsyms.h>
63 #include <linux/swapops.h>
64 #include <linux/elf.h>
65 #include <linux/gfp.h>
66 #include <linux/migrate.h>
67 #include <linux/string.h>
68 #include <linux/dma-debug.h>
69 #include <linux/debugfs.h>
70 #include <linux/userfaultfd_k.h>
71 #include <linux/dax.h>
72 #include <linux/oom.h>
75 #include <asm/mmu_context.h>
76 #include <asm/pgalloc.h>
77 #include <linux/uaccess.h>
79 #include <asm/tlbflush.h>
80 #include <asm/pgtable.h>
84 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
85 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
88 #ifndef CONFIG_NEED_MULTIPLE_NODES
89 /* use the per-pgdat data instead for discontigmem - mbligh */
90 unsigned long max_mapnr;
91 EXPORT_SYMBOL(max_mapnr);
94 EXPORT_SYMBOL(mem_map);
98 * A number of key systems in x86 including ioremap() rely on the assumption
99 * that high_memory defines the upper bound on direct map memory, then end
100 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and
101 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
105 EXPORT_SYMBOL(high_memory);
108 * Randomize the address space (stacks, mmaps, brk, etc.).
110 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
111 * as ancient (libc5 based) binaries can segfault. )
113 int randomize_va_space __read_mostly =
114 #ifdef CONFIG_COMPAT_BRK
120 #ifndef arch_faults_on_old_pte
121 static inline bool arch_faults_on_old_pte(void)
124 * Those arches which don't have hw access flag feature need to
125 * implement their own helper. By default, "true" means pagefault
126 * will be hit on old pte.
132 static int __init disable_randmaps(char *s)
134 randomize_va_space = 0;
137 __setup("norandmaps", disable_randmaps);
139 unsigned long zero_pfn __read_mostly;
140 EXPORT_SYMBOL(zero_pfn);
142 unsigned long highest_memmap_pfn __read_mostly;
145 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
147 static int __init init_zero_pfn(void)
149 zero_pfn = page_to_pfn(ZERO_PAGE(0));
152 early_initcall(init_zero_pfn);
155 #if defined(SPLIT_RSS_COUNTING)
157 void sync_mm_rss(struct mm_struct *mm)
161 for (i = 0; i < NR_MM_COUNTERS; i++) {
162 if (current->rss_stat.count[i]) {
163 add_mm_counter(mm, i, current->rss_stat.count[i]);
164 current->rss_stat.count[i] = 0;
167 current->rss_stat.events = 0;
170 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
172 struct task_struct *task = current;
174 if (likely(task->mm == mm))
175 task->rss_stat.count[member] += val;
177 add_mm_counter(mm, member, val);
179 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
180 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
182 /* sync counter once per 64 page faults */
183 #define TASK_RSS_EVENTS_THRESH (64)
184 static void check_sync_rss_stat(struct task_struct *task)
186 if (unlikely(task != current))
188 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
189 sync_mm_rss(task->mm);
191 #else /* SPLIT_RSS_COUNTING */
193 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
194 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
196 static void check_sync_rss_stat(struct task_struct *task)
200 #endif /* SPLIT_RSS_COUNTING */
202 #ifdef HAVE_GENERIC_MMU_GATHER
204 static bool tlb_next_batch(struct mmu_gather *tlb)
206 struct mmu_gather_batch *batch;
210 tlb->active = batch->next;
214 if (tlb->batch_count == MAX_GATHER_BATCH_COUNT)
217 batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0);
224 batch->max = MAX_GATHER_BATCH;
226 tlb->active->next = batch;
232 void arch_tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm,
233 unsigned long start, unsigned long end)
237 /* Is it from 0 to ~0? */
238 tlb->fullmm = !(start | (end+1));
239 tlb->need_flush_all = 0;
240 tlb->local.next = NULL;
242 tlb->local.max = ARRAY_SIZE(tlb->__pages);
243 tlb->active = &tlb->local;
244 tlb->batch_count = 0;
246 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
251 __tlb_reset_range(tlb);
254 static void tlb_flush_mmu_tlbonly(struct mmu_gather *tlb)
260 mmu_notifier_invalidate_range(tlb->mm, tlb->start, tlb->end);
261 __tlb_reset_range(tlb);
264 static void tlb_flush_mmu_free(struct mmu_gather *tlb)
266 struct mmu_gather_batch *batch;
268 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
269 tlb_table_flush(tlb);
271 for (batch = &tlb->local; batch && batch->nr; batch = batch->next) {
272 free_pages_and_swap_cache(batch->pages, batch->nr);
275 tlb->active = &tlb->local;
278 void tlb_flush_mmu(struct mmu_gather *tlb)
280 tlb_flush_mmu_tlbonly(tlb);
281 tlb_flush_mmu_free(tlb);
285 * Called at the end of the shootdown operation to free up any resources
286 * that were required.
288 void arch_tlb_finish_mmu(struct mmu_gather *tlb,
289 unsigned long start, unsigned long end, bool force)
291 struct mmu_gather_batch *batch, *next;
294 __tlb_adjust_range(tlb, start, end - start);
298 /* keep the page table cache within bounds */
301 for (batch = tlb->local.next; batch; batch = next) {
303 free_pages((unsigned long)batch, 0);
305 tlb->local.next = NULL;
309 * Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while
310 * handling the additional races in SMP caused by other CPUs caching valid
311 * mappings in their TLBs. Returns the number of free page slots left.
312 * When out of page slots we must call tlb_flush_mmu().
313 *returns true if the caller should flush.
315 bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, int page_size)
317 struct mmu_gather_batch *batch;
319 VM_BUG_ON(!tlb->end);
320 VM_WARN_ON(tlb->page_size != page_size);
324 * Add the page and check if we are full. If so
327 batch->pages[batch->nr++] = page;
328 if (batch->nr == batch->max) {
329 if (!tlb_next_batch(tlb))
333 VM_BUG_ON_PAGE(batch->nr > batch->max, page);
338 void tlb_flush_pmd_range(struct mmu_gather *tlb, unsigned long address,
341 if (tlb->page_size != 0 && tlb->page_size != PMD_SIZE)
344 tlb->page_size = PMD_SIZE;
345 tlb->start = min(tlb->start, address);
346 tlb->end = max(tlb->end, address + size);
348 #endif /* HAVE_GENERIC_MMU_GATHER */
350 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
353 * See the comment near struct mmu_table_batch.
357 * If we want tlb_remove_table() to imply TLB invalidates.
359 static inline void tlb_table_invalidate(struct mmu_gather *tlb)
361 #ifdef CONFIG_HAVE_RCU_TABLE_INVALIDATE
363 * Invalidate page-table caches used by hardware walkers. Then we still
364 * need to RCU-sched wait while freeing the pages because software
365 * walkers can still be in-flight.
367 tlb_flush_mmu_tlbonly(tlb);
371 static void tlb_remove_table_smp_sync(void *arg)
373 /* Simply deliver the interrupt */
376 static void tlb_remove_table_one(void *table)
379 * This isn't an RCU grace period and hence the page-tables cannot be
380 * assumed to be actually RCU-freed.
382 * It is however sufficient for software page-table walkers that rely on
383 * IRQ disabling. See the comment near struct mmu_table_batch.
385 smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
386 __tlb_remove_table(table);
389 static void tlb_remove_table_rcu(struct rcu_head *head)
391 struct mmu_table_batch *batch;
394 batch = container_of(head, struct mmu_table_batch, rcu);
396 for (i = 0; i < batch->nr; i++)
397 __tlb_remove_table(batch->tables[i]);
399 free_page((unsigned long)batch);
402 void tlb_table_flush(struct mmu_gather *tlb)
404 struct mmu_table_batch **batch = &tlb->batch;
407 tlb_table_invalidate(tlb);
408 call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
413 void tlb_remove_table(struct mmu_gather *tlb, void *table)
415 struct mmu_table_batch **batch = &tlb->batch;
417 if (*batch == NULL) {
418 *batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
419 if (*batch == NULL) {
420 tlb_table_invalidate(tlb);
421 tlb_remove_table_one(table);
427 (*batch)->tables[(*batch)->nr++] = table;
428 if ((*batch)->nr == MAX_TABLE_BATCH)
429 tlb_table_flush(tlb);
432 #endif /* CONFIG_HAVE_RCU_TABLE_FREE */
435 * Called to initialize an (on-stack) mmu_gather structure for page-table
436 * tear-down from @mm. The @fullmm argument is used when @mm is without
437 * users and we're going to destroy the full address space (exit/execve).
439 void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm,
440 unsigned long start, unsigned long end)
442 arch_tlb_gather_mmu(tlb, mm, start, end);
443 inc_tlb_flush_pending(tlb->mm);
446 void tlb_finish_mmu(struct mmu_gather *tlb,
447 unsigned long start, unsigned long end)
450 * If there are parallel threads are doing PTE changes on same range
451 * under non-exclusive lock(e.g., mmap_sem read-side) but defer TLB
452 * flush by batching, a thread has stable TLB entry can fail to flush
453 * the TLB by observing pte_none|!pte_dirty, for example so flush TLB
454 * forcefully if we detect parallel PTE batching threads.
456 bool force = mm_tlb_flush_nested(tlb->mm);
458 arch_tlb_finish_mmu(tlb, start, end, force);
459 dec_tlb_flush_pending(tlb->mm);
463 * Note: this doesn't free the actual pages themselves. That
464 * has been handled earlier when unmapping all the memory regions.
466 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
469 pgtable_t token = pmd_pgtable(*pmd);
471 pte_free_tlb(tlb, token, addr);
472 atomic_long_dec(&tlb->mm->nr_ptes);
475 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
476 unsigned long addr, unsigned long end,
477 unsigned long floor, unsigned long ceiling)
484 pmd = pmd_offset(pud, addr);
486 next = pmd_addr_end(addr, end);
487 if (pmd_none_or_clear_bad(pmd))
489 free_pte_range(tlb, pmd, addr);
490 } while (pmd++, addr = next, addr != end);
500 if (end - 1 > ceiling - 1)
503 pmd = pmd_offset(pud, start);
505 pmd_free_tlb(tlb, pmd, start);
506 mm_dec_nr_pmds(tlb->mm);
509 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
510 unsigned long addr, unsigned long end,
511 unsigned long floor, unsigned long ceiling)
518 pud = pud_offset(p4d, addr);
520 next = pud_addr_end(addr, end);
521 if (pud_none_or_clear_bad(pud))
523 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
524 } while (pud++, addr = next, addr != end);
534 if (end - 1 > ceiling - 1)
537 pud = pud_offset(p4d, start);
539 pud_free_tlb(tlb, pud, start);
542 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
543 unsigned long addr, unsigned long end,
544 unsigned long floor, unsigned long ceiling)
551 p4d = p4d_offset(pgd, addr);
553 next = p4d_addr_end(addr, end);
554 if (p4d_none_or_clear_bad(p4d))
556 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
557 } while (p4d++, addr = next, addr != end);
563 ceiling &= PGDIR_MASK;
567 if (end - 1 > ceiling - 1)
570 p4d = p4d_offset(pgd, start);
572 p4d_free_tlb(tlb, p4d, start);
576 * This function frees user-level page tables of a process.
578 void free_pgd_range(struct mmu_gather *tlb,
579 unsigned long addr, unsigned long end,
580 unsigned long floor, unsigned long ceiling)
586 * The next few lines have given us lots of grief...
588 * Why are we testing PMD* at this top level? Because often
589 * there will be no work to do at all, and we'd prefer not to
590 * go all the way down to the bottom just to discover that.
592 * Why all these "- 1"s? Because 0 represents both the bottom
593 * of the address space and the top of it (using -1 for the
594 * top wouldn't help much: the masks would do the wrong thing).
595 * The rule is that addr 0 and floor 0 refer to the bottom of
596 * the address space, but end 0 and ceiling 0 refer to the top
597 * Comparisons need to use "end - 1" and "ceiling - 1" (though
598 * that end 0 case should be mythical).
600 * Wherever addr is brought up or ceiling brought down, we must
601 * be careful to reject "the opposite 0" before it confuses the
602 * subsequent tests. But what about where end is brought down
603 * by PMD_SIZE below? no, end can't go down to 0 there.
605 * Whereas we round start (addr) and ceiling down, by different
606 * masks at different levels, in order to test whether a table
607 * now has no other vmas using it, so can be freed, we don't
608 * bother to round floor or end up - the tests don't need that.
622 if (end - 1 > ceiling - 1)
627 * We add page table cache pages with PAGE_SIZE,
628 * (see pte_free_tlb()), flush the tlb if we need
630 tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
631 pgd = pgd_offset(tlb->mm, addr);
633 next = pgd_addr_end(addr, end);
634 if (pgd_none_or_clear_bad(pgd))
636 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
637 } while (pgd++, addr = next, addr != end);
640 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
641 unsigned long floor, unsigned long ceiling)
644 struct vm_area_struct *next = vma->vm_next;
645 unsigned long addr = vma->vm_start;
648 * Hide vma from rmap and truncate_pagecache before freeing
651 unlink_anon_vmas(vma);
652 unlink_file_vma(vma);
654 if (is_vm_hugetlb_page(vma)) {
655 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
656 floor, next ? next->vm_start : ceiling);
659 * Optimization: gather nearby vmas into one call down
661 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
662 && !is_vm_hugetlb_page(next)) {
665 unlink_anon_vmas(vma);
666 unlink_file_vma(vma);
668 free_pgd_range(tlb, addr, vma->vm_end,
669 floor, next ? next->vm_start : ceiling);
675 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd, unsigned long address)
678 pgtable_t new = pte_alloc_one(mm, address);
683 * Ensure all pte setup (eg. pte page lock and page clearing) are
684 * visible before the pte is made visible to other CPUs by being
685 * put into page tables.
687 * The other side of the story is the pointer chasing in the page
688 * table walking code (when walking the page table without locking;
689 * ie. most of the time). Fortunately, these data accesses consist
690 * of a chain of data-dependent loads, meaning most CPUs (alpha
691 * being the notable exception) will already guarantee loads are
692 * seen in-order. See the alpha page table accessors for the
693 * smp_read_barrier_depends() barriers in page table walking code.
695 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
697 ptl = pmd_lock(mm, pmd);
698 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
699 atomic_long_inc(&mm->nr_ptes);
700 pmd_populate(mm, pmd, new);
709 int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
711 pte_t *new = pte_alloc_one_kernel(&init_mm, address);
715 smp_wmb(); /* See comment in __pte_alloc */
717 spin_lock(&init_mm.page_table_lock);
718 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
719 pmd_populate_kernel(&init_mm, pmd, new);
722 spin_unlock(&init_mm.page_table_lock);
724 pte_free_kernel(&init_mm, new);
728 static inline void init_rss_vec(int *rss)
730 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
733 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
737 if (current->mm == mm)
739 for (i = 0; i < NR_MM_COUNTERS; i++)
741 add_mm_counter(mm, i, rss[i]);
745 * This function is called to print an error when a bad pte
746 * is found. For example, we might have a PFN-mapped pte in
747 * a region that doesn't allow it.
749 * The calling function must still handle the error.
751 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
752 pte_t pte, struct page *page)
754 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
755 p4d_t *p4d = p4d_offset(pgd, addr);
756 pud_t *pud = pud_offset(p4d, addr);
757 pmd_t *pmd = pmd_offset(pud, addr);
758 struct address_space *mapping;
760 static unsigned long resume;
761 static unsigned long nr_shown;
762 static unsigned long nr_unshown;
765 * Allow a burst of 60 reports, then keep quiet for that minute;
766 * or allow a steady drip of one report per second.
768 if (nr_shown == 60) {
769 if (time_before(jiffies, resume)) {
774 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
781 resume = jiffies + 60 * HZ;
783 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
784 index = linear_page_index(vma, addr);
786 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
788 (long long)pte_val(pte), (long long)pmd_val(*pmd));
790 dump_page(page, "bad pte");
791 pr_alert("addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
792 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
794 * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y
796 pr_alert("file:%pD fault:%pf mmap:%pf readpage:%pf\n",
798 vma->vm_ops ? vma->vm_ops->fault : NULL,
799 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
800 mapping ? mapping->a_ops->readpage : NULL);
802 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
806 * vm_normal_page -- This function gets the "struct page" associated with a pte.
808 * "Special" mappings do not wish to be associated with a "struct page" (either
809 * it doesn't exist, or it exists but they don't want to touch it). In this
810 * case, NULL is returned here. "Normal" mappings do have a struct page.
812 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
813 * pte bit, in which case this function is trivial. Secondly, an architecture
814 * may not have a spare pte bit, which requires a more complicated scheme,
817 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
818 * special mapping (even if there are underlying and valid "struct pages").
819 * COWed pages of a VM_PFNMAP are always normal.
821 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
822 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
823 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
824 * mapping will always honor the rule
826 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
828 * And for normal mappings this is false.
830 * This restricts such mappings to be a linear translation from virtual address
831 * to pfn. To get around this restriction, we allow arbitrary mappings so long
832 * as the vma is not a COW mapping; in that case, we know that all ptes are
833 * special (because none can have been COWed).
836 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
838 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
839 * page" backing, however the difference is that _all_ pages with a struct
840 * page (that is, those where pfn_valid is true) are refcounted and considered
841 * normal pages by the VM. The disadvantage is that pages are refcounted
842 * (which can be slower and simply not an option for some PFNMAP users). The
843 * advantage is that we don't have to follow the strict linearity rule of
844 * PFNMAP mappings in order to support COWable mappings.
847 #ifdef __HAVE_ARCH_PTE_SPECIAL
848 # define HAVE_PTE_SPECIAL 1
850 # define HAVE_PTE_SPECIAL 0
852 struct page *_vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
853 pte_t pte, bool with_public_device)
855 unsigned long pfn = pte_pfn(pte);
857 if (HAVE_PTE_SPECIAL) {
858 if (likely(!pte_special(pte)))
860 if (vma->vm_ops && vma->vm_ops->find_special_page)
861 return vma->vm_ops->find_special_page(vma, addr);
862 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
864 if (is_zero_pfn(pfn))
868 * Device public pages are special pages (they are ZONE_DEVICE
869 * pages but different from persistent memory). They behave
870 * allmost like normal pages. The difference is that they are
871 * not on the lru and thus should never be involve with any-
872 * thing that involve lru manipulation (mlock, numa balancing,
875 * This is why we still want to return NULL for such page from
876 * vm_normal_page() so that we do not have to special case all
877 * call site of vm_normal_page().
879 if (likely(pfn <= highest_memmap_pfn)) {
880 struct page *page = pfn_to_page(pfn);
882 if (is_device_public_page(page)) {
883 if (with_public_device)
888 print_bad_pte(vma, addr, pte, NULL);
892 /* !HAVE_PTE_SPECIAL case follows: */
894 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
895 if (vma->vm_flags & VM_MIXEDMAP) {
901 off = (addr - vma->vm_start) >> PAGE_SHIFT;
902 if (pfn == vma->vm_pgoff + off)
904 if (!is_cow_mapping(vma->vm_flags))
909 if (is_zero_pfn(pfn))
912 if (unlikely(pfn > highest_memmap_pfn)) {
913 print_bad_pte(vma, addr, pte, NULL);
918 * NOTE! We still have PageReserved() pages in the page tables.
919 * eg. VDSO mappings can cause them to exist.
922 return pfn_to_page(pfn);
925 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
926 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
929 unsigned long pfn = pmd_pfn(pmd);
932 * There is no pmd_special() but there may be special pmds, e.g.
933 * in a direct-access (dax) mapping, so let's just replicate the
934 * !HAVE_PTE_SPECIAL case from vm_normal_page() here.
936 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
937 if (vma->vm_flags & VM_MIXEDMAP) {
943 off = (addr - vma->vm_start) >> PAGE_SHIFT;
944 if (pfn == vma->vm_pgoff + off)
946 if (!is_cow_mapping(vma->vm_flags))
951 if (is_zero_pfn(pfn))
953 if (unlikely(pfn > highest_memmap_pfn))
957 * NOTE! We still have PageReserved() pages in the page tables.
958 * eg. VDSO mappings can cause them to exist.
961 return pfn_to_page(pfn);
966 * copy one vm_area from one task to the other. Assumes the page tables
967 * already present in the new task to be cleared in the whole range
968 * covered by this vma.
971 static inline unsigned long
972 copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
973 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
974 unsigned long addr, int *rss)
976 unsigned long vm_flags = vma->vm_flags;
977 pte_t pte = *src_pte;
980 /* pte contains position in swap or file, so copy. */
981 if (unlikely(!pte_present(pte))) {
982 swp_entry_t entry = pte_to_swp_entry(pte);
984 if (likely(!non_swap_entry(entry))) {
985 if (swap_duplicate(entry) < 0)
988 /* make sure dst_mm is on swapoff's mmlist. */
989 if (unlikely(list_empty(&dst_mm->mmlist))) {
990 spin_lock(&mmlist_lock);
991 if (list_empty(&dst_mm->mmlist))
992 list_add(&dst_mm->mmlist,
994 spin_unlock(&mmlist_lock);
997 } else if (is_migration_entry(entry)) {
998 page = migration_entry_to_page(entry);
1000 rss[mm_counter(page)]++;
1002 if (is_write_migration_entry(entry) &&
1003 is_cow_mapping(vm_flags)) {
1005 * COW mappings require pages in both
1006 * parent and child to be set to read.
1008 make_migration_entry_read(&entry);
1009 pte = swp_entry_to_pte(entry);
1010 if (pte_swp_soft_dirty(*src_pte))
1011 pte = pte_swp_mksoft_dirty(pte);
1012 set_pte_at(src_mm, addr, src_pte, pte);
1014 } else if (is_device_private_entry(entry)) {
1015 page = device_private_entry_to_page(entry);
1018 * Update rss count even for unaddressable pages, as
1019 * they should treated just like normal pages in this
1022 * We will likely want to have some new rss counters
1023 * for unaddressable pages, at some point. But for now
1024 * keep things as they are.
1027 rss[mm_counter(page)]++;
1028 page_dup_rmap(page, false);
1031 * We do not preserve soft-dirty information, because so
1032 * far, checkpoint/restore is the only feature that
1033 * requires that. And checkpoint/restore does not work
1034 * when a device driver is involved (you cannot easily
1035 * save and restore device driver state).
1037 if (is_write_device_private_entry(entry) &&
1038 is_cow_mapping(vm_flags)) {
1039 make_device_private_entry_read(&entry);
1040 pte = swp_entry_to_pte(entry);
1041 set_pte_at(src_mm, addr, src_pte, pte);
1048 * If it's a COW mapping, write protect it both
1049 * in the parent and the child
1051 if (is_cow_mapping(vm_flags)) {
1052 ptep_set_wrprotect(src_mm, addr, src_pte);
1053 pte = pte_wrprotect(pte);
1057 * If it's a shared mapping, mark it clean in
1060 if (vm_flags & VM_SHARED)
1061 pte = pte_mkclean(pte);
1062 pte = pte_mkold(pte);
1064 page = vm_normal_page(vma, addr, pte);
1067 page_dup_rmap(page, false);
1068 rss[mm_counter(page)]++;
1069 } else if (pte_devmap(pte)) {
1070 page = pte_page(pte);
1073 * Cache coherent device memory behave like regular page and
1074 * not like persistent memory page. For more informations see
1075 * MEMORY_DEVICE_CACHE_COHERENT in memory_hotplug.h
1077 if (is_device_public_page(page)) {
1079 page_dup_rmap(page, false);
1080 rss[mm_counter(page)]++;
1085 set_pte_at(dst_mm, addr, dst_pte, pte);
1089 static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1090 pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
1091 unsigned long addr, unsigned long end)
1093 pte_t *orig_src_pte, *orig_dst_pte;
1094 pte_t *src_pte, *dst_pte;
1095 spinlock_t *src_ptl, *dst_ptl;
1097 int rss[NR_MM_COUNTERS];
1098 swp_entry_t entry = (swp_entry_t){0};
1103 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
1106 src_pte = pte_offset_map(src_pmd, addr);
1107 src_ptl = pte_lockptr(src_mm, src_pmd);
1108 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1109 orig_src_pte = src_pte;
1110 orig_dst_pte = dst_pte;
1111 arch_enter_lazy_mmu_mode();
1115 * We are holding two locks at this point - either of them
1116 * could generate latencies in another task on another CPU.
1118 if (progress >= 32) {
1120 if (need_resched() ||
1121 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
1124 if (pte_none(*src_pte)) {
1128 entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
1133 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
1135 arch_leave_lazy_mmu_mode();
1136 spin_unlock(src_ptl);
1137 pte_unmap(orig_src_pte);
1138 add_mm_rss_vec(dst_mm, rss);
1139 pte_unmap_unlock(orig_dst_pte, dst_ptl);
1143 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
1152 static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1153 pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
1154 unsigned long addr, unsigned long end)
1156 pmd_t *src_pmd, *dst_pmd;
1159 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1162 src_pmd = pmd_offset(src_pud, addr);
1164 next = pmd_addr_end(addr, end);
1165 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1166 || pmd_devmap(*src_pmd)) {
1168 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, vma);
1169 err = copy_huge_pmd(dst_mm, src_mm,
1170 dst_pmd, src_pmd, addr, vma);
1177 if (pmd_none_or_clear_bad(src_pmd))
1179 if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
1182 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1186 static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1187 p4d_t *dst_p4d, p4d_t *src_p4d, struct vm_area_struct *vma,
1188 unsigned long addr, unsigned long end)
1190 pud_t *src_pud, *dst_pud;
1193 dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1196 src_pud = pud_offset(src_p4d, addr);
1198 next = pud_addr_end(addr, end);
1199 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1202 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, vma);
1203 err = copy_huge_pud(dst_mm, src_mm,
1204 dst_pud, src_pud, addr, vma);
1211 if (pud_none_or_clear_bad(src_pud))
1213 if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
1216 } while (dst_pud++, src_pud++, addr = next, addr != end);
1220 static inline int copy_p4d_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1221 pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
1222 unsigned long addr, unsigned long end)
1224 p4d_t *src_p4d, *dst_p4d;
1227 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1230 src_p4d = p4d_offset(src_pgd, addr);
1232 next = p4d_addr_end(addr, end);
1233 if (p4d_none_or_clear_bad(src_p4d))
1235 if (copy_pud_range(dst_mm, src_mm, dst_p4d, src_p4d,
1238 } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1242 int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1243 struct vm_area_struct *vma)
1245 pgd_t *src_pgd, *dst_pgd;
1247 unsigned long addr = vma->vm_start;
1248 unsigned long end = vma->vm_end;
1249 unsigned long mmun_start; /* For mmu_notifiers */
1250 unsigned long mmun_end; /* For mmu_notifiers */
1255 * Don't copy ptes where a page fault will fill them correctly.
1256 * Fork becomes much lighter when there are big shared or private
1257 * readonly mappings. The tradeoff is that copy_page_range is more
1258 * efficient than faulting.
1260 if (!(vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1264 if (is_vm_hugetlb_page(vma))
1265 return copy_hugetlb_page_range(dst_mm, src_mm, vma);
1267 if (unlikely(vma->vm_flags & VM_PFNMAP)) {
1269 * We do not free on error cases below as remove_vma
1270 * gets called on error from higher level routine
1272 ret = track_pfn_copy(vma);
1278 * We need to invalidate the secondary MMU mappings only when
1279 * there could be a permission downgrade on the ptes of the
1280 * parent mm. And a permission downgrade will only happen if
1281 * is_cow_mapping() returns true.
1283 is_cow = is_cow_mapping(vma->vm_flags);
1287 mmu_notifier_invalidate_range_start(src_mm, mmun_start,
1291 dst_pgd = pgd_offset(dst_mm, addr);
1292 src_pgd = pgd_offset(src_mm, addr);
1294 next = pgd_addr_end(addr, end);
1295 if (pgd_none_or_clear_bad(src_pgd))
1297 if (unlikely(copy_p4d_range(dst_mm, src_mm, dst_pgd, src_pgd,
1298 vma, addr, next))) {
1302 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1305 mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end);
1309 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1310 struct vm_area_struct *vma, pmd_t *pmd,
1311 unsigned long addr, unsigned long end,
1312 struct zap_details *details)
1314 struct mm_struct *mm = tlb->mm;
1315 int force_flush = 0;
1316 int rss[NR_MM_COUNTERS];
1322 tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
1325 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1327 flush_tlb_batched_pending(mm);
1328 arch_enter_lazy_mmu_mode();
1331 if (pte_none(ptent))
1334 if (pte_present(ptent)) {
1337 page = _vm_normal_page(vma, addr, ptent, true);
1338 if (unlikely(details) && page) {
1340 * unmap_shared_mapping_pages() wants to
1341 * invalidate cache without truncating:
1342 * unmap shared but keep private pages.
1344 if (details->check_mapping &&
1345 details->check_mapping != page_rmapping(page))
1348 ptent = ptep_get_and_clear_full(mm, addr, pte,
1350 tlb_remove_tlb_entry(tlb, pte, addr);
1351 if (unlikely(!page))
1354 if (!PageAnon(page)) {
1355 if (pte_dirty(ptent)) {
1357 set_page_dirty(page);
1359 if (pte_young(ptent) &&
1360 likely(!(vma->vm_flags & VM_SEQ_READ)))
1361 mark_page_accessed(page);
1363 rss[mm_counter(page)]--;
1364 page_remove_rmap(page, false);
1365 if (unlikely(page_mapcount(page) < 0))
1366 print_bad_pte(vma, addr, ptent, page);
1367 if (unlikely(__tlb_remove_page(tlb, page))) {
1375 entry = pte_to_swp_entry(ptent);
1376 if (non_swap_entry(entry) && is_device_private_entry(entry)) {
1377 struct page *page = device_private_entry_to_page(entry);
1379 if (unlikely(details && details->check_mapping)) {
1381 * unmap_shared_mapping_pages() wants to
1382 * invalidate cache without truncating:
1383 * unmap shared but keep private pages.
1385 if (details->check_mapping !=
1386 page_rmapping(page))
1390 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1391 rss[mm_counter(page)]--;
1392 page_remove_rmap(page, false);
1397 /* If details->check_mapping, we leave swap entries. */
1398 if (unlikely(details))
1401 entry = pte_to_swp_entry(ptent);
1402 if (!non_swap_entry(entry))
1404 else if (is_migration_entry(entry)) {
1407 page = migration_entry_to_page(entry);
1408 rss[mm_counter(page)]--;
1410 if (unlikely(!free_swap_and_cache(entry)))
1411 print_bad_pte(vma, addr, ptent, NULL);
1412 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1413 } while (pte++, addr += PAGE_SIZE, addr != end);
1415 add_mm_rss_vec(mm, rss);
1416 arch_leave_lazy_mmu_mode();
1418 /* Do the actual TLB flush before dropping ptl */
1420 tlb_flush_mmu_tlbonly(tlb);
1421 pte_unmap_unlock(start_pte, ptl);
1424 * If we forced a TLB flush (either due to running out of
1425 * batch buffers or because we needed to flush dirty TLB
1426 * entries before releasing the ptl), free the batched
1427 * memory too. Restart if we didn't do everything.
1431 tlb_flush_mmu_free(tlb);
1439 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1440 struct vm_area_struct *vma, pud_t *pud,
1441 unsigned long addr, unsigned long end,
1442 struct zap_details *details)
1447 pmd = pmd_offset(pud, addr);
1449 next = pmd_addr_end(addr, end);
1450 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1451 if (next - addr != HPAGE_PMD_SIZE)
1452 __split_huge_pmd(vma, pmd, addr, false, NULL);
1453 else if (zap_huge_pmd(tlb, vma, pmd, addr))
1458 * Here there can be other concurrent MADV_DONTNEED or
1459 * trans huge page faults running, and if the pmd is
1460 * none or trans huge it can change under us. This is
1461 * because MADV_DONTNEED holds the mmap_sem in read
1464 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1466 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1469 } while (pmd++, addr = next, addr != end);
1474 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1475 struct vm_area_struct *vma, p4d_t *p4d,
1476 unsigned long addr, unsigned long end,
1477 struct zap_details *details)
1482 pud = pud_offset(p4d, addr);
1484 next = pud_addr_end(addr, end);
1485 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1486 if (next - addr != HPAGE_PUD_SIZE) {
1487 VM_BUG_ON_VMA(!rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1488 split_huge_pud(vma, pud, addr);
1489 } else if (zap_huge_pud(tlb, vma, pud, addr))
1493 if (pud_none_or_clear_bad(pud))
1495 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1498 } while (pud++, addr = next, addr != end);
1503 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1504 struct vm_area_struct *vma, pgd_t *pgd,
1505 unsigned long addr, unsigned long end,
1506 struct zap_details *details)
1511 p4d = p4d_offset(pgd, addr);
1513 next = p4d_addr_end(addr, end);
1514 if (p4d_none_or_clear_bad(p4d))
1516 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1517 } while (p4d++, addr = next, addr != end);
1522 void unmap_page_range(struct mmu_gather *tlb,
1523 struct vm_area_struct *vma,
1524 unsigned long addr, unsigned long end,
1525 struct zap_details *details)
1530 BUG_ON(addr >= end);
1531 tlb_start_vma(tlb, vma);
1532 pgd = pgd_offset(vma->vm_mm, addr);
1534 next = pgd_addr_end(addr, end);
1535 if (pgd_none_or_clear_bad(pgd))
1537 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1538 } while (pgd++, addr = next, addr != end);
1539 tlb_end_vma(tlb, vma);
1543 static void unmap_single_vma(struct mmu_gather *tlb,
1544 struct vm_area_struct *vma, unsigned long start_addr,
1545 unsigned long end_addr,
1546 struct zap_details *details)
1548 unsigned long start = max(vma->vm_start, start_addr);
1551 if (start >= vma->vm_end)
1553 end = min(vma->vm_end, end_addr);
1554 if (end <= vma->vm_start)
1558 uprobe_munmap(vma, start, end);
1560 if (unlikely(vma->vm_flags & VM_PFNMAP))
1561 untrack_pfn(vma, 0, 0);
1564 if (unlikely(is_vm_hugetlb_page(vma))) {
1566 * It is undesirable to test vma->vm_file as it
1567 * should be non-null for valid hugetlb area.
1568 * However, vm_file will be NULL in the error
1569 * cleanup path of mmap_region. When
1570 * hugetlbfs ->mmap method fails,
1571 * mmap_region() nullifies vma->vm_file
1572 * before calling this function to clean up.
1573 * Since no pte has actually been setup, it is
1574 * safe to do nothing in this case.
1577 i_mmap_lock_write(vma->vm_file->f_mapping);
1578 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1579 i_mmap_unlock_write(vma->vm_file->f_mapping);
1582 unmap_page_range(tlb, vma, start, end, details);
1587 * unmap_vmas - unmap a range of memory covered by a list of vma's
1588 * @tlb: address of the caller's struct mmu_gather
1589 * @vma: the starting vma
1590 * @start_addr: virtual address at which to start unmapping
1591 * @end_addr: virtual address at which to end unmapping
1593 * Unmap all pages in the vma list.
1595 * Only addresses between `start' and `end' will be unmapped.
1597 * The VMA list must be sorted in ascending virtual address order.
1599 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1600 * range after unmap_vmas() returns. So the only responsibility here is to
1601 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1602 * drops the lock and schedules.
1604 void unmap_vmas(struct mmu_gather *tlb,
1605 struct vm_area_struct *vma, unsigned long start_addr,
1606 unsigned long end_addr)
1608 struct mm_struct *mm = vma->vm_mm;
1610 mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1611 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1612 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1613 mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
1617 * zap_page_range - remove user pages in a given range
1618 * @vma: vm_area_struct holding the applicable pages
1619 * @start: starting address of pages to zap
1620 * @size: number of bytes to zap
1622 * Caller must protect the VMA list
1624 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1627 struct mm_struct *mm = vma->vm_mm;
1628 struct mmu_gather tlb;
1629 unsigned long end = start + size;
1632 tlb_gather_mmu(&tlb, mm, start, end);
1633 update_hiwater_rss(mm);
1634 mmu_notifier_invalidate_range_start(mm, start, end);
1635 for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
1636 unmap_single_vma(&tlb, vma, start, end, NULL);
1639 * zap_page_range does not specify whether mmap_sem should be
1640 * held for read or write. That allows parallel zap_page_range
1641 * operations to unmap a PTE and defer a flush meaning that
1642 * this call observes pte_none and fails to flush the TLB.
1643 * Rather than adding a complex API, ensure that no stale
1644 * TLB entries exist when this call returns.
1646 flush_tlb_range(vma, start, end);
1649 mmu_notifier_invalidate_range_end(mm, start, end);
1650 tlb_finish_mmu(&tlb, start, end);
1654 * zap_page_range_single - remove user pages in a given range
1655 * @vma: vm_area_struct holding the applicable pages
1656 * @address: starting address of pages to zap
1657 * @size: number of bytes to zap
1658 * @details: details of shared cache invalidation
1660 * The range must fit into one VMA.
1662 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1663 unsigned long size, struct zap_details *details)
1665 struct mm_struct *mm = vma->vm_mm;
1666 struct mmu_gather tlb;
1667 unsigned long end = address + size;
1670 tlb_gather_mmu(&tlb, mm, address, end);
1671 update_hiwater_rss(mm);
1672 mmu_notifier_invalidate_range_start(mm, address, end);
1673 unmap_single_vma(&tlb, vma, address, end, details);
1674 mmu_notifier_invalidate_range_end(mm, address, end);
1675 tlb_finish_mmu(&tlb, address, end);
1679 * zap_vma_ptes - remove ptes mapping the vma
1680 * @vma: vm_area_struct holding ptes to be zapped
1681 * @address: starting address of pages to zap
1682 * @size: number of bytes to zap
1684 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1686 * The entire address range must be fully contained within the vma.
1688 * Returns 0 if successful.
1690 int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1693 if (address < vma->vm_start || address + size > vma->vm_end ||
1694 !(vma->vm_flags & VM_PFNMAP))
1696 zap_page_range_single(vma, address, size, NULL);
1699 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1701 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1709 pgd = pgd_offset(mm, addr);
1710 p4d = p4d_alloc(mm, pgd, addr);
1713 pud = pud_alloc(mm, p4d, addr);
1716 pmd = pmd_alloc(mm, pud, addr);
1720 VM_BUG_ON(pmd_trans_huge(*pmd));
1721 return pte_alloc_map_lock(mm, pmd, addr, ptl);
1725 * This is the old fallback for page remapping.
1727 * For historical reasons, it only allows reserved pages. Only
1728 * old drivers should use this, and they needed to mark their
1729 * pages reserved for the old functions anyway.
1731 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1732 struct page *page, pgprot_t prot)
1734 struct mm_struct *mm = vma->vm_mm;
1743 flush_dcache_page(page);
1744 pte = get_locked_pte(mm, addr, &ptl);
1748 if (!pte_none(*pte))
1751 /* Ok, finally just insert the thing.. */
1753 inc_mm_counter_fast(mm, mm_counter_file(page));
1754 page_add_file_rmap(page, false);
1755 set_pte_at(mm, addr, pte, mk_pte(page, prot));
1758 pte_unmap_unlock(pte, ptl);
1761 pte_unmap_unlock(pte, ptl);
1767 * vm_insert_page - insert single page into user vma
1768 * @vma: user vma to map to
1769 * @addr: target user address of this page
1770 * @page: source kernel page
1772 * This allows drivers to insert individual pages they've allocated
1775 * The page has to be a nice clean _individual_ kernel allocation.
1776 * If you allocate a compound page, you need to have marked it as
1777 * such (__GFP_COMP), or manually just split the page up yourself
1778 * (see split_page()).
1780 * NOTE! Traditionally this was done with "remap_pfn_range()" which
1781 * took an arbitrary page protection parameter. This doesn't allow
1782 * that. Your vma protection will have to be set up correctly, which
1783 * means that if you want a shared writable mapping, you'd better
1784 * ask for a shared writable mapping!
1786 * The page does not need to be reserved.
1788 * Usually this function is called from f_op->mmap() handler
1789 * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
1790 * Caller must set VM_MIXEDMAP on vma if it wants to call this
1791 * function from other places, for example from page-fault handler.
1793 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1796 if (addr < vma->vm_start || addr >= vma->vm_end)
1798 if (!page_count(page))
1800 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1801 BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
1802 BUG_ON(vma->vm_flags & VM_PFNMAP);
1803 vma->vm_flags |= VM_MIXEDMAP;
1805 return insert_page(vma, addr, page, vma->vm_page_prot);
1807 EXPORT_SYMBOL(vm_insert_page);
1809 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1810 pfn_t pfn, pgprot_t prot, bool mkwrite)
1812 struct mm_struct *mm = vma->vm_mm;
1818 pte = get_locked_pte(mm, addr, &ptl);
1822 if (!pte_none(*pte)) {
1825 * For read faults on private mappings the PFN passed
1826 * in may not match the PFN we have mapped if the
1827 * mapped PFN is a writeable COW page. In the mkwrite
1828 * case we are creating a writable PTE for a shared
1829 * mapping and we expect the PFNs to match. If they
1830 * don't match, we are likely racing with block
1831 * allocation and mapping invalidation so just skip the
1834 if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
1835 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
1838 entry = pte_mkyoung(*pte);
1839 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1840 if (ptep_set_access_flags(vma, addr, pte, entry, 1))
1841 update_mmu_cache(vma, addr, pte);
1846 /* Ok, finally just insert the thing.. */
1847 if (pfn_t_devmap(pfn))
1848 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
1850 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1853 entry = pte_mkyoung(entry);
1854 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1857 set_pte_at(mm, addr, pte, entry);
1858 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1862 pte_unmap_unlock(pte, ptl);
1868 * vm_insert_pfn - insert single pfn into user vma
1869 * @vma: user vma to map to
1870 * @addr: target user address of this page
1871 * @pfn: source kernel pfn
1873 * Similar to vm_insert_page, this allows drivers to insert individual pages
1874 * they've allocated into a user vma. Same comments apply.
1876 * This function should only be called from a vm_ops->fault handler, and
1877 * in that case the handler should return NULL.
1879 * vma cannot be a COW mapping.
1881 * As this is called only for pages that do not currently exist, we
1882 * do not need to flush old virtual caches or the TLB.
1884 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1887 return vm_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
1889 EXPORT_SYMBOL(vm_insert_pfn);
1892 * vm_insert_pfn_prot - insert single pfn into user vma with specified pgprot
1893 * @vma: user vma to map to
1894 * @addr: target user address of this page
1895 * @pfn: source kernel pfn
1896 * @pgprot: pgprot flags for the inserted page
1898 * This is exactly like vm_insert_pfn, except that it allows drivers to
1899 * to override pgprot on a per-page basis.
1901 * This only makes sense for IO mappings, and it makes no sense for
1902 * cow mappings. In general, using multiple vmas is preferable;
1903 * vm_insert_pfn_prot should only be used if using multiple VMAs is
1906 int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
1907 unsigned long pfn, pgprot_t pgprot)
1911 * Technically, architectures with pte_special can avoid all these
1912 * restrictions (same for remap_pfn_range). However we would like
1913 * consistency in testing and feature parity among all, so we should
1914 * try to keep these invariants in place for everybody.
1916 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1917 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1918 (VM_PFNMAP|VM_MIXEDMAP));
1919 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1920 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1922 if (addr < vma->vm_start || addr >= vma->vm_end)
1925 if (!pfn_modify_allowed(pfn, pgprot))
1928 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
1930 ret = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
1935 EXPORT_SYMBOL(vm_insert_pfn_prot);
1937 static int __vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1938 pfn_t pfn, bool mkwrite)
1940 pgprot_t pgprot = vma->vm_page_prot;
1942 BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
1944 if (addr < vma->vm_start || addr >= vma->vm_end)
1947 track_pfn_insert(vma, &pgprot, pfn);
1949 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
1953 * If we don't have pte special, then we have to use the pfn_valid()
1954 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1955 * refcount the page if pfn_valid is true (hence insert_page rather
1956 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
1957 * without pte special, it would there be refcounted as a normal page.
1959 if (!HAVE_PTE_SPECIAL && !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1963 * At this point we are committed to insert_page()
1964 * regardless of whether the caller specified flags that
1965 * result in pfn_t_has_page() == false.
1967 page = pfn_to_page(pfn_t_to_pfn(pfn));
1968 return insert_page(vma, addr, page, pgprot);
1970 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
1973 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1976 return __vm_insert_mixed(vma, addr, pfn, false);
1979 EXPORT_SYMBOL(vm_insert_mixed);
1981 int vm_insert_mixed_mkwrite(struct vm_area_struct *vma, unsigned long addr,
1984 return __vm_insert_mixed(vma, addr, pfn, true);
1986 EXPORT_SYMBOL(vm_insert_mixed_mkwrite);
1989 * maps a range of physical memory into the requested pages. the old
1990 * mappings are removed. any references to nonexistent pages results
1991 * in null mappings (currently treated as "copy-on-access")
1993 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
1994 unsigned long addr, unsigned long end,
1995 unsigned long pfn, pgprot_t prot)
1997 pte_t *pte, *mapped_pte;
2001 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2004 arch_enter_lazy_mmu_mode();
2006 BUG_ON(!pte_none(*pte));
2007 if (!pfn_modify_allowed(pfn, prot)) {
2011 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2013 } while (pte++, addr += PAGE_SIZE, addr != end);
2014 arch_leave_lazy_mmu_mode();
2015 pte_unmap_unlock(mapped_pte, ptl);
2019 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2020 unsigned long addr, unsigned long end,
2021 unsigned long pfn, pgprot_t prot)
2027 pfn -= addr >> PAGE_SHIFT;
2028 pmd = pmd_alloc(mm, pud, addr);
2031 VM_BUG_ON(pmd_trans_huge(*pmd));
2033 next = pmd_addr_end(addr, end);
2034 err = remap_pte_range(mm, pmd, addr, next,
2035 pfn + (addr >> PAGE_SHIFT), prot);
2038 } while (pmd++, addr = next, addr != end);
2042 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2043 unsigned long addr, unsigned long end,
2044 unsigned long pfn, pgprot_t prot)
2050 pfn -= addr >> PAGE_SHIFT;
2051 pud = pud_alloc(mm, p4d, addr);
2055 next = pud_addr_end(addr, end);
2056 err = remap_pmd_range(mm, pud, addr, next,
2057 pfn + (addr >> PAGE_SHIFT), prot);
2060 } while (pud++, addr = next, addr != end);
2064 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2065 unsigned long addr, unsigned long end,
2066 unsigned long pfn, pgprot_t prot)
2072 pfn -= addr >> PAGE_SHIFT;
2073 p4d = p4d_alloc(mm, pgd, addr);
2077 next = p4d_addr_end(addr, end);
2078 err = remap_pud_range(mm, p4d, addr, next,
2079 pfn + (addr >> PAGE_SHIFT), prot);
2082 } while (p4d++, addr = next, addr != end);
2087 * remap_pfn_range - remap kernel memory to userspace
2088 * @vma: user vma to map to
2089 * @addr: target user address to start at
2090 * @pfn: physical address of kernel memory
2091 * @size: size of map area
2092 * @prot: page protection flags for this mapping
2094 * Note: this is only safe if the mm semaphore is held when called.
2096 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2097 unsigned long pfn, unsigned long size, pgprot_t prot)
2101 unsigned long end = addr + PAGE_ALIGN(size);
2102 struct mm_struct *mm = vma->vm_mm;
2103 unsigned long remap_pfn = pfn;
2107 * Physically remapped pages are special. Tell the
2108 * rest of the world about it:
2109 * VM_IO tells people not to look at these pages
2110 * (accesses can have side effects).
2111 * VM_PFNMAP tells the core MM that the base pages are just
2112 * raw PFN mappings, and do not have a "struct page" associated
2115 * Disable vma merging and expanding with mremap().
2117 * Omit vma from core dump, even when VM_IO turned off.
2119 * There's a horrible special case to handle copy-on-write
2120 * behaviour that some programs depend on. We mark the "original"
2121 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2122 * See vm_normal_page() for details.
2124 if (is_cow_mapping(vma->vm_flags)) {
2125 if (addr != vma->vm_start || end != vma->vm_end)
2127 vma->vm_pgoff = pfn;
2130 err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
2134 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2136 BUG_ON(addr >= end);
2137 pfn -= addr >> PAGE_SHIFT;
2138 pgd = pgd_offset(mm, addr);
2139 flush_cache_range(vma, addr, end);
2141 next = pgd_addr_end(addr, end);
2142 err = remap_p4d_range(mm, pgd, addr, next,
2143 pfn + (addr >> PAGE_SHIFT), prot);
2146 } while (pgd++, addr = next, addr != end);
2149 untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
2153 EXPORT_SYMBOL(remap_pfn_range);
2156 * vm_iomap_memory - remap memory to userspace
2157 * @vma: user vma to map to
2158 * @start: start of area
2159 * @len: size of area
2161 * This is a simplified io_remap_pfn_range() for common driver use. The
2162 * driver just needs to give us the physical memory range to be mapped,
2163 * we'll figure out the rest from the vma information.
2165 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2166 * whatever write-combining details or similar.
2168 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2170 unsigned long vm_len, pfn, pages;
2172 /* Check that the physical memory area passed in looks valid */
2173 if (start + len < start)
2176 * You *really* shouldn't map things that aren't page-aligned,
2177 * but we've historically allowed it because IO memory might
2178 * just have smaller alignment.
2180 len += start & ~PAGE_MASK;
2181 pfn = start >> PAGE_SHIFT;
2182 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2183 if (pfn + pages < pfn)
2186 /* We start the mapping 'vm_pgoff' pages into the area */
2187 if (vma->vm_pgoff > pages)
2189 pfn += vma->vm_pgoff;
2190 pages -= vma->vm_pgoff;
2192 /* Can we fit all of the mapping? */
2193 vm_len = vma->vm_end - vma->vm_start;
2194 if (vm_len >> PAGE_SHIFT > pages)
2197 /* Ok, let it rip */
2198 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2200 EXPORT_SYMBOL(vm_iomap_memory);
2202 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2203 unsigned long addr, unsigned long end,
2204 pte_fn_t fn, void *data)
2209 spinlock_t *uninitialized_var(ptl);
2211 pte = (mm == &init_mm) ?
2212 pte_alloc_kernel(pmd, addr) :
2213 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2217 BUG_ON(pmd_huge(*pmd));
2219 arch_enter_lazy_mmu_mode();
2221 token = pmd_pgtable(*pmd);
2224 err = fn(pte++, token, addr, data);
2227 } while (addr += PAGE_SIZE, addr != end);
2229 arch_leave_lazy_mmu_mode();
2232 pte_unmap_unlock(pte-1, ptl);
2236 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2237 unsigned long addr, unsigned long end,
2238 pte_fn_t fn, void *data)
2244 BUG_ON(pud_huge(*pud));
2246 pmd = pmd_alloc(mm, pud, addr);
2250 next = pmd_addr_end(addr, end);
2251 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
2254 } while (pmd++, addr = next, addr != end);
2258 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2259 unsigned long addr, unsigned long end,
2260 pte_fn_t fn, void *data)
2266 pud = pud_alloc(mm, p4d, addr);
2270 next = pud_addr_end(addr, end);
2271 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
2274 } while (pud++, addr = next, addr != end);
2278 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2279 unsigned long addr, unsigned long end,
2280 pte_fn_t fn, void *data)
2286 p4d = p4d_alloc(mm, pgd, addr);
2290 next = p4d_addr_end(addr, end);
2291 err = apply_to_pud_range(mm, p4d, addr, next, fn, data);
2294 } while (p4d++, addr = next, addr != end);
2299 * Scan a region of virtual memory, filling in page tables as necessary
2300 * and calling a provided function on each leaf page table.
2302 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2303 unsigned long size, pte_fn_t fn, void *data)
2307 unsigned long end = addr + size;
2310 if (WARN_ON(addr >= end))
2313 pgd = pgd_offset(mm, addr);
2315 next = pgd_addr_end(addr, end);
2316 err = apply_to_p4d_range(mm, pgd, addr, next, fn, data);
2319 } while (pgd++, addr = next, addr != end);
2323 EXPORT_SYMBOL_GPL(apply_to_page_range);
2326 * handle_pte_fault chooses page fault handler according to an entry which was
2327 * read non-atomically. Before making any commitment, on those architectures
2328 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2329 * parts, do_swap_page must check under lock before unmapping the pte and
2330 * proceeding (but do_wp_page is only called after already making such a check;
2331 * and do_anonymous_page can safely check later on).
2333 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2334 pte_t *page_table, pte_t orig_pte)
2337 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
2338 if (sizeof(pte_t) > sizeof(unsigned long)) {
2339 spinlock_t *ptl = pte_lockptr(mm, pmd);
2341 same = pte_same(*page_table, orig_pte);
2345 pte_unmap(page_table);
2349 static inline bool cow_user_page(struct page *dst, struct page *src,
2350 struct vm_fault *vmf)
2355 bool locked = false;
2356 struct vm_area_struct *vma = vmf->vma;
2357 struct mm_struct *mm = vma->vm_mm;
2358 unsigned long addr = vmf->address;
2360 debug_dma_assert_idle(src);
2363 copy_user_highpage(dst, src, addr, vma);
2368 * If the source page was a PFN mapping, we don't have
2369 * a "struct page" for it. We do a best-effort copy by
2370 * just copying from the original user address. If that
2371 * fails, we just zero-fill it. Live with it.
2373 kaddr = kmap_atomic(dst);
2374 uaddr = (void __user *)(addr & PAGE_MASK);
2377 * On architectures with software "accessed" bits, we would
2378 * take a double page fault, so mark it accessed here.
2380 if (arch_faults_on_old_pte() && !pte_young(vmf->orig_pte)) {
2383 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2385 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2387 * Other thread has already handled the fault
2388 * and we don't need to do anything. If it's
2389 * not the case, the fault will be triggered
2390 * again on the same address.
2396 entry = pte_mkyoung(vmf->orig_pte);
2397 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2398 update_mmu_cache(vma, addr, vmf->pte);
2402 * This really shouldn't fail, because the page is there
2403 * in the page tables. But it might just be unreadable,
2404 * in which case we just give up and fill the result with
2407 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2411 /* Re-validate under PTL if the page is still mapped */
2412 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2414 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2415 /* The PTE changed under us. Retry page fault. */
2421 * The same page can be mapped back since last copy attampt.
2422 * Try to copy again under PTL.
2424 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2426 * Give a warn in case there can be some obscure
2439 pte_unmap_unlock(vmf->pte, vmf->ptl);
2440 kunmap_atomic(kaddr);
2441 flush_dcache_page(dst);
2446 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2448 struct file *vm_file = vma->vm_file;
2451 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2454 * Special mappings (e.g. VDSO) do not have any file so fake
2455 * a default GFP_KERNEL for them.
2461 * Notify the address space that the page is about to become writable so that
2462 * it can prohibit this or wait for the page to get into an appropriate state.
2464 * We do this without the lock held, so that it can sleep if it needs to.
2466 static int do_page_mkwrite(struct vm_fault *vmf)
2469 struct page *page = vmf->page;
2470 unsigned int old_flags = vmf->flags;
2472 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2474 ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2475 /* Restore original flags so that caller is not surprised */
2476 vmf->flags = old_flags;
2477 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2479 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2481 if (!page->mapping) {
2483 return 0; /* retry */
2485 ret |= VM_FAULT_LOCKED;
2487 VM_BUG_ON_PAGE(!PageLocked(page), page);
2492 * Handle dirtying of a page in shared file mapping on a write fault.
2494 * The function expects the page to be locked and unlocks it.
2496 static void fault_dirty_shared_page(struct vm_area_struct *vma,
2499 struct address_space *mapping;
2501 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2503 dirtied = set_page_dirty(page);
2504 VM_BUG_ON_PAGE(PageAnon(page), page);
2506 * Take a local copy of the address_space - page.mapping may be zeroed
2507 * by truncate after unlock_page(). The address_space itself remains
2508 * pinned by vma->vm_file's reference. We rely on unlock_page()'s
2509 * release semantics to prevent the compiler from undoing this copying.
2511 mapping = page_rmapping(page);
2514 if ((dirtied || page_mkwrite) && mapping) {
2516 * Some device drivers do not set page.mapping
2517 * but still dirty their pages
2519 balance_dirty_pages_ratelimited(mapping);
2523 file_update_time(vma->vm_file);
2527 * Handle write page faults for pages that can be reused in the current vma
2529 * This can happen either due to the mapping being with the VM_SHARED flag,
2530 * or due to us being the last reference standing to the page. In either
2531 * case, all we need to do here is to mark the page as writable and update
2532 * any related book-keeping.
2534 static inline void wp_page_reuse(struct vm_fault *vmf)
2535 __releases(vmf->ptl)
2537 struct vm_area_struct *vma = vmf->vma;
2538 struct page *page = vmf->page;
2541 * Clear the pages cpupid information as the existing
2542 * information potentially belongs to a now completely
2543 * unrelated process.
2546 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2548 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2549 entry = pte_mkyoung(vmf->orig_pte);
2550 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2551 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
2552 update_mmu_cache(vma, vmf->address, vmf->pte);
2553 pte_unmap_unlock(vmf->pte, vmf->ptl);
2557 * Handle the case of a page which we actually need to copy to a new page.
2559 * Called with mmap_sem locked and the old page referenced, but
2560 * without the ptl held.
2562 * High level logic flow:
2564 * - Allocate a page, copy the content of the old page to the new one.
2565 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2566 * - Take the PTL. If the pte changed, bail out and release the allocated page
2567 * - If the pte is still the way we remember it, update the page table and all
2568 * relevant references. This includes dropping the reference the page-table
2569 * held to the old page, as well as updating the rmap.
2570 * - In any case, unlock the PTL and drop the reference we took to the old page.
2572 static int wp_page_copy(struct vm_fault *vmf)
2574 struct vm_area_struct *vma = vmf->vma;
2575 struct mm_struct *mm = vma->vm_mm;
2576 struct page *old_page = vmf->page;
2577 struct page *new_page = NULL;
2579 int page_copied = 0;
2580 const unsigned long mmun_start = vmf->address & PAGE_MASK;
2581 const unsigned long mmun_end = mmun_start + PAGE_SIZE;
2582 struct mem_cgroup *memcg;
2584 if (unlikely(anon_vma_prepare(vma)))
2587 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
2588 new_page = alloc_zeroed_user_highpage_movable(vma,
2593 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2598 if (!cow_user_page(new_page, old_page, vmf)) {
2600 * COW failed, if the fault was solved by other,
2601 * it's fine. If not, userspace would re-fault on
2602 * the same address and we will handle the fault
2603 * from the second attempt.
2612 if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg, false))
2615 __SetPageUptodate(new_page);
2617 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2620 * Re-check the pte - we dropped the lock
2622 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
2623 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2625 if (!PageAnon(old_page)) {
2626 dec_mm_counter_fast(mm,
2627 mm_counter_file(old_page));
2628 inc_mm_counter_fast(mm, MM_ANONPAGES);
2631 inc_mm_counter_fast(mm, MM_ANONPAGES);
2633 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2634 entry = mk_pte(new_page, vma->vm_page_prot);
2635 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2637 * Clear the pte entry and flush it first, before updating the
2638 * pte with the new entry. This will avoid a race condition
2639 * seen in the presence of one thread doing SMC and another
2642 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
2643 page_add_new_anon_rmap(new_page, vma, vmf->address, false);
2644 mem_cgroup_commit_charge(new_page, memcg, false, false);
2645 lru_cache_add_active_or_unevictable(new_page, vma);
2647 * We call the notify macro here because, when using secondary
2648 * mmu page tables (such as kvm shadow page tables), we want the
2649 * new page to be mapped directly into the secondary page table.
2651 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
2652 update_mmu_cache(vma, vmf->address, vmf->pte);
2655 * Only after switching the pte to the new page may
2656 * we remove the mapcount here. Otherwise another
2657 * process may come and find the rmap count decremented
2658 * before the pte is switched to the new page, and
2659 * "reuse" the old page writing into it while our pte
2660 * here still points into it and can be read by other
2663 * The critical issue is to order this
2664 * page_remove_rmap with the ptp_clear_flush above.
2665 * Those stores are ordered by (if nothing else,)
2666 * the barrier present in the atomic_add_negative
2667 * in page_remove_rmap.
2669 * Then the TLB flush in ptep_clear_flush ensures that
2670 * no process can access the old page before the
2671 * decremented mapcount is visible. And the old page
2672 * cannot be reused until after the decremented
2673 * mapcount is visible. So transitively, TLBs to
2674 * old page will be flushed before it can be reused.
2676 page_remove_rmap(old_page, false);
2679 /* Free the old page.. */
2680 new_page = old_page;
2683 mem_cgroup_cancel_charge(new_page, memcg, false);
2689 pte_unmap_unlock(vmf->pte, vmf->ptl);
2690 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2693 * Don't let another task, with possibly unlocked vma,
2694 * keep the mlocked page.
2696 if (page_copied && (vma->vm_flags & VM_LOCKED)) {
2697 lock_page(old_page); /* LRU manipulation */
2698 if (PageMlocked(old_page))
2699 munlock_vma_page(old_page);
2700 unlock_page(old_page);
2704 return page_copied ? VM_FAULT_WRITE : 0;
2710 return VM_FAULT_OOM;
2714 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
2715 * writeable once the page is prepared
2717 * @vmf: structure describing the fault
2719 * This function handles all that is needed to finish a write page fault in a
2720 * shared mapping due to PTE being read-only once the mapped page is prepared.
2721 * It handles locking of PTE and modifying it. The function returns
2722 * VM_FAULT_WRITE on success, 0 when PTE got changed before we acquired PTE
2725 * The function expects the page to be locked or other protection against
2726 * concurrent faults / writeback (such as DAX radix tree locks).
2728 int finish_mkwrite_fault(struct vm_fault *vmf)
2730 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
2731 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
2734 * We might have raced with another page fault while we released the
2735 * pte_offset_map_lock.
2737 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2738 pte_unmap_unlock(vmf->pte, vmf->ptl);
2739 return VM_FAULT_NOPAGE;
2746 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2749 static int wp_pfn_shared(struct vm_fault *vmf)
2751 struct vm_area_struct *vma = vmf->vma;
2753 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2756 pte_unmap_unlock(vmf->pte, vmf->ptl);
2757 vmf->flags |= FAULT_FLAG_MKWRITE;
2758 ret = vma->vm_ops->pfn_mkwrite(vmf);
2759 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
2761 return finish_mkwrite_fault(vmf);
2764 return VM_FAULT_WRITE;
2767 static int wp_page_shared(struct vm_fault *vmf)
2768 __releases(vmf->ptl)
2770 struct vm_area_struct *vma = vmf->vma;
2772 get_page(vmf->page);
2774 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2777 pte_unmap_unlock(vmf->pte, vmf->ptl);
2778 tmp = do_page_mkwrite(vmf);
2779 if (unlikely(!tmp || (tmp &
2780 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
2781 put_page(vmf->page);
2784 tmp = finish_mkwrite_fault(vmf);
2785 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2786 unlock_page(vmf->page);
2787 put_page(vmf->page);
2792 lock_page(vmf->page);
2794 fault_dirty_shared_page(vma, vmf->page);
2795 put_page(vmf->page);
2797 return VM_FAULT_WRITE;
2801 * This routine handles present pages, when users try to write
2802 * to a shared page. It is done by copying the page to a new address
2803 * and decrementing the shared-page counter for the old page.
2805 * Note that this routine assumes that the protection checks have been
2806 * done by the caller (the low-level page fault routine in most cases).
2807 * Thus we can safely just mark it writable once we've done any necessary
2810 * We also mark the page dirty at this point even though the page will
2811 * change only once the write actually happens. This avoids a few races,
2812 * and potentially makes it more efficient.
2814 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2815 * but allow concurrent faults), with pte both mapped and locked.
2816 * We return with mmap_sem still held, but pte unmapped and unlocked.
2818 static int do_wp_page(struct vm_fault *vmf)
2819 __releases(vmf->ptl)
2821 struct vm_area_struct *vma = vmf->vma;
2823 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
2826 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
2829 * We should not cow pages in a shared writeable mapping.
2830 * Just mark the pages writable and/or call ops->pfn_mkwrite.
2832 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2833 (VM_WRITE|VM_SHARED))
2834 return wp_pfn_shared(vmf);
2836 pte_unmap_unlock(vmf->pte, vmf->ptl);
2837 return wp_page_copy(vmf);
2841 * Take out anonymous pages first, anonymous shared vmas are
2842 * not dirty accountable.
2844 if (PageAnon(vmf->page) && !PageKsm(vmf->page)) {
2845 int total_map_swapcount;
2846 if (!trylock_page(vmf->page)) {
2847 get_page(vmf->page);
2848 pte_unmap_unlock(vmf->pte, vmf->ptl);
2849 lock_page(vmf->page);
2850 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
2851 vmf->address, &vmf->ptl);
2852 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2853 unlock_page(vmf->page);
2854 pte_unmap_unlock(vmf->pte, vmf->ptl);
2855 put_page(vmf->page);
2858 put_page(vmf->page);
2860 if (reuse_swap_page(vmf->page, &total_map_swapcount)) {
2861 if (total_map_swapcount == 1) {
2863 * The page is all ours. Move it to
2864 * our anon_vma so the rmap code will
2865 * not search our parent or siblings.
2866 * Protected against the rmap code by
2869 page_move_anon_rmap(vmf->page, vma);
2871 unlock_page(vmf->page);
2873 return VM_FAULT_WRITE;
2875 unlock_page(vmf->page);
2876 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2877 (VM_WRITE|VM_SHARED))) {
2878 return wp_page_shared(vmf);
2882 * Ok, we need to copy. Oh, well..
2884 get_page(vmf->page);
2886 pte_unmap_unlock(vmf->pte, vmf->ptl);
2887 return wp_page_copy(vmf);
2890 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2891 unsigned long start_addr, unsigned long end_addr,
2892 struct zap_details *details)
2894 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2897 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
2898 struct zap_details *details)
2900 struct vm_area_struct *vma;
2901 pgoff_t vba, vea, zba, zea;
2903 vma_interval_tree_foreach(vma, root,
2904 details->first_index, details->last_index) {
2906 vba = vma->vm_pgoff;
2907 vea = vba + vma_pages(vma) - 1;
2908 zba = details->first_index;
2911 zea = details->last_index;
2915 unmap_mapping_range_vma(vma,
2916 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2917 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2923 * unmap_mapping_range - unmap the portion of all mmaps in the specified
2924 * address_space corresponding to the specified page range in the underlying
2927 * @mapping: the address space containing mmaps to be unmapped.
2928 * @holebegin: byte in first page to unmap, relative to the start of
2929 * the underlying file. This will be rounded down to a PAGE_SIZE
2930 * boundary. Note that this is different from truncate_pagecache(), which
2931 * must keep the partial page. In contrast, we must get rid of
2933 * @holelen: size of prospective hole in bytes. This will be rounded
2934 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
2936 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
2937 * but 0 when invalidating pagecache, don't throw away private data.
2939 void unmap_mapping_range(struct address_space *mapping,
2940 loff_t const holebegin, loff_t const holelen, int even_cows)
2942 struct zap_details details = { };
2943 pgoff_t hba = holebegin >> PAGE_SHIFT;
2944 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2946 /* Check for overflow. */
2947 if (sizeof(holelen) > sizeof(hlen)) {
2949 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2950 if (holeend & ~(long long)ULONG_MAX)
2951 hlen = ULONG_MAX - hba + 1;
2954 details.check_mapping = even_cows ? NULL : mapping;
2955 details.first_index = hba;
2956 details.last_index = hba + hlen - 1;
2957 if (details.last_index < details.first_index)
2958 details.last_index = ULONG_MAX;
2960 i_mmap_lock_write(mapping);
2961 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
2962 unmap_mapping_range_tree(&mapping->i_mmap, &details);
2963 i_mmap_unlock_write(mapping);
2965 EXPORT_SYMBOL(unmap_mapping_range);
2968 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2969 * but allow concurrent faults), and pte mapped but not yet locked.
2970 * We return with pte unmapped and unlocked.
2972 * We return with the mmap_sem locked or unlocked in the same cases
2973 * as does filemap_fault().
2975 int do_swap_page(struct vm_fault *vmf)
2977 struct vm_area_struct *vma = vmf->vma;
2978 struct page *page = NULL, *swapcache;
2979 struct mem_cgroup *memcg;
2980 struct vma_swap_readahead swap_ra;
2986 bool vma_readahead = swap_use_vma_readahead();
2989 page = swap_readahead_detect(vmf, &swap_ra);
2990 if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte)) {
2996 entry = pte_to_swp_entry(vmf->orig_pte);
2997 if (unlikely(non_swap_entry(entry))) {
2998 if (is_migration_entry(entry)) {
2999 migration_entry_wait(vma->vm_mm, vmf->pmd,
3001 } else if (is_device_private_entry(entry)) {
3003 * For un-addressable device memory we call the pgmap
3004 * fault handler callback. The callback must migrate
3005 * the page back to some CPU accessible page.
3007 ret = device_private_entry_fault(vma, vmf->address, entry,
3008 vmf->flags, vmf->pmd);
3009 } else if (is_hwpoison_entry(entry)) {
3010 ret = VM_FAULT_HWPOISON;
3012 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3013 ret = VM_FAULT_SIGBUS;
3017 delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3019 page = lookup_swap_cache(entry, vma_readahead ? vma : NULL,
3023 page = do_swap_page_readahead(entry,
3024 GFP_HIGHUSER_MOVABLE, vmf, &swap_ra);
3026 page = swapin_readahead(entry,
3027 GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3030 * Back out if somebody else faulted in this pte
3031 * while we released the pte lock.
3033 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3034 vmf->address, &vmf->ptl);
3035 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3037 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3041 /* Had to read the page from swap area: Major fault */
3042 ret = VM_FAULT_MAJOR;
3043 count_vm_event(PGMAJFAULT);
3044 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3045 } else if (PageHWPoison(page)) {
3047 * hwpoisoned dirty swapcache pages are kept for killing
3048 * owner processes (which may be unknown at hwpoison time)
3050 ret = VM_FAULT_HWPOISON;
3051 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3057 locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3059 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3061 ret |= VM_FAULT_RETRY;
3066 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3067 * release the swapcache from under us. The page pin, and pte_same
3068 * test below, are not enough to exclude that. Even if it is still
3069 * swapcache, we need to check that the page's swap has not changed.
3071 if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
3074 page = ksm_might_need_to_copy(page, vma, vmf->address);
3075 if (unlikely(!page)) {
3081 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
3088 * Back out if somebody else already faulted in this pte.
3090 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3092 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3095 if (unlikely(!PageUptodate(page))) {
3096 ret = VM_FAULT_SIGBUS;
3101 * The page isn't present yet, go ahead with the fault.
3103 * Be careful about the sequence of operations here.
3104 * To get its accounting right, reuse_swap_page() must be called
3105 * while the page is counted on swap but not yet in mapcount i.e.
3106 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3107 * must be called after the swap_free(), or it will never succeed.
3110 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3111 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3112 pte = mk_pte(page, vma->vm_page_prot);
3113 if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3114 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3115 vmf->flags &= ~FAULT_FLAG_WRITE;
3116 ret |= VM_FAULT_WRITE;
3117 exclusive = RMAP_EXCLUSIVE;
3119 flush_icache_page(vma, page);
3120 if (pte_swp_soft_dirty(vmf->orig_pte))
3121 pte = pte_mksoft_dirty(pte);
3122 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3123 vmf->orig_pte = pte;
3124 if (page == swapcache) {
3125 do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3126 mem_cgroup_commit_charge(page, memcg, true, false);
3127 activate_page(page);
3128 } else { /* ksm created a completely new copy */
3129 page_add_new_anon_rmap(page, vma, vmf->address, false);
3130 mem_cgroup_commit_charge(page, memcg, false, false);
3131 lru_cache_add_active_or_unevictable(page, vma);
3135 if (mem_cgroup_swap_full(page) ||
3136 (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3137 try_to_free_swap(page);
3139 if (page != swapcache) {
3141 * Hold the lock to avoid the swap entry to be reused
3142 * until we take the PT lock for the pte_same() check
3143 * (to avoid false positives from pte_same). For
3144 * further safety release the lock after the swap_free
3145 * so that the swap count won't change under a
3146 * parallel locked swapcache.
3148 unlock_page(swapcache);
3149 put_page(swapcache);
3152 if (vmf->flags & FAULT_FLAG_WRITE) {
3153 ret |= do_wp_page(vmf);
3154 if (ret & VM_FAULT_ERROR)
3155 ret &= VM_FAULT_ERROR;
3159 /* No need to invalidate - it was non-present before */
3160 update_mmu_cache(vma, vmf->address, vmf->pte);
3162 pte_unmap_unlock(vmf->pte, vmf->ptl);
3166 mem_cgroup_cancel_charge(page, memcg, false);
3167 pte_unmap_unlock(vmf->pte, vmf->ptl);
3172 if (page != swapcache) {
3173 unlock_page(swapcache);
3174 put_page(swapcache);
3180 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3181 * but allow concurrent faults), and pte mapped but not yet locked.
3182 * We return with mmap_sem still held, but pte unmapped and unlocked.
3184 static int do_anonymous_page(struct vm_fault *vmf)
3186 struct vm_area_struct *vma = vmf->vma;
3187 struct mem_cgroup *memcg;
3192 /* File mapping without ->vm_ops ? */
3193 if (vma->vm_flags & VM_SHARED)
3194 return VM_FAULT_SIGBUS;
3197 * Use pte_alloc() instead of pte_alloc_map(). We can't run
3198 * pte_offset_map() on pmds where a huge pmd might be created
3199 * from a different thread.
3201 * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
3202 * parallel threads are excluded by other means.
3204 * Here we only have down_read(mmap_sem).
3206 if (pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))
3207 return VM_FAULT_OOM;
3209 /* See the comment in pte_alloc_one_map() */
3210 if (unlikely(pmd_trans_unstable(vmf->pmd)))
3213 /* Use the zero-page for reads */
3214 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3215 !mm_forbids_zeropage(vma->vm_mm)) {
3216 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3217 vma->vm_page_prot));
3218 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3219 vmf->address, &vmf->ptl);
3220 if (!pte_none(*vmf->pte))
3222 ret = check_stable_address_space(vma->vm_mm);
3225 /* Deliver the page fault to userland, check inside PT lock */
3226 if (userfaultfd_missing(vma)) {
3227 pte_unmap_unlock(vmf->pte, vmf->ptl);
3228 return handle_userfault(vmf, VM_UFFD_MISSING);
3233 /* Allocate our own private page. */
3234 if (unlikely(anon_vma_prepare(vma)))
3236 page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3240 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
3244 * The memory barrier inside __SetPageUptodate makes sure that
3245 * preceeding stores to the page contents become visible before
3246 * the set_pte_at() write.
3248 __SetPageUptodate(page);
3250 entry = mk_pte(page, vma->vm_page_prot);
3251 if (vma->vm_flags & VM_WRITE)
3252 entry = pte_mkwrite(pte_mkdirty(entry));
3254 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3256 if (!pte_none(*vmf->pte))
3259 ret = check_stable_address_space(vma->vm_mm);
3263 /* Deliver the page fault to userland, check inside PT lock */
3264 if (userfaultfd_missing(vma)) {
3265 pte_unmap_unlock(vmf->pte, vmf->ptl);
3266 mem_cgroup_cancel_charge(page, memcg, false);
3268 return handle_userfault(vmf, VM_UFFD_MISSING);
3271 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3272 page_add_new_anon_rmap(page, vma, vmf->address, false);
3273 mem_cgroup_commit_charge(page, memcg, false, false);
3274 lru_cache_add_active_or_unevictable(page, vma);
3276 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3278 /* No need to invalidate - it was non-present before */
3279 update_mmu_cache(vma, vmf->address, vmf->pte);
3281 pte_unmap_unlock(vmf->pte, vmf->ptl);
3284 mem_cgroup_cancel_charge(page, memcg, false);
3290 return VM_FAULT_OOM;
3294 * The mmap_sem must have been held on entry, and may have been
3295 * released depending on flags and vma->vm_ops->fault() return value.
3296 * See filemap_fault() and __lock_page_retry().
3298 static int __do_fault(struct vm_fault *vmf)
3300 struct vm_area_struct *vma = vmf->vma;
3304 * Preallocate pte before we take page_lock because this might lead to
3305 * deadlocks for memcg reclaim which waits for pages under writeback:
3307 * SetPageWriteback(A)
3313 * wait_on_page_writeback(A)
3314 * SetPageWriteback(B)
3316 * # flush A, B to clear the writeback
3318 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3319 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
3321 if (!vmf->prealloc_pte)
3322 return VM_FAULT_OOM;
3323 smp_wmb(); /* See comment in __pte_alloc() */
3326 ret = vma->vm_ops->fault(vmf);
3327 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3328 VM_FAULT_DONE_COW)))
3331 if (unlikely(PageHWPoison(vmf->page))) {
3332 if (ret & VM_FAULT_LOCKED)
3333 unlock_page(vmf->page);
3334 put_page(vmf->page);
3336 return VM_FAULT_HWPOISON;
3339 if (unlikely(!(ret & VM_FAULT_LOCKED)))
3340 lock_page(vmf->page);
3342 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3348 * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3349 * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3350 * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3351 * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3353 static int pmd_devmap_trans_unstable(pmd_t *pmd)
3355 return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3358 static int pte_alloc_one_map(struct vm_fault *vmf)
3360 struct vm_area_struct *vma = vmf->vma;
3362 if (!pmd_none(*vmf->pmd))
3364 if (vmf->prealloc_pte) {
3365 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3366 if (unlikely(!pmd_none(*vmf->pmd))) {
3367 spin_unlock(vmf->ptl);
3371 atomic_long_inc(&vma->vm_mm->nr_ptes);
3372 pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3373 spin_unlock(vmf->ptl);
3374 vmf->prealloc_pte = NULL;
3375 } else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))) {
3376 return VM_FAULT_OOM;
3380 * If a huge pmd materialized under us just retry later. Use
3381 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3382 * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3383 * under us and then back to pmd_none, as a result of MADV_DONTNEED
3384 * running immediately after a huge pmd fault in a different thread of
3385 * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3386 * All we have to ensure is that it is a regular pmd that we can walk
3387 * with pte_offset_map() and we can do that through an atomic read in
3388 * C, which is what pmd_trans_unstable() provides.
3390 if (pmd_devmap_trans_unstable(vmf->pmd))
3391 return VM_FAULT_NOPAGE;
3394 * At this point we know that our vmf->pmd points to a page of ptes
3395 * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3396 * for the duration of the fault. If a racing MADV_DONTNEED runs and
3397 * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3398 * be valid and we will re-check to make sure the vmf->pte isn't
3399 * pte_none() under vmf->ptl protection when we return to
3402 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3407 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3409 #define HPAGE_CACHE_INDEX_MASK (HPAGE_PMD_NR - 1)
3410 static inline bool transhuge_vma_suitable(struct vm_area_struct *vma,
3411 unsigned long haddr)
3413 if (((vma->vm_start >> PAGE_SHIFT) & HPAGE_CACHE_INDEX_MASK) !=
3414 (vma->vm_pgoff & HPAGE_CACHE_INDEX_MASK))
3416 if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
3421 static void deposit_prealloc_pte(struct vm_fault *vmf)
3423 struct vm_area_struct *vma = vmf->vma;
3425 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3427 * We are going to consume the prealloc table,
3428 * count that as nr_ptes.
3430 atomic_long_inc(&vma->vm_mm->nr_ptes);
3431 vmf->prealloc_pte = NULL;
3434 static int do_set_pmd(struct vm_fault *vmf, struct page *page)
3436 struct vm_area_struct *vma = vmf->vma;
3437 bool write = vmf->flags & FAULT_FLAG_WRITE;
3438 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3442 if (!transhuge_vma_suitable(vma, haddr))
3443 return VM_FAULT_FALLBACK;
3445 ret = VM_FAULT_FALLBACK;
3446 page = compound_head(page);
3449 * Archs like ppc64 need additonal space to store information
3450 * related to pte entry. Use the preallocated table for that.
3452 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3453 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm, vmf->address);
3454 if (!vmf->prealloc_pte)
3455 return VM_FAULT_OOM;
3456 smp_wmb(); /* See comment in __pte_alloc() */
3459 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3460 if (unlikely(!pmd_none(*vmf->pmd)))
3463 for (i = 0; i < HPAGE_PMD_NR; i++)
3464 flush_icache_page(vma, page + i);
3466 entry = mk_huge_pmd(page, vma->vm_page_prot);
3468 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3470 add_mm_counter(vma->vm_mm, MM_FILEPAGES, HPAGE_PMD_NR);
3471 page_add_file_rmap(page, true);
3473 * deposit and withdraw with pmd lock held
3475 if (arch_needs_pgtable_deposit())
3476 deposit_prealloc_pte(vmf);
3478 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3480 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3482 /* fault is handled */
3484 count_vm_event(THP_FILE_MAPPED);
3486 spin_unlock(vmf->ptl);
3490 static int do_set_pmd(struct vm_fault *vmf, struct page *page)
3498 * alloc_set_pte - setup new PTE entry for given page and add reverse page
3499 * mapping. If needed, the fucntion allocates page table or use pre-allocated.
3501 * @vmf: fault environment
3502 * @memcg: memcg to charge page (only for private mappings)
3503 * @page: page to map
3505 * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
3508 * Target users are page handler itself and implementations of
3509 * vm_ops->map_pages.
3511 int alloc_set_pte(struct vm_fault *vmf, struct mem_cgroup *memcg,
3514 struct vm_area_struct *vma = vmf->vma;
3515 bool write = vmf->flags & FAULT_FLAG_WRITE;
3519 if (pmd_none(*vmf->pmd) && PageTransCompound(page) &&
3520 IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
3522 VM_BUG_ON_PAGE(memcg, page);
3524 ret = do_set_pmd(vmf, page);
3525 if (ret != VM_FAULT_FALLBACK)
3530 ret = pte_alloc_one_map(vmf);
3535 /* Re-check under ptl */
3536 if (unlikely(!pte_none(*vmf->pte)))
3537 return VM_FAULT_NOPAGE;
3539 flush_icache_page(vma, page);
3540 entry = mk_pte(page, vma->vm_page_prot);
3542 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3543 /* copy-on-write page */
3544 if (write && !(vma->vm_flags & VM_SHARED)) {
3545 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3546 page_add_new_anon_rmap(page, vma, vmf->address, false);
3547 mem_cgroup_commit_charge(page, memcg, false, false);
3548 lru_cache_add_active_or_unevictable(page, vma);
3550 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3551 page_add_file_rmap(page, false);
3553 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3555 /* no need to invalidate: a not-present page won't be cached */
3556 update_mmu_cache(vma, vmf->address, vmf->pte);
3563 * finish_fault - finish page fault once we have prepared the page to fault
3565 * @vmf: structure describing the fault
3567 * This function handles all that is needed to finish a page fault once the
3568 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
3569 * given page, adds reverse page mapping, handles memcg charges and LRU
3570 * addition. The function returns 0 on success, VM_FAULT_ code in case of
3573 * The function expects the page to be locked and on success it consumes a
3574 * reference of a page being mapped (for the PTE which maps it).
3576 int finish_fault(struct vm_fault *vmf)
3581 /* Did we COW the page? */
3582 if ((vmf->flags & FAULT_FLAG_WRITE) &&
3583 !(vmf->vma->vm_flags & VM_SHARED))
3584 page = vmf->cow_page;
3589 * check even for read faults because we might have lost our CoWed
3592 if (!(vmf->vma->vm_flags & VM_SHARED))
3593 ret = check_stable_address_space(vmf->vma->vm_mm);
3595 ret = alloc_set_pte(vmf, vmf->memcg, page);
3597 pte_unmap_unlock(vmf->pte, vmf->ptl);
3601 static unsigned long fault_around_bytes __read_mostly =
3602 rounddown_pow_of_two(65536);
3604 #ifdef CONFIG_DEBUG_FS
3605 static int fault_around_bytes_get(void *data, u64 *val)
3607 *val = fault_around_bytes;
3612 * fault_around_pages() and fault_around_mask() expects fault_around_bytes
3613 * rounded down to nearest page order. It's what do_fault_around() expects to
3616 static int fault_around_bytes_set(void *data, u64 val)
3618 if (val / PAGE_SIZE > PTRS_PER_PTE)
3620 if (val > PAGE_SIZE)
3621 fault_around_bytes = rounddown_pow_of_two(val);
3623 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
3626 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
3627 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
3629 static int __init fault_around_debugfs(void)
3633 ret = debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
3634 &fault_around_bytes_fops);
3636 pr_warn("Failed to create fault_around_bytes in debugfs");
3639 late_initcall(fault_around_debugfs);
3643 * do_fault_around() tries to map few pages around the fault address. The hope
3644 * is that the pages will be needed soon and this will lower the number of
3647 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
3648 * not ready to be mapped: not up-to-date, locked, etc.
3650 * This function is called with the page table lock taken. In the split ptlock
3651 * case the page table lock only protects only those entries which belong to
3652 * the page table corresponding to the fault address.
3654 * This function doesn't cross the VMA boundaries, in order to call map_pages()
3657 * fault_around_pages() defines how many pages we'll try to map.
3658 * do_fault_around() expects it to return a power of two less than or equal to
3661 * The virtual address of the area that we map is naturally aligned to the
3662 * fault_around_pages() value (and therefore to page order). This way it's
3663 * easier to guarantee that we don't cross page table boundaries.
3665 static int do_fault_around(struct vm_fault *vmf)
3667 unsigned long address = vmf->address, nr_pages, mask;
3668 pgoff_t start_pgoff = vmf->pgoff;
3672 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3673 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3675 vmf->address = max(address & mask, vmf->vma->vm_start);
3676 off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3680 * end_pgoff is either end of page table or end of vma
3681 * or fault_around_pages() from start_pgoff, depending what is nearest.
3683 end_pgoff = start_pgoff -
3684 ((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
3686 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
3687 start_pgoff + nr_pages - 1);
3689 if (pmd_none(*vmf->pmd)) {
3690 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
3692 if (!vmf->prealloc_pte)
3694 smp_wmb(); /* See comment in __pte_alloc() */
3697 vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
3699 /* Huge page is mapped? Page fault is solved */
3700 if (pmd_trans_huge(*vmf->pmd)) {
3701 ret = VM_FAULT_NOPAGE;
3705 /* ->map_pages() haven't done anything useful. Cold page cache? */
3709 /* check if the page fault is solved */
3710 vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
3711 if (!pte_none(*vmf->pte))
3712 ret = VM_FAULT_NOPAGE;
3713 pte_unmap_unlock(vmf->pte, vmf->ptl);
3715 vmf->address = address;
3720 static int do_read_fault(struct vm_fault *vmf)
3722 struct vm_area_struct *vma = vmf->vma;
3726 * Let's call ->map_pages() first and use ->fault() as fallback
3727 * if page by the offset is not ready to be mapped (cold cache or
3730 if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
3731 ret = do_fault_around(vmf);
3736 ret = __do_fault(vmf);
3737 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3740 ret |= finish_fault(vmf);
3741 unlock_page(vmf->page);
3742 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3743 put_page(vmf->page);
3747 static int do_cow_fault(struct vm_fault *vmf)
3749 struct vm_area_struct *vma = vmf->vma;
3752 if (unlikely(anon_vma_prepare(vma)))
3753 return VM_FAULT_OOM;
3755 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3757 return VM_FAULT_OOM;
3759 if (mem_cgroup_try_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL,
3760 &vmf->memcg, false)) {
3761 put_page(vmf->cow_page);
3762 return VM_FAULT_OOM;
3765 ret = __do_fault(vmf);
3766 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3768 if (ret & VM_FAULT_DONE_COW)
3771 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
3772 __SetPageUptodate(vmf->cow_page);
3774 ret |= finish_fault(vmf);
3775 unlock_page(vmf->page);
3776 put_page(vmf->page);
3777 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3781 mem_cgroup_cancel_charge(vmf->cow_page, vmf->memcg, false);
3782 put_page(vmf->cow_page);
3786 static int do_shared_fault(struct vm_fault *vmf)
3788 struct vm_area_struct *vma = vmf->vma;
3791 ret = __do_fault(vmf);
3792 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3796 * Check if the backing address space wants to know that the page is
3797 * about to become writable
3799 if (vma->vm_ops->page_mkwrite) {
3800 unlock_page(vmf->page);
3801 tmp = do_page_mkwrite(vmf);
3802 if (unlikely(!tmp ||
3803 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3804 put_page(vmf->page);
3809 ret |= finish_fault(vmf);
3810 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3812 unlock_page(vmf->page);
3813 put_page(vmf->page);
3817 fault_dirty_shared_page(vma, vmf->page);
3822 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3823 * but allow concurrent faults).
3824 * The mmap_sem may have been released depending on flags and our
3825 * return value. See filemap_fault() and __lock_page_or_retry().
3827 static int do_fault(struct vm_fault *vmf)
3829 struct vm_area_struct *vma = vmf->vma;
3833 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
3835 if (!vma->vm_ops->fault) {
3837 * If we find a migration pmd entry or a none pmd entry, which
3838 * should never happen, return SIGBUS
3840 if (unlikely(!pmd_present(*vmf->pmd)))
3841 ret = VM_FAULT_SIGBUS;
3843 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
3848 * Make sure this is not a temporary clearing of pte
3849 * by holding ptl and checking again. A R/M/W update
3850 * of pte involves: take ptl, clearing the pte so that
3851 * we don't have concurrent modification by hardware
3852 * followed by an update.
3854 if (unlikely(pte_none(*vmf->pte)))
3855 ret = VM_FAULT_SIGBUS;
3857 ret = VM_FAULT_NOPAGE;
3859 pte_unmap_unlock(vmf->pte, vmf->ptl);
3861 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
3862 ret = do_read_fault(vmf);
3863 else if (!(vma->vm_flags & VM_SHARED))
3864 ret = do_cow_fault(vmf);
3866 ret = do_shared_fault(vmf);
3868 /* preallocated pagetable is unused: free it */
3869 if (vmf->prealloc_pte) {
3870 pte_free(vma->vm_mm, vmf->prealloc_pte);
3871 vmf->prealloc_pte = NULL;
3876 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3877 unsigned long addr, int page_nid,
3882 count_vm_numa_event(NUMA_HINT_FAULTS);
3883 if (page_nid == numa_node_id()) {
3884 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3885 *flags |= TNF_FAULT_LOCAL;
3888 return mpol_misplaced(page, vma, addr);
3891 static int do_numa_page(struct vm_fault *vmf)
3893 struct vm_area_struct *vma = vmf->vma;
3894 struct page *page = NULL;
3898 bool migrated = false;
3900 bool was_writable = pte_savedwrite(vmf->orig_pte);
3904 * The "pte" at this point cannot be used safely without
3905 * validation through pte_unmap_same(). It's of NUMA type but
3906 * the pfn may be screwed if the read is non atomic.
3908 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
3909 spin_lock(vmf->ptl);
3910 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
3911 pte_unmap_unlock(vmf->pte, vmf->ptl);
3916 * Make it present again, Depending on how arch implementes non
3917 * accessible ptes, some can allow access by kernel mode.
3919 pte = ptep_modify_prot_start(vma->vm_mm, vmf->address, vmf->pte);
3920 pte = pte_modify(pte, vma->vm_page_prot);
3921 pte = pte_mkyoung(pte);
3923 pte = pte_mkwrite(pte);
3924 ptep_modify_prot_commit(vma->vm_mm, vmf->address, vmf->pte, pte);
3925 update_mmu_cache(vma, vmf->address, vmf->pte);
3927 page = vm_normal_page(vma, vmf->address, pte);
3929 pte_unmap_unlock(vmf->pte, vmf->ptl);
3933 /* TODO: handle PTE-mapped THP */
3934 if (PageCompound(page)) {
3935 pte_unmap_unlock(vmf->pte, vmf->ptl);
3940 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
3941 * much anyway since they can be in shared cache state. This misses
3942 * the case where a mapping is writable but the process never writes
3943 * to it but pte_write gets cleared during protection updates and
3944 * pte_dirty has unpredictable behaviour between PTE scan updates,
3945 * background writeback, dirty balancing and application behaviour.
3947 if (!pte_write(pte))
3948 flags |= TNF_NO_GROUP;
3951 * Flag if the page is shared between multiple address spaces. This
3952 * is later used when determining whether to group tasks together
3954 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
3955 flags |= TNF_SHARED;
3957 last_cpupid = page_cpupid_last(page);
3958 page_nid = page_to_nid(page);
3959 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
3961 pte_unmap_unlock(vmf->pte, vmf->ptl);
3962 if (target_nid == -1) {
3967 /* Migrate to the requested node */
3968 migrated = migrate_misplaced_page(page, vma, target_nid);
3970 page_nid = target_nid;
3971 flags |= TNF_MIGRATED;
3973 flags |= TNF_MIGRATE_FAIL;
3977 task_numa_fault(last_cpupid, page_nid, 1, flags);
3981 static inline int create_huge_pmd(struct vm_fault *vmf)
3983 if (vma_is_anonymous(vmf->vma))
3984 return do_huge_pmd_anonymous_page(vmf);
3985 if (vmf->vma->vm_ops->huge_fault)
3986 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
3987 return VM_FAULT_FALLBACK;
3990 static int wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
3992 if (vma_is_anonymous(vmf->vma))
3993 return do_huge_pmd_wp_page(vmf, orig_pmd);
3994 if (vmf->vma->vm_ops->huge_fault)
3995 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
3997 /* COW handled on pte level: split pmd */
3998 VM_BUG_ON_VMA(vmf->vma->vm_flags & VM_SHARED, vmf->vma);
3999 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4001 return VM_FAULT_FALLBACK;
4004 static inline bool vma_is_accessible(struct vm_area_struct *vma)
4006 return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
4009 static int create_huge_pud(struct vm_fault *vmf)
4011 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4012 /* No support for anonymous transparent PUD pages yet */
4013 if (vma_is_anonymous(vmf->vma))
4014 return VM_FAULT_FALLBACK;
4015 if (vmf->vma->vm_ops->huge_fault)
4016 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4017 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4018 return VM_FAULT_FALLBACK;
4021 static int wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4023 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4024 /* No support for anonymous transparent PUD pages yet */
4025 if (vma_is_anonymous(vmf->vma))
4026 return VM_FAULT_FALLBACK;
4027 if (vmf->vma->vm_ops->huge_fault)
4028 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4029 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4030 return VM_FAULT_FALLBACK;
4034 * These routines also need to handle stuff like marking pages dirty
4035 * and/or accessed for architectures that don't do it in hardware (most
4036 * RISC architectures). The early dirtying is also good on the i386.
4038 * There is also a hook called "update_mmu_cache()" that architectures
4039 * with external mmu caches can use to update those (ie the Sparc or
4040 * PowerPC hashed page tables that act as extended TLBs).
4042 * We enter with non-exclusive mmap_sem (to exclude vma changes, but allow
4043 * concurrent faults).
4045 * The mmap_sem may have been released depending on flags and our return value.
4046 * See filemap_fault() and __lock_page_or_retry().
4048 static int handle_pte_fault(struct vm_fault *vmf)
4052 if (unlikely(pmd_none(*vmf->pmd))) {
4054 * Leave __pte_alloc() until later: because vm_ops->fault may
4055 * want to allocate huge page, and if we expose page table
4056 * for an instant, it will be difficult to retract from
4057 * concurrent faults and from rmap lookups.
4061 /* See comment in pte_alloc_one_map() */
4062 if (pmd_devmap_trans_unstable(vmf->pmd))
4065 * A regular pmd is established and it can't morph into a huge
4066 * pmd from under us anymore at this point because we hold the
4067 * mmap_sem read mode and khugepaged takes it in write mode.
4068 * So now it's safe to run pte_offset_map().
4070 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4071 vmf->orig_pte = *vmf->pte;
4074 * some architectures can have larger ptes than wordsize,
4075 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4076 * CONFIG_32BIT=y, so READ_ONCE or ACCESS_ONCE cannot guarantee
4077 * atomic accesses. The code below just needs a consistent
4078 * view for the ifs and we later double check anyway with the
4079 * ptl lock held. So here a barrier will do.
4082 if (pte_none(vmf->orig_pte)) {
4083 pte_unmap(vmf->pte);
4089 if (vma_is_anonymous(vmf->vma))
4090 return do_anonymous_page(vmf);
4092 return do_fault(vmf);
4095 if (!pte_present(vmf->orig_pte))
4096 return do_swap_page(vmf);
4098 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4099 return do_numa_page(vmf);
4101 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4102 spin_lock(vmf->ptl);
4103 entry = vmf->orig_pte;
4104 if (unlikely(!pte_same(*vmf->pte, entry)))
4106 if (vmf->flags & FAULT_FLAG_WRITE) {
4107 if (!pte_write(entry))
4108 return do_wp_page(vmf);
4109 entry = pte_mkdirty(entry);
4111 entry = pte_mkyoung(entry);
4112 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4113 vmf->flags & FAULT_FLAG_WRITE)) {
4114 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4117 * This is needed only for protection faults but the arch code
4118 * is not yet telling us if this is a protection fault or not.
4119 * This still avoids useless tlb flushes for .text page faults
4122 if (vmf->flags & FAULT_FLAG_WRITE)
4123 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4126 pte_unmap_unlock(vmf->pte, vmf->ptl);
4131 * By the time we get here, we already hold the mm semaphore
4133 * The mmap_sem may have been released depending on flags and our
4134 * return value. See filemap_fault() and __lock_page_or_retry().
4136 static int __handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4139 struct vm_fault vmf = {
4141 .address = address & PAGE_MASK,
4143 .pgoff = linear_page_index(vma, address),
4144 .gfp_mask = __get_fault_gfp_mask(vma),
4146 unsigned int dirty = flags & FAULT_FLAG_WRITE;
4147 struct mm_struct *mm = vma->vm_mm;
4152 pgd = pgd_offset(mm, address);
4153 p4d = p4d_alloc(mm, pgd, address);
4155 return VM_FAULT_OOM;
4157 vmf.pud = pud_alloc(mm, p4d, address);
4159 return VM_FAULT_OOM;
4160 if (pud_none(*vmf.pud) && transparent_hugepage_enabled(vma)) {
4161 ret = create_huge_pud(&vmf);
4162 if (!(ret & VM_FAULT_FALLBACK))
4165 pud_t orig_pud = *vmf.pud;
4168 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4170 /* NUMA case for anonymous PUDs would go here */
4172 if (dirty && !pud_write(orig_pud)) {
4173 ret = wp_huge_pud(&vmf, orig_pud);
4174 if (!(ret & VM_FAULT_FALLBACK))
4177 huge_pud_set_accessed(&vmf, orig_pud);
4183 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4185 return VM_FAULT_OOM;
4186 if (pmd_none(*vmf.pmd) && transparent_hugepage_enabled(vma)) {
4187 ret = create_huge_pmd(&vmf);
4188 if (!(ret & VM_FAULT_FALLBACK))
4191 pmd_t orig_pmd = *vmf.pmd;
4194 if (unlikely(is_swap_pmd(orig_pmd))) {
4195 VM_BUG_ON(thp_migration_supported() &&
4196 !is_pmd_migration_entry(orig_pmd));
4197 if (is_pmd_migration_entry(orig_pmd))
4198 pmd_migration_entry_wait(mm, vmf.pmd);
4201 if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
4202 if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
4203 return do_huge_pmd_numa_page(&vmf, orig_pmd);
4205 if (dirty && !pmd_write(orig_pmd)) {
4206 ret = wp_huge_pmd(&vmf, orig_pmd);
4207 if (!(ret & VM_FAULT_FALLBACK))
4210 huge_pmd_set_accessed(&vmf, orig_pmd);
4216 return handle_pte_fault(&vmf);
4220 * By the time we get here, we already hold the mm semaphore
4222 * The mmap_sem may have been released depending on flags and our
4223 * return value. See filemap_fault() and __lock_page_or_retry().
4225 int handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4230 __set_current_state(TASK_RUNNING);
4232 count_vm_event(PGFAULT);
4233 count_memcg_event_mm(vma->vm_mm, PGFAULT);
4235 /* do counter updates before entering really critical section. */
4236 check_sync_rss_stat(current);
4238 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4239 flags & FAULT_FLAG_INSTRUCTION,
4240 flags & FAULT_FLAG_REMOTE))
4241 return VM_FAULT_SIGSEGV;
4244 * Enable the memcg OOM handling for faults triggered in user
4245 * space. Kernel faults are handled more gracefully.
4247 if (flags & FAULT_FLAG_USER)
4248 mem_cgroup_oom_enable();
4250 if (unlikely(is_vm_hugetlb_page(vma)))
4251 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4253 ret = __handle_mm_fault(vma, address, flags);
4255 if (flags & FAULT_FLAG_USER) {
4256 mem_cgroup_oom_disable();
4258 * The task may have entered a memcg OOM situation but
4259 * if the allocation error was handled gracefully (no
4260 * VM_FAULT_OOM), there is no need to kill anything.
4261 * Just clean up the OOM state peacefully.
4263 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4264 mem_cgroup_oom_synchronize(false);
4269 EXPORT_SYMBOL_GPL(handle_mm_fault);
4271 #ifndef __PAGETABLE_P4D_FOLDED
4273 * Allocate p4d page table.
4274 * We've already handled the fast-path in-line.
4276 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4278 p4d_t *new = p4d_alloc_one(mm, address);
4282 smp_wmb(); /* See comment in __pte_alloc */
4284 spin_lock(&mm->page_table_lock);
4285 if (pgd_present(*pgd)) /* Another has populated it */
4288 pgd_populate(mm, pgd, new);
4289 spin_unlock(&mm->page_table_lock);
4292 #endif /* __PAGETABLE_P4D_FOLDED */
4294 #ifndef __PAGETABLE_PUD_FOLDED
4296 * Allocate page upper directory.
4297 * We've already handled the fast-path in-line.
4299 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4301 pud_t *new = pud_alloc_one(mm, address);
4305 smp_wmb(); /* See comment in __pte_alloc */
4307 spin_lock(&mm->page_table_lock);
4308 #ifndef __ARCH_HAS_5LEVEL_HACK
4309 if (p4d_present(*p4d)) /* Another has populated it */
4312 p4d_populate(mm, p4d, new);
4314 if (pgd_present(*p4d)) /* Another has populated it */
4317 pgd_populate(mm, p4d, new);
4318 #endif /* __ARCH_HAS_5LEVEL_HACK */
4319 spin_unlock(&mm->page_table_lock);
4322 #endif /* __PAGETABLE_PUD_FOLDED */
4324 #ifndef __PAGETABLE_PMD_FOLDED
4326 * Allocate page middle directory.
4327 * We've already handled the fast-path in-line.
4329 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4332 pmd_t *new = pmd_alloc_one(mm, address);
4336 smp_wmb(); /* See comment in __pte_alloc */
4338 ptl = pud_lock(mm, pud);
4339 #ifndef __ARCH_HAS_4LEVEL_HACK
4340 if (!pud_present(*pud)) {
4342 pud_populate(mm, pud, new);
4343 } else /* Another has populated it */
4346 if (!pgd_present(*pud)) {
4348 pgd_populate(mm, pud, new);
4349 } else /* Another has populated it */
4351 #endif /* __ARCH_HAS_4LEVEL_HACK */
4355 #endif /* __PAGETABLE_PMD_FOLDED */
4357 static int __follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4358 unsigned long *start, unsigned long *end,
4359 pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4367 pgd = pgd_offset(mm, address);
4368 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4371 p4d = p4d_offset(pgd, address);
4372 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4375 pud = pud_offset(p4d, address);
4376 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4379 pmd = pmd_offset(pud, address);
4380 VM_BUG_ON(pmd_trans_huge(*pmd));
4382 if (pmd_huge(*pmd)) {
4387 *start = address & PMD_MASK;
4388 *end = *start + PMD_SIZE;
4389 mmu_notifier_invalidate_range_start(mm, *start, *end);
4391 *ptlp = pmd_lock(mm, pmd);
4392 if (pmd_huge(*pmd)) {
4398 mmu_notifier_invalidate_range_end(mm, *start, *end);
4401 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4405 *start = address & PAGE_MASK;
4406 *end = *start + PAGE_SIZE;
4407 mmu_notifier_invalidate_range_start(mm, *start, *end);
4409 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4410 if (!pte_present(*ptep))
4415 pte_unmap_unlock(ptep, *ptlp);
4417 mmu_notifier_invalidate_range_end(mm, *start, *end);
4422 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4423 pte_t **ptepp, spinlock_t **ptlp)
4427 /* (void) is needed to make gcc happy */
4428 (void) __cond_lock(*ptlp,
4429 !(res = __follow_pte_pmd(mm, address, NULL, NULL,
4430 ptepp, NULL, ptlp)));
4434 int follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4435 unsigned long *start, unsigned long *end,
4436 pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4440 /* (void) is needed to make gcc happy */
4441 (void) __cond_lock(*ptlp,
4442 !(res = __follow_pte_pmd(mm, address, start, end,
4443 ptepp, pmdpp, ptlp)));
4446 EXPORT_SYMBOL(follow_pte_pmd);
4449 * follow_pfn - look up PFN at a user virtual address
4450 * @vma: memory mapping
4451 * @address: user virtual address
4452 * @pfn: location to store found PFN
4454 * Only IO mappings and raw PFN mappings are allowed.
4456 * Returns zero and the pfn at @pfn on success, -ve otherwise.
4458 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4465 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4468 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4471 *pfn = pte_pfn(*ptep);
4472 pte_unmap_unlock(ptep, ptl);
4475 EXPORT_SYMBOL(follow_pfn);
4477 #ifdef CONFIG_HAVE_IOREMAP_PROT
4478 int follow_phys(struct vm_area_struct *vma,
4479 unsigned long address, unsigned int flags,
4480 unsigned long *prot, resource_size_t *phys)
4486 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4489 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4493 if ((flags & FOLL_WRITE) && !pte_write(pte))
4496 *prot = pgprot_val(pte_pgprot(pte));
4497 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4501 pte_unmap_unlock(ptep, ptl);
4506 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4507 void *buf, int len, int write)
4509 resource_size_t phys_addr;
4510 unsigned long prot = 0;
4511 void __iomem *maddr;
4512 int offset = addr & (PAGE_SIZE-1);
4514 if (follow_phys(vma, addr, write, &prot, &phys_addr))
4517 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4522 memcpy_toio(maddr + offset, buf, len);
4524 memcpy_fromio(buf, maddr + offset, len);
4529 EXPORT_SYMBOL_GPL(generic_access_phys);
4533 * Access another process' address space as given in mm. If non-NULL, use the
4534 * given task for page fault accounting.
4536 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4537 unsigned long addr, void *buf, int len, unsigned int gup_flags)
4539 struct vm_area_struct *vma;
4540 void *old_buf = buf;
4541 int write = gup_flags & FOLL_WRITE;
4543 down_read(&mm->mmap_sem);
4544 /* ignore errors, just check how much was successfully transferred */
4546 int bytes, ret, offset;
4548 struct page *page = NULL;
4550 ret = get_user_pages_remote(tsk, mm, addr, 1,
4551 gup_flags, &page, &vma, NULL);
4553 #ifndef CONFIG_HAVE_IOREMAP_PROT
4557 * Check if this is a VM_IO | VM_PFNMAP VMA, which
4558 * we can access using slightly different code.
4560 vma = find_vma(mm, addr);
4561 if (!vma || vma->vm_start > addr)
4563 if (vma->vm_ops && vma->vm_ops->access)
4564 ret = vma->vm_ops->access(vma, addr, buf,
4572 offset = addr & (PAGE_SIZE-1);
4573 if (bytes > PAGE_SIZE-offset)
4574 bytes = PAGE_SIZE-offset;
4578 copy_to_user_page(vma, page, addr,
4579 maddr + offset, buf, bytes);
4580 set_page_dirty_lock(page);
4582 copy_from_user_page(vma, page, addr,
4583 buf, maddr + offset, bytes);
4592 up_read(&mm->mmap_sem);
4594 return buf - old_buf;
4598 * access_remote_vm - access another process' address space
4599 * @mm: the mm_struct of the target address space
4600 * @addr: start address to access
4601 * @buf: source or destination buffer
4602 * @len: number of bytes to transfer
4603 * @gup_flags: flags modifying lookup behaviour
4605 * The caller must hold a reference on @mm.
4607 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
4608 void *buf, int len, unsigned int gup_flags)
4610 return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
4614 * Access another process' address space.
4615 * Source/target buffer must be kernel space,
4616 * Do not walk the page table directly, use get_user_pages
4618 int access_process_vm(struct task_struct *tsk, unsigned long addr,
4619 void *buf, int len, unsigned int gup_flags)
4621 struct mm_struct *mm;
4624 mm = get_task_mm(tsk);
4628 ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
4634 EXPORT_SYMBOL_GPL(access_process_vm);
4637 * Print the name of a VMA.
4639 void print_vma_addr(char *prefix, unsigned long ip)
4641 struct mm_struct *mm = current->mm;
4642 struct vm_area_struct *vma;
4645 * Do not print if we are in atomic
4646 * contexts (in exception stacks, etc.):
4648 if (preempt_count())
4651 down_read(&mm->mmap_sem);
4652 vma = find_vma(mm, ip);
4653 if (vma && vma->vm_file) {
4654 struct file *f = vma->vm_file;
4655 char *buf = (char *)__get_free_page(GFP_KERNEL);
4659 p = file_path(f, buf, PAGE_SIZE);
4662 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
4664 vma->vm_end - vma->vm_start);
4665 free_page((unsigned long)buf);
4668 up_read(&mm->mmap_sem);
4671 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4672 void __might_fault(const char *file, int line)
4675 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4676 * holding the mmap_sem, this is safe because kernel memory doesn't
4677 * get paged out, therefore we'll never actually fault, and the
4678 * below annotations will generate false positives.
4680 if (uaccess_kernel())
4682 if (pagefault_disabled())
4684 __might_sleep(file, line, 0);
4685 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4687 might_lock_read(¤t->mm->mmap_sem);
4690 EXPORT_SYMBOL(__might_fault);
4693 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4694 static void clear_gigantic_page(struct page *page,
4696 unsigned int pages_per_huge_page)
4699 struct page *p = page;
4702 for (i = 0; i < pages_per_huge_page;
4703 i++, p = mem_map_next(p, page, i)) {
4705 clear_user_highpage(p, addr + i * PAGE_SIZE);
4708 void clear_huge_page(struct page *page,
4709 unsigned long addr_hint, unsigned int pages_per_huge_page)
4712 unsigned long addr = addr_hint &
4713 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4715 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4716 clear_gigantic_page(page, addr, pages_per_huge_page);
4720 /* Clear sub-page to access last to keep its cache lines hot */
4722 n = (addr_hint - addr) / PAGE_SIZE;
4723 if (2 * n <= pages_per_huge_page) {
4724 /* If sub-page to access in first half of huge page */
4727 /* Clear sub-pages at the end of huge page */
4728 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
4730 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4733 /* If sub-page to access in second half of huge page */
4734 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
4735 l = pages_per_huge_page - n;
4736 /* Clear sub-pages at the begin of huge page */
4737 for (i = 0; i < base; i++) {
4739 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4743 * Clear remaining sub-pages in left-right-left-right pattern
4744 * towards the sub-page to access
4746 for (i = 0; i < l; i++) {
4747 int left_idx = base + i;
4748 int right_idx = base + 2 * l - 1 - i;
4751 clear_user_highpage(page + left_idx,
4752 addr + left_idx * PAGE_SIZE);
4754 clear_user_highpage(page + right_idx,
4755 addr + right_idx * PAGE_SIZE);
4759 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4761 struct vm_area_struct *vma,
4762 unsigned int pages_per_huge_page)
4765 struct page *dst_base = dst;
4766 struct page *src_base = src;
4768 for (i = 0; i < pages_per_huge_page; ) {
4770 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4773 dst = mem_map_next(dst, dst_base, i);
4774 src = mem_map_next(src, src_base, i);
4778 void copy_user_huge_page(struct page *dst, struct page *src,
4779 unsigned long addr, struct vm_area_struct *vma,
4780 unsigned int pages_per_huge_page)
4784 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4785 copy_user_gigantic_page(dst, src, addr, vma,
4786 pages_per_huge_page);
4791 for (i = 0; i < pages_per_huge_page; i++) {
4793 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
4797 long copy_huge_page_from_user(struct page *dst_page,
4798 const void __user *usr_src,
4799 unsigned int pages_per_huge_page,
4800 bool allow_pagefault)
4802 void *src = (void *)usr_src;
4804 unsigned long i, rc = 0;
4805 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
4806 struct page *subpage = dst_page;
4808 for (i = 0; i < pages_per_huge_page;
4809 i++, subpage = mem_map_next(subpage, dst_page, i)) {
4810 if (allow_pagefault)
4811 page_kaddr = kmap(subpage);
4813 page_kaddr = kmap_atomic(subpage);
4814 rc = copy_from_user(page_kaddr,
4815 (const void __user *)(src + i * PAGE_SIZE),
4817 if (allow_pagefault)
4820 kunmap_atomic(page_kaddr);
4822 ret_val -= (PAGE_SIZE - rc);
4830 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
4832 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
4834 static struct kmem_cache *page_ptl_cachep;
4836 void __init ptlock_cache_init(void)
4838 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
4842 bool ptlock_alloc(struct page *page)
4846 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
4853 void ptlock_free(struct page *page)
4855 kmem_cache_free(page_ptl_cachep, page->ptl);