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 #endif /* HAVE_GENERIC_MMU_GATHER */
340 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
343 * See the comment near struct mmu_table_batch.
347 * If we want tlb_remove_table() to imply TLB invalidates.
349 static inline void tlb_table_invalidate(struct mmu_gather *tlb)
351 #ifdef CONFIG_HAVE_RCU_TABLE_INVALIDATE
353 * Invalidate page-table caches used by hardware walkers. Then we still
354 * need to RCU-sched wait while freeing the pages because software
355 * walkers can still be in-flight.
357 tlb_flush_mmu_tlbonly(tlb);
361 static void tlb_remove_table_smp_sync(void *arg)
363 /* Simply deliver the interrupt */
366 static void tlb_remove_table_one(void *table)
369 * This isn't an RCU grace period and hence the page-tables cannot be
370 * assumed to be actually RCU-freed.
372 * It is however sufficient for software page-table walkers that rely on
373 * IRQ disabling. See the comment near struct mmu_table_batch.
375 smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
376 __tlb_remove_table(table);
379 static void tlb_remove_table_rcu(struct rcu_head *head)
381 struct mmu_table_batch *batch;
384 batch = container_of(head, struct mmu_table_batch, rcu);
386 for (i = 0; i < batch->nr; i++)
387 __tlb_remove_table(batch->tables[i]);
389 free_page((unsigned long)batch);
392 void tlb_table_flush(struct mmu_gather *tlb)
394 struct mmu_table_batch **batch = &tlb->batch;
397 tlb_table_invalidate(tlb);
398 call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
403 void tlb_remove_table(struct mmu_gather *tlb, void *table)
405 struct mmu_table_batch **batch = &tlb->batch;
407 if (*batch == NULL) {
408 *batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
409 if (*batch == NULL) {
410 tlb_table_invalidate(tlb);
411 tlb_remove_table_one(table);
417 (*batch)->tables[(*batch)->nr++] = table;
418 if ((*batch)->nr == MAX_TABLE_BATCH)
419 tlb_table_flush(tlb);
422 #endif /* CONFIG_HAVE_RCU_TABLE_FREE */
425 * Called to initialize an (on-stack) mmu_gather structure for page-table
426 * tear-down from @mm. The @fullmm argument is used when @mm is without
427 * users and we're going to destroy the full address space (exit/execve).
429 void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm,
430 unsigned long start, unsigned long end)
432 arch_tlb_gather_mmu(tlb, mm, start, end);
433 inc_tlb_flush_pending(tlb->mm);
436 void tlb_finish_mmu(struct mmu_gather *tlb,
437 unsigned long start, unsigned long end)
440 * If there are parallel threads are doing PTE changes on same range
441 * under non-exclusive lock(e.g., mmap_sem read-side) but defer TLB
442 * flush by batching, a thread has stable TLB entry can fail to flush
443 * the TLB by observing pte_none|!pte_dirty, for example so flush TLB
444 * forcefully if we detect parallel PTE batching threads.
446 bool force = mm_tlb_flush_nested(tlb->mm);
448 arch_tlb_finish_mmu(tlb, start, end, force);
449 dec_tlb_flush_pending(tlb->mm);
453 * Note: this doesn't free the actual pages themselves. That
454 * has been handled earlier when unmapping all the memory regions.
456 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
459 pgtable_t token = pmd_pgtable(*pmd);
461 pte_free_tlb(tlb, token, addr);
462 atomic_long_dec(&tlb->mm->nr_ptes);
465 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
466 unsigned long addr, unsigned long end,
467 unsigned long floor, unsigned long ceiling)
474 pmd = pmd_offset(pud, addr);
476 next = pmd_addr_end(addr, end);
477 if (pmd_none_or_clear_bad(pmd))
479 free_pte_range(tlb, pmd, addr);
480 } while (pmd++, addr = next, addr != end);
490 if (end - 1 > ceiling - 1)
493 pmd = pmd_offset(pud, start);
495 pmd_free_tlb(tlb, pmd, start);
496 mm_dec_nr_pmds(tlb->mm);
499 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
500 unsigned long addr, unsigned long end,
501 unsigned long floor, unsigned long ceiling)
508 pud = pud_offset(p4d, addr);
510 next = pud_addr_end(addr, end);
511 if (pud_none_or_clear_bad(pud))
513 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
514 } while (pud++, addr = next, addr != end);
524 if (end - 1 > ceiling - 1)
527 pud = pud_offset(p4d, start);
529 pud_free_tlb(tlb, pud, start);
532 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
533 unsigned long addr, unsigned long end,
534 unsigned long floor, unsigned long ceiling)
541 p4d = p4d_offset(pgd, addr);
543 next = p4d_addr_end(addr, end);
544 if (p4d_none_or_clear_bad(p4d))
546 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
547 } while (p4d++, addr = next, addr != end);
553 ceiling &= PGDIR_MASK;
557 if (end - 1 > ceiling - 1)
560 p4d = p4d_offset(pgd, start);
562 p4d_free_tlb(tlb, p4d, start);
566 * This function frees user-level page tables of a process.
568 void free_pgd_range(struct mmu_gather *tlb,
569 unsigned long addr, unsigned long end,
570 unsigned long floor, unsigned long ceiling)
576 * The next few lines have given us lots of grief...
578 * Why are we testing PMD* at this top level? Because often
579 * there will be no work to do at all, and we'd prefer not to
580 * go all the way down to the bottom just to discover that.
582 * Why all these "- 1"s? Because 0 represents both the bottom
583 * of the address space and the top of it (using -1 for the
584 * top wouldn't help much: the masks would do the wrong thing).
585 * The rule is that addr 0 and floor 0 refer to the bottom of
586 * the address space, but end 0 and ceiling 0 refer to the top
587 * Comparisons need to use "end - 1" and "ceiling - 1" (though
588 * that end 0 case should be mythical).
590 * Wherever addr is brought up or ceiling brought down, we must
591 * be careful to reject "the opposite 0" before it confuses the
592 * subsequent tests. But what about where end is brought down
593 * by PMD_SIZE below? no, end can't go down to 0 there.
595 * Whereas we round start (addr) and ceiling down, by different
596 * masks at different levels, in order to test whether a table
597 * now has no other vmas using it, so can be freed, we don't
598 * bother to round floor or end up - the tests don't need that.
612 if (end - 1 > ceiling - 1)
617 * We add page table cache pages with PAGE_SIZE,
618 * (see pte_free_tlb()), flush the tlb if we need
620 tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
621 pgd = pgd_offset(tlb->mm, addr);
623 next = pgd_addr_end(addr, end);
624 if (pgd_none_or_clear_bad(pgd))
626 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
627 } while (pgd++, addr = next, addr != end);
630 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
631 unsigned long floor, unsigned long ceiling)
634 struct vm_area_struct *next = vma->vm_next;
635 unsigned long addr = vma->vm_start;
638 * Hide vma from rmap and truncate_pagecache before freeing
641 unlink_anon_vmas(vma);
642 unlink_file_vma(vma);
644 if (is_vm_hugetlb_page(vma)) {
645 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
646 floor, next ? next->vm_start : ceiling);
649 * Optimization: gather nearby vmas into one call down
651 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
652 && !is_vm_hugetlb_page(next)) {
655 unlink_anon_vmas(vma);
656 unlink_file_vma(vma);
658 free_pgd_range(tlb, addr, vma->vm_end,
659 floor, next ? next->vm_start : ceiling);
665 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd, unsigned long address)
668 pgtable_t new = pte_alloc_one(mm, address);
673 * Ensure all pte setup (eg. pte page lock and page clearing) are
674 * visible before the pte is made visible to other CPUs by being
675 * put into page tables.
677 * The other side of the story is the pointer chasing in the page
678 * table walking code (when walking the page table without locking;
679 * ie. most of the time). Fortunately, these data accesses consist
680 * of a chain of data-dependent loads, meaning most CPUs (alpha
681 * being the notable exception) will already guarantee loads are
682 * seen in-order. See the alpha page table accessors for the
683 * smp_read_barrier_depends() barriers in page table walking code.
685 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
687 ptl = pmd_lock(mm, pmd);
688 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
689 atomic_long_inc(&mm->nr_ptes);
690 pmd_populate(mm, pmd, new);
699 int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
701 pte_t *new = pte_alloc_one_kernel(&init_mm, address);
705 smp_wmb(); /* See comment in __pte_alloc */
707 spin_lock(&init_mm.page_table_lock);
708 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
709 pmd_populate_kernel(&init_mm, pmd, new);
712 spin_unlock(&init_mm.page_table_lock);
714 pte_free_kernel(&init_mm, new);
718 static inline void init_rss_vec(int *rss)
720 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
723 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
727 if (current->mm == mm)
729 for (i = 0; i < NR_MM_COUNTERS; i++)
731 add_mm_counter(mm, i, rss[i]);
735 * This function is called to print an error when a bad pte
736 * is found. For example, we might have a PFN-mapped pte in
737 * a region that doesn't allow it.
739 * The calling function must still handle the error.
741 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
742 pte_t pte, struct page *page)
744 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
745 p4d_t *p4d = p4d_offset(pgd, addr);
746 pud_t *pud = pud_offset(p4d, addr);
747 pmd_t *pmd = pmd_offset(pud, addr);
748 struct address_space *mapping;
750 static unsigned long resume;
751 static unsigned long nr_shown;
752 static unsigned long nr_unshown;
755 * Allow a burst of 60 reports, then keep quiet for that minute;
756 * or allow a steady drip of one report per second.
758 if (nr_shown == 60) {
759 if (time_before(jiffies, resume)) {
764 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
771 resume = jiffies + 60 * HZ;
773 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
774 index = linear_page_index(vma, addr);
776 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
778 (long long)pte_val(pte), (long long)pmd_val(*pmd));
780 dump_page(page, "bad pte");
781 pr_alert("addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
782 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
784 * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y
786 pr_alert("file:%pD fault:%pf mmap:%pf readpage:%pf\n",
788 vma->vm_ops ? vma->vm_ops->fault : NULL,
789 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
790 mapping ? mapping->a_ops->readpage : NULL);
792 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
796 * vm_normal_page -- This function gets the "struct page" associated with a pte.
798 * "Special" mappings do not wish to be associated with a "struct page" (either
799 * it doesn't exist, or it exists but they don't want to touch it). In this
800 * case, NULL is returned here. "Normal" mappings do have a struct page.
802 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
803 * pte bit, in which case this function is trivial. Secondly, an architecture
804 * may not have a spare pte bit, which requires a more complicated scheme,
807 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
808 * special mapping (even if there are underlying and valid "struct pages").
809 * COWed pages of a VM_PFNMAP are always normal.
811 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
812 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
813 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
814 * mapping will always honor the rule
816 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
818 * And for normal mappings this is false.
820 * This restricts such mappings to be a linear translation from virtual address
821 * to pfn. To get around this restriction, we allow arbitrary mappings so long
822 * as the vma is not a COW mapping; in that case, we know that all ptes are
823 * special (because none can have been COWed).
826 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
828 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
829 * page" backing, however the difference is that _all_ pages with a struct
830 * page (that is, those where pfn_valid is true) are refcounted and considered
831 * normal pages by the VM. The disadvantage is that pages are refcounted
832 * (which can be slower and simply not an option for some PFNMAP users). The
833 * advantage is that we don't have to follow the strict linearity rule of
834 * PFNMAP mappings in order to support COWable mappings.
837 #ifdef __HAVE_ARCH_PTE_SPECIAL
838 # define HAVE_PTE_SPECIAL 1
840 # define HAVE_PTE_SPECIAL 0
842 struct page *_vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
843 pte_t pte, bool with_public_device)
845 unsigned long pfn = pte_pfn(pte);
847 if (HAVE_PTE_SPECIAL) {
848 if (likely(!pte_special(pte)))
850 if (vma->vm_ops && vma->vm_ops->find_special_page)
851 return vma->vm_ops->find_special_page(vma, addr);
852 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
854 if (is_zero_pfn(pfn))
858 * Device public pages are special pages (they are ZONE_DEVICE
859 * pages but different from persistent memory). They behave
860 * allmost like normal pages. The difference is that they are
861 * not on the lru and thus should never be involve with any-
862 * thing that involve lru manipulation (mlock, numa balancing,
865 * This is why we still want to return NULL for such page from
866 * vm_normal_page() so that we do not have to special case all
867 * call site of vm_normal_page().
869 if (likely(pfn <= highest_memmap_pfn)) {
870 struct page *page = pfn_to_page(pfn);
872 if (is_device_public_page(page)) {
873 if (with_public_device)
878 print_bad_pte(vma, addr, pte, NULL);
882 /* !HAVE_PTE_SPECIAL case follows: */
884 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
885 if (vma->vm_flags & VM_MIXEDMAP) {
891 off = (addr - vma->vm_start) >> PAGE_SHIFT;
892 if (pfn == vma->vm_pgoff + off)
894 if (!is_cow_mapping(vma->vm_flags))
899 if (is_zero_pfn(pfn))
902 if (unlikely(pfn > highest_memmap_pfn)) {
903 print_bad_pte(vma, addr, pte, NULL);
908 * NOTE! We still have PageReserved() pages in the page tables.
909 * eg. VDSO mappings can cause them to exist.
912 return pfn_to_page(pfn);
915 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
916 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
919 unsigned long pfn = pmd_pfn(pmd);
922 * There is no pmd_special() but there may be special pmds, e.g.
923 * in a direct-access (dax) mapping, so let's just replicate the
924 * !HAVE_PTE_SPECIAL case from vm_normal_page() here.
926 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
927 if (vma->vm_flags & VM_MIXEDMAP) {
933 off = (addr - vma->vm_start) >> PAGE_SHIFT;
934 if (pfn == vma->vm_pgoff + off)
936 if (!is_cow_mapping(vma->vm_flags))
941 if (is_zero_pfn(pfn))
943 if (unlikely(pfn > highest_memmap_pfn))
947 * NOTE! We still have PageReserved() pages in the page tables.
948 * eg. VDSO mappings can cause them to exist.
951 return pfn_to_page(pfn);
956 * copy one vm_area from one task to the other. Assumes the page tables
957 * already present in the new task to be cleared in the whole range
958 * covered by this vma.
961 static inline unsigned long
962 copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
963 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
964 unsigned long addr, int *rss)
966 unsigned long vm_flags = vma->vm_flags;
967 pte_t pte = *src_pte;
970 /* pte contains position in swap or file, so copy. */
971 if (unlikely(!pte_present(pte))) {
972 swp_entry_t entry = pte_to_swp_entry(pte);
974 if (likely(!non_swap_entry(entry))) {
975 if (swap_duplicate(entry) < 0)
978 /* make sure dst_mm is on swapoff's mmlist. */
979 if (unlikely(list_empty(&dst_mm->mmlist))) {
980 spin_lock(&mmlist_lock);
981 if (list_empty(&dst_mm->mmlist))
982 list_add(&dst_mm->mmlist,
984 spin_unlock(&mmlist_lock);
987 } else if (is_migration_entry(entry)) {
988 page = migration_entry_to_page(entry);
990 rss[mm_counter(page)]++;
992 if (is_write_migration_entry(entry) &&
993 is_cow_mapping(vm_flags)) {
995 * COW mappings require pages in both
996 * parent and child to be set to read.
998 make_migration_entry_read(&entry);
999 pte = swp_entry_to_pte(entry);
1000 if (pte_swp_soft_dirty(*src_pte))
1001 pte = pte_swp_mksoft_dirty(pte);
1002 set_pte_at(src_mm, addr, src_pte, pte);
1004 } else if (is_device_private_entry(entry)) {
1005 page = device_private_entry_to_page(entry);
1008 * Update rss count even for unaddressable pages, as
1009 * they should treated just like normal pages in this
1012 * We will likely want to have some new rss counters
1013 * for unaddressable pages, at some point. But for now
1014 * keep things as they are.
1017 rss[mm_counter(page)]++;
1018 page_dup_rmap(page, false);
1021 * We do not preserve soft-dirty information, because so
1022 * far, checkpoint/restore is the only feature that
1023 * requires that. And checkpoint/restore does not work
1024 * when a device driver is involved (you cannot easily
1025 * save and restore device driver state).
1027 if (is_write_device_private_entry(entry) &&
1028 is_cow_mapping(vm_flags)) {
1029 make_device_private_entry_read(&entry);
1030 pte = swp_entry_to_pte(entry);
1031 set_pte_at(src_mm, addr, src_pte, pte);
1038 * If it's a COW mapping, write protect it both
1039 * in the parent and the child
1041 if (is_cow_mapping(vm_flags)) {
1042 ptep_set_wrprotect(src_mm, addr, src_pte);
1043 pte = pte_wrprotect(pte);
1047 * If it's a shared mapping, mark it clean in
1050 if (vm_flags & VM_SHARED)
1051 pte = pte_mkclean(pte);
1052 pte = pte_mkold(pte);
1054 page = vm_normal_page(vma, addr, pte);
1057 page_dup_rmap(page, false);
1058 rss[mm_counter(page)]++;
1059 } else if (pte_devmap(pte)) {
1060 page = pte_page(pte);
1063 * Cache coherent device memory behave like regular page and
1064 * not like persistent memory page. For more informations see
1065 * MEMORY_DEVICE_CACHE_COHERENT in memory_hotplug.h
1067 if (is_device_public_page(page)) {
1069 page_dup_rmap(page, false);
1070 rss[mm_counter(page)]++;
1075 set_pte_at(dst_mm, addr, dst_pte, pte);
1079 static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1080 pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
1081 unsigned long addr, unsigned long end)
1083 pte_t *orig_src_pte, *orig_dst_pte;
1084 pte_t *src_pte, *dst_pte;
1085 spinlock_t *src_ptl, *dst_ptl;
1087 int rss[NR_MM_COUNTERS];
1088 swp_entry_t entry = (swp_entry_t){0};
1093 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
1096 src_pte = pte_offset_map(src_pmd, addr);
1097 src_ptl = pte_lockptr(src_mm, src_pmd);
1098 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1099 orig_src_pte = src_pte;
1100 orig_dst_pte = dst_pte;
1101 arch_enter_lazy_mmu_mode();
1105 * We are holding two locks at this point - either of them
1106 * could generate latencies in another task on another CPU.
1108 if (progress >= 32) {
1110 if (need_resched() ||
1111 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
1114 if (pte_none(*src_pte)) {
1118 entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
1123 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
1125 arch_leave_lazy_mmu_mode();
1126 spin_unlock(src_ptl);
1127 pte_unmap(orig_src_pte);
1128 add_mm_rss_vec(dst_mm, rss);
1129 pte_unmap_unlock(orig_dst_pte, dst_ptl);
1133 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
1142 static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1143 pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
1144 unsigned long addr, unsigned long end)
1146 pmd_t *src_pmd, *dst_pmd;
1149 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1152 src_pmd = pmd_offset(src_pud, addr);
1154 next = pmd_addr_end(addr, end);
1155 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1156 || pmd_devmap(*src_pmd)) {
1158 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, vma);
1159 err = copy_huge_pmd(dst_mm, src_mm,
1160 dst_pmd, src_pmd, addr, vma);
1167 if (pmd_none_or_clear_bad(src_pmd))
1169 if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
1172 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1176 static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1177 p4d_t *dst_p4d, p4d_t *src_p4d, struct vm_area_struct *vma,
1178 unsigned long addr, unsigned long end)
1180 pud_t *src_pud, *dst_pud;
1183 dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1186 src_pud = pud_offset(src_p4d, addr);
1188 next = pud_addr_end(addr, end);
1189 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1192 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, vma);
1193 err = copy_huge_pud(dst_mm, src_mm,
1194 dst_pud, src_pud, addr, vma);
1201 if (pud_none_or_clear_bad(src_pud))
1203 if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
1206 } while (dst_pud++, src_pud++, addr = next, addr != end);
1210 static inline int copy_p4d_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1211 pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
1212 unsigned long addr, unsigned long end)
1214 p4d_t *src_p4d, *dst_p4d;
1217 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1220 src_p4d = p4d_offset(src_pgd, addr);
1222 next = p4d_addr_end(addr, end);
1223 if (p4d_none_or_clear_bad(src_p4d))
1225 if (copy_pud_range(dst_mm, src_mm, dst_p4d, src_p4d,
1228 } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1232 int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1233 struct vm_area_struct *vma)
1235 pgd_t *src_pgd, *dst_pgd;
1237 unsigned long addr = vma->vm_start;
1238 unsigned long end = vma->vm_end;
1239 unsigned long mmun_start; /* For mmu_notifiers */
1240 unsigned long mmun_end; /* For mmu_notifiers */
1245 * Don't copy ptes where a page fault will fill them correctly.
1246 * Fork becomes much lighter when there are big shared or private
1247 * readonly mappings. The tradeoff is that copy_page_range is more
1248 * efficient than faulting.
1250 if (!(vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1254 if (is_vm_hugetlb_page(vma))
1255 return copy_hugetlb_page_range(dst_mm, src_mm, vma);
1257 if (unlikely(vma->vm_flags & VM_PFNMAP)) {
1259 * We do not free on error cases below as remove_vma
1260 * gets called on error from higher level routine
1262 ret = track_pfn_copy(vma);
1268 * We need to invalidate the secondary MMU mappings only when
1269 * there could be a permission downgrade on the ptes of the
1270 * parent mm. And a permission downgrade will only happen if
1271 * is_cow_mapping() returns true.
1273 is_cow = is_cow_mapping(vma->vm_flags);
1277 mmu_notifier_invalidate_range_start(src_mm, mmun_start,
1281 dst_pgd = pgd_offset(dst_mm, addr);
1282 src_pgd = pgd_offset(src_mm, addr);
1284 next = pgd_addr_end(addr, end);
1285 if (pgd_none_or_clear_bad(src_pgd))
1287 if (unlikely(copy_p4d_range(dst_mm, src_mm, dst_pgd, src_pgd,
1288 vma, addr, next))) {
1292 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1295 mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end);
1299 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1300 struct vm_area_struct *vma, pmd_t *pmd,
1301 unsigned long addr, unsigned long end,
1302 struct zap_details *details)
1304 struct mm_struct *mm = tlb->mm;
1305 int force_flush = 0;
1306 int rss[NR_MM_COUNTERS];
1312 tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
1315 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1317 flush_tlb_batched_pending(mm);
1318 arch_enter_lazy_mmu_mode();
1321 if (pte_none(ptent))
1324 if (pte_present(ptent)) {
1327 page = _vm_normal_page(vma, addr, ptent, true);
1328 if (unlikely(details) && page) {
1330 * unmap_shared_mapping_pages() wants to
1331 * invalidate cache without truncating:
1332 * unmap shared but keep private pages.
1334 if (details->check_mapping &&
1335 details->check_mapping != page_rmapping(page))
1338 ptent = ptep_get_and_clear_full(mm, addr, pte,
1340 tlb_remove_tlb_entry(tlb, pte, addr);
1341 if (unlikely(!page))
1344 if (!PageAnon(page)) {
1345 if (pte_dirty(ptent)) {
1347 set_page_dirty(page);
1349 if (pte_young(ptent) &&
1350 likely(!(vma->vm_flags & VM_SEQ_READ)))
1351 mark_page_accessed(page);
1353 rss[mm_counter(page)]--;
1354 page_remove_rmap(page, false);
1355 if (unlikely(page_mapcount(page) < 0))
1356 print_bad_pte(vma, addr, ptent, page);
1357 if (unlikely(__tlb_remove_page(tlb, page))) {
1365 entry = pte_to_swp_entry(ptent);
1366 if (non_swap_entry(entry) && is_device_private_entry(entry)) {
1367 struct page *page = device_private_entry_to_page(entry);
1369 if (unlikely(details && details->check_mapping)) {
1371 * unmap_shared_mapping_pages() wants to
1372 * invalidate cache without truncating:
1373 * unmap shared but keep private pages.
1375 if (details->check_mapping !=
1376 page_rmapping(page))
1380 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1381 rss[mm_counter(page)]--;
1382 page_remove_rmap(page, false);
1387 /* If details->check_mapping, we leave swap entries. */
1388 if (unlikely(details))
1391 entry = pte_to_swp_entry(ptent);
1392 if (!non_swap_entry(entry))
1394 else if (is_migration_entry(entry)) {
1397 page = migration_entry_to_page(entry);
1398 rss[mm_counter(page)]--;
1400 if (unlikely(!free_swap_and_cache(entry)))
1401 print_bad_pte(vma, addr, ptent, NULL);
1402 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1403 } while (pte++, addr += PAGE_SIZE, addr != end);
1405 add_mm_rss_vec(mm, rss);
1406 arch_leave_lazy_mmu_mode();
1408 /* Do the actual TLB flush before dropping ptl */
1410 tlb_flush_mmu_tlbonly(tlb);
1411 pte_unmap_unlock(start_pte, ptl);
1414 * If we forced a TLB flush (either due to running out of
1415 * batch buffers or because we needed to flush dirty TLB
1416 * entries before releasing the ptl), free the batched
1417 * memory too. Restart if we didn't do everything.
1421 tlb_flush_mmu_free(tlb);
1429 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1430 struct vm_area_struct *vma, pud_t *pud,
1431 unsigned long addr, unsigned long end,
1432 struct zap_details *details)
1437 pmd = pmd_offset(pud, addr);
1439 next = pmd_addr_end(addr, end);
1440 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1441 if (next - addr != HPAGE_PMD_SIZE)
1442 __split_huge_pmd(vma, pmd, addr, false, NULL);
1443 else if (zap_huge_pmd(tlb, vma, pmd, addr))
1448 * Here there can be other concurrent MADV_DONTNEED or
1449 * trans huge page faults running, and if the pmd is
1450 * none or trans huge it can change under us. This is
1451 * because MADV_DONTNEED holds the mmap_sem in read
1454 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1456 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1459 } while (pmd++, addr = next, addr != end);
1464 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1465 struct vm_area_struct *vma, p4d_t *p4d,
1466 unsigned long addr, unsigned long end,
1467 struct zap_details *details)
1472 pud = pud_offset(p4d, addr);
1474 next = pud_addr_end(addr, end);
1475 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1476 if (next - addr != HPAGE_PUD_SIZE) {
1477 VM_BUG_ON_VMA(!rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1478 split_huge_pud(vma, pud, addr);
1479 } else if (zap_huge_pud(tlb, vma, pud, addr))
1483 if (pud_none_or_clear_bad(pud))
1485 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1488 } while (pud++, addr = next, addr != end);
1493 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1494 struct vm_area_struct *vma, pgd_t *pgd,
1495 unsigned long addr, unsigned long end,
1496 struct zap_details *details)
1501 p4d = p4d_offset(pgd, addr);
1503 next = p4d_addr_end(addr, end);
1504 if (p4d_none_or_clear_bad(p4d))
1506 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1507 } while (p4d++, addr = next, addr != end);
1512 void unmap_page_range(struct mmu_gather *tlb,
1513 struct vm_area_struct *vma,
1514 unsigned long addr, unsigned long end,
1515 struct zap_details *details)
1520 BUG_ON(addr >= end);
1521 tlb_start_vma(tlb, vma);
1522 pgd = pgd_offset(vma->vm_mm, addr);
1524 next = pgd_addr_end(addr, end);
1525 if (pgd_none_or_clear_bad(pgd))
1527 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1528 } while (pgd++, addr = next, addr != end);
1529 tlb_end_vma(tlb, vma);
1533 static void unmap_single_vma(struct mmu_gather *tlb,
1534 struct vm_area_struct *vma, unsigned long start_addr,
1535 unsigned long end_addr,
1536 struct zap_details *details)
1538 unsigned long start = max(vma->vm_start, start_addr);
1541 if (start >= vma->vm_end)
1543 end = min(vma->vm_end, end_addr);
1544 if (end <= vma->vm_start)
1548 uprobe_munmap(vma, start, end);
1550 if (unlikely(vma->vm_flags & VM_PFNMAP))
1551 untrack_pfn(vma, 0, 0);
1554 if (unlikely(is_vm_hugetlb_page(vma))) {
1556 * It is undesirable to test vma->vm_file as it
1557 * should be non-null for valid hugetlb area.
1558 * However, vm_file will be NULL in the error
1559 * cleanup path of mmap_region. When
1560 * hugetlbfs ->mmap method fails,
1561 * mmap_region() nullifies vma->vm_file
1562 * before calling this function to clean up.
1563 * Since no pte has actually been setup, it is
1564 * safe to do nothing in this case.
1567 i_mmap_lock_write(vma->vm_file->f_mapping);
1568 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1569 i_mmap_unlock_write(vma->vm_file->f_mapping);
1572 unmap_page_range(tlb, vma, start, end, details);
1577 * unmap_vmas - unmap a range of memory covered by a list of vma's
1578 * @tlb: address of the caller's struct mmu_gather
1579 * @vma: the starting vma
1580 * @start_addr: virtual address at which to start unmapping
1581 * @end_addr: virtual address at which to end unmapping
1583 * Unmap all pages in the vma list.
1585 * Only addresses between `start' and `end' will be unmapped.
1587 * The VMA list must be sorted in ascending virtual address order.
1589 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1590 * range after unmap_vmas() returns. So the only responsibility here is to
1591 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1592 * drops the lock and schedules.
1594 void unmap_vmas(struct mmu_gather *tlb,
1595 struct vm_area_struct *vma, unsigned long start_addr,
1596 unsigned long end_addr)
1598 struct mm_struct *mm = vma->vm_mm;
1600 mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1601 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1602 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1603 mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
1607 * zap_page_range - remove user pages in a given range
1608 * @vma: vm_area_struct holding the applicable pages
1609 * @start: starting address of pages to zap
1610 * @size: number of bytes to zap
1612 * Caller must protect the VMA list
1614 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1617 struct mm_struct *mm = vma->vm_mm;
1618 struct mmu_gather tlb;
1619 unsigned long end = start + size;
1622 tlb_gather_mmu(&tlb, mm, start, end);
1623 update_hiwater_rss(mm);
1624 mmu_notifier_invalidate_range_start(mm, start, end);
1625 for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
1626 unmap_single_vma(&tlb, vma, start, end, NULL);
1629 * zap_page_range does not specify whether mmap_sem should be
1630 * held for read or write. That allows parallel zap_page_range
1631 * operations to unmap a PTE and defer a flush meaning that
1632 * this call observes pte_none and fails to flush the TLB.
1633 * Rather than adding a complex API, ensure that no stale
1634 * TLB entries exist when this call returns.
1636 flush_tlb_range(vma, start, end);
1639 mmu_notifier_invalidate_range_end(mm, start, end);
1640 tlb_finish_mmu(&tlb, start, end);
1644 * zap_page_range_single - remove user pages in a given range
1645 * @vma: vm_area_struct holding the applicable pages
1646 * @address: starting address of pages to zap
1647 * @size: number of bytes to zap
1648 * @details: details of shared cache invalidation
1650 * The range must fit into one VMA.
1652 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1653 unsigned long size, struct zap_details *details)
1655 struct mm_struct *mm = vma->vm_mm;
1656 struct mmu_gather tlb;
1657 unsigned long end = address + size;
1660 tlb_gather_mmu(&tlb, mm, address, end);
1661 update_hiwater_rss(mm);
1662 mmu_notifier_invalidate_range_start(mm, address, end);
1663 unmap_single_vma(&tlb, vma, address, end, details);
1664 mmu_notifier_invalidate_range_end(mm, address, end);
1665 tlb_finish_mmu(&tlb, address, end);
1669 * zap_vma_ptes - remove ptes mapping the vma
1670 * @vma: vm_area_struct holding ptes to be zapped
1671 * @address: starting address of pages to zap
1672 * @size: number of bytes to zap
1674 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1676 * The entire address range must be fully contained within the vma.
1678 * Returns 0 if successful.
1680 int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1683 if (address < vma->vm_start || address + size > vma->vm_end ||
1684 !(vma->vm_flags & VM_PFNMAP))
1686 zap_page_range_single(vma, address, size, NULL);
1689 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1691 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1699 pgd = pgd_offset(mm, addr);
1700 p4d = p4d_alloc(mm, pgd, addr);
1703 pud = pud_alloc(mm, p4d, addr);
1706 pmd = pmd_alloc(mm, pud, addr);
1710 VM_BUG_ON(pmd_trans_huge(*pmd));
1711 return pte_alloc_map_lock(mm, pmd, addr, ptl);
1715 * This is the old fallback for page remapping.
1717 * For historical reasons, it only allows reserved pages. Only
1718 * old drivers should use this, and they needed to mark their
1719 * pages reserved for the old functions anyway.
1721 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1722 struct page *page, pgprot_t prot)
1724 struct mm_struct *mm = vma->vm_mm;
1733 flush_dcache_page(page);
1734 pte = get_locked_pte(mm, addr, &ptl);
1738 if (!pte_none(*pte))
1741 /* Ok, finally just insert the thing.. */
1743 inc_mm_counter_fast(mm, mm_counter_file(page));
1744 page_add_file_rmap(page, false);
1745 set_pte_at(mm, addr, pte, mk_pte(page, prot));
1748 pte_unmap_unlock(pte, ptl);
1751 pte_unmap_unlock(pte, ptl);
1757 * vm_insert_page - insert single page into user vma
1758 * @vma: user vma to map to
1759 * @addr: target user address of this page
1760 * @page: source kernel page
1762 * This allows drivers to insert individual pages they've allocated
1765 * The page has to be a nice clean _individual_ kernel allocation.
1766 * If you allocate a compound page, you need to have marked it as
1767 * such (__GFP_COMP), or manually just split the page up yourself
1768 * (see split_page()).
1770 * NOTE! Traditionally this was done with "remap_pfn_range()" which
1771 * took an arbitrary page protection parameter. This doesn't allow
1772 * that. Your vma protection will have to be set up correctly, which
1773 * means that if you want a shared writable mapping, you'd better
1774 * ask for a shared writable mapping!
1776 * The page does not need to be reserved.
1778 * Usually this function is called from f_op->mmap() handler
1779 * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
1780 * Caller must set VM_MIXEDMAP on vma if it wants to call this
1781 * function from other places, for example from page-fault handler.
1783 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1786 if (addr < vma->vm_start || addr >= vma->vm_end)
1788 if (!page_count(page))
1790 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1791 BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
1792 BUG_ON(vma->vm_flags & VM_PFNMAP);
1793 vma->vm_flags |= VM_MIXEDMAP;
1795 return insert_page(vma, addr, page, vma->vm_page_prot);
1797 EXPORT_SYMBOL(vm_insert_page);
1799 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1800 pfn_t pfn, pgprot_t prot, bool mkwrite)
1802 struct mm_struct *mm = vma->vm_mm;
1808 pte = get_locked_pte(mm, addr, &ptl);
1812 if (!pte_none(*pte)) {
1815 * For read faults on private mappings the PFN passed
1816 * in may not match the PFN we have mapped if the
1817 * mapped PFN is a writeable COW page. In the mkwrite
1818 * case we are creating a writable PTE for a shared
1819 * mapping and we expect the PFNs to match. If they
1820 * don't match, we are likely racing with block
1821 * allocation and mapping invalidation so just skip the
1824 if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
1825 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
1828 entry = pte_mkyoung(*pte);
1829 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1830 if (ptep_set_access_flags(vma, addr, pte, entry, 1))
1831 update_mmu_cache(vma, addr, pte);
1836 /* Ok, finally just insert the thing.. */
1837 if (pfn_t_devmap(pfn))
1838 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
1840 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1843 entry = pte_mkyoung(entry);
1844 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1847 set_pte_at(mm, addr, pte, entry);
1848 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1852 pte_unmap_unlock(pte, ptl);
1858 * vm_insert_pfn - insert single pfn into user vma
1859 * @vma: user vma to map to
1860 * @addr: target user address of this page
1861 * @pfn: source kernel pfn
1863 * Similar to vm_insert_page, this allows drivers to insert individual pages
1864 * they've allocated into a user vma. Same comments apply.
1866 * This function should only be called from a vm_ops->fault handler, and
1867 * in that case the handler should return NULL.
1869 * vma cannot be a COW mapping.
1871 * As this is called only for pages that do not currently exist, we
1872 * do not need to flush old virtual caches or the TLB.
1874 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1877 return vm_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
1879 EXPORT_SYMBOL(vm_insert_pfn);
1882 * vm_insert_pfn_prot - insert single pfn into user vma with specified pgprot
1883 * @vma: user vma to map to
1884 * @addr: target user address of this page
1885 * @pfn: source kernel pfn
1886 * @pgprot: pgprot flags for the inserted page
1888 * This is exactly like vm_insert_pfn, except that it allows drivers to
1889 * to override pgprot on a per-page basis.
1891 * This only makes sense for IO mappings, and it makes no sense for
1892 * cow mappings. In general, using multiple vmas is preferable;
1893 * vm_insert_pfn_prot should only be used if using multiple VMAs is
1896 int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
1897 unsigned long pfn, pgprot_t pgprot)
1901 * Technically, architectures with pte_special can avoid all these
1902 * restrictions (same for remap_pfn_range). However we would like
1903 * consistency in testing and feature parity among all, so we should
1904 * try to keep these invariants in place for everybody.
1906 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1907 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1908 (VM_PFNMAP|VM_MIXEDMAP));
1909 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1910 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1912 if (addr < vma->vm_start || addr >= vma->vm_end)
1915 if (!pfn_modify_allowed(pfn, pgprot))
1918 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
1920 ret = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
1925 EXPORT_SYMBOL(vm_insert_pfn_prot);
1927 static int __vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1928 pfn_t pfn, bool mkwrite)
1930 pgprot_t pgprot = vma->vm_page_prot;
1932 BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
1934 if (addr < vma->vm_start || addr >= vma->vm_end)
1937 track_pfn_insert(vma, &pgprot, pfn);
1939 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
1943 * If we don't have pte special, then we have to use the pfn_valid()
1944 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1945 * refcount the page if pfn_valid is true (hence insert_page rather
1946 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
1947 * without pte special, it would there be refcounted as a normal page.
1949 if (!HAVE_PTE_SPECIAL && !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1953 * At this point we are committed to insert_page()
1954 * regardless of whether the caller specified flags that
1955 * result in pfn_t_has_page() == false.
1957 page = pfn_to_page(pfn_t_to_pfn(pfn));
1958 return insert_page(vma, addr, page, pgprot);
1960 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
1963 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1966 return __vm_insert_mixed(vma, addr, pfn, false);
1969 EXPORT_SYMBOL(vm_insert_mixed);
1971 int vm_insert_mixed_mkwrite(struct vm_area_struct *vma, unsigned long addr,
1974 return __vm_insert_mixed(vma, addr, pfn, true);
1976 EXPORT_SYMBOL(vm_insert_mixed_mkwrite);
1979 * maps a range of physical memory into the requested pages. the old
1980 * mappings are removed. any references to nonexistent pages results
1981 * in null mappings (currently treated as "copy-on-access")
1983 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
1984 unsigned long addr, unsigned long end,
1985 unsigned long pfn, pgprot_t prot)
1987 pte_t *pte, *mapped_pte;
1991 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
1994 arch_enter_lazy_mmu_mode();
1996 BUG_ON(!pte_none(*pte));
1997 if (!pfn_modify_allowed(pfn, prot)) {
2001 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2003 } while (pte++, addr += PAGE_SIZE, addr != end);
2004 arch_leave_lazy_mmu_mode();
2005 pte_unmap_unlock(mapped_pte, ptl);
2009 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2010 unsigned long addr, unsigned long end,
2011 unsigned long pfn, pgprot_t prot)
2017 pfn -= addr >> PAGE_SHIFT;
2018 pmd = pmd_alloc(mm, pud, addr);
2021 VM_BUG_ON(pmd_trans_huge(*pmd));
2023 next = pmd_addr_end(addr, end);
2024 err = remap_pte_range(mm, pmd, addr, next,
2025 pfn + (addr >> PAGE_SHIFT), prot);
2028 } while (pmd++, addr = next, addr != end);
2032 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2033 unsigned long addr, unsigned long end,
2034 unsigned long pfn, pgprot_t prot)
2040 pfn -= addr >> PAGE_SHIFT;
2041 pud = pud_alloc(mm, p4d, addr);
2045 next = pud_addr_end(addr, end);
2046 err = remap_pmd_range(mm, pud, addr, next,
2047 pfn + (addr >> PAGE_SHIFT), prot);
2050 } while (pud++, addr = next, addr != end);
2054 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2055 unsigned long addr, unsigned long end,
2056 unsigned long pfn, pgprot_t prot)
2062 pfn -= addr >> PAGE_SHIFT;
2063 p4d = p4d_alloc(mm, pgd, addr);
2067 next = p4d_addr_end(addr, end);
2068 err = remap_pud_range(mm, p4d, addr, next,
2069 pfn + (addr >> PAGE_SHIFT), prot);
2072 } while (p4d++, addr = next, addr != end);
2077 * remap_pfn_range - remap kernel memory to userspace
2078 * @vma: user vma to map to
2079 * @addr: target user address to start at
2080 * @pfn: physical address of kernel memory
2081 * @size: size of map area
2082 * @prot: page protection flags for this mapping
2084 * Note: this is only safe if the mm semaphore is held when called.
2086 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2087 unsigned long pfn, unsigned long size, pgprot_t prot)
2091 unsigned long end = addr + PAGE_ALIGN(size);
2092 struct mm_struct *mm = vma->vm_mm;
2093 unsigned long remap_pfn = pfn;
2097 * Physically remapped pages are special. Tell the
2098 * rest of the world about it:
2099 * VM_IO tells people not to look at these pages
2100 * (accesses can have side effects).
2101 * VM_PFNMAP tells the core MM that the base pages are just
2102 * raw PFN mappings, and do not have a "struct page" associated
2105 * Disable vma merging and expanding with mremap().
2107 * Omit vma from core dump, even when VM_IO turned off.
2109 * There's a horrible special case to handle copy-on-write
2110 * behaviour that some programs depend on. We mark the "original"
2111 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2112 * See vm_normal_page() for details.
2114 if (is_cow_mapping(vma->vm_flags)) {
2115 if (addr != vma->vm_start || end != vma->vm_end)
2117 vma->vm_pgoff = pfn;
2120 err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
2124 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2126 BUG_ON(addr >= end);
2127 pfn -= addr >> PAGE_SHIFT;
2128 pgd = pgd_offset(mm, addr);
2129 flush_cache_range(vma, addr, end);
2131 next = pgd_addr_end(addr, end);
2132 err = remap_p4d_range(mm, pgd, addr, next,
2133 pfn + (addr >> PAGE_SHIFT), prot);
2136 } while (pgd++, addr = next, addr != end);
2139 untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
2143 EXPORT_SYMBOL(remap_pfn_range);
2146 * vm_iomap_memory - remap memory to userspace
2147 * @vma: user vma to map to
2148 * @start: start of area
2149 * @len: size of area
2151 * This is a simplified io_remap_pfn_range() for common driver use. The
2152 * driver just needs to give us the physical memory range to be mapped,
2153 * we'll figure out the rest from the vma information.
2155 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2156 * whatever write-combining details or similar.
2158 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2160 unsigned long vm_len, pfn, pages;
2162 /* Check that the physical memory area passed in looks valid */
2163 if (start + len < start)
2166 * You *really* shouldn't map things that aren't page-aligned,
2167 * but we've historically allowed it because IO memory might
2168 * just have smaller alignment.
2170 len += start & ~PAGE_MASK;
2171 pfn = start >> PAGE_SHIFT;
2172 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2173 if (pfn + pages < pfn)
2176 /* We start the mapping 'vm_pgoff' pages into the area */
2177 if (vma->vm_pgoff > pages)
2179 pfn += vma->vm_pgoff;
2180 pages -= vma->vm_pgoff;
2182 /* Can we fit all of the mapping? */
2183 vm_len = vma->vm_end - vma->vm_start;
2184 if (vm_len >> PAGE_SHIFT > pages)
2187 /* Ok, let it rip */
2188 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2190 EXPORT_SYMBOL(vm_iomap_memory);
2192 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2193 unsigned long addr, unsigned long end,
2194 pte_fn_t fn, void *data)
2199 spinlock_t *uninitialized_var(ptl);
2201 pte = (mm == &init_mm) ?
2202 pte_alloc_kernel(pmd, addr) :
2203 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2207 BUG_ON(pmd_huge(*pmd));
2209 arch_enter_lazy_mmu_mode();
2211 token = pmd_pgtable(*pmd);
2214 err = fn(pte++, token, addr, data);
2217 } while (addr += PAGE_SIZE, addr != end);
2219 arch_leave_lazy_mmu_mode();
2222 pte_unmap_unlock(pte-1, ptl);
2226 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2227 unsigned long addr, unsigned long end,
2228 pte_fn_t fn, void *data)
2234 BUG_ON(pud_huge(*pud));
2236 pmd = pmd_alloc(mm, pud, addr);
2240 next = pmd_addr_end(addr, end);
2241 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
2244 } while (pmd++, addr = next, addr != end);
2248 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2249 unsigned long addr, unsigned long end,
2250 pte_fn_t fn, void *data)
2256 pud = pud_alloc(mm, p4d, addr);
2260 next = pud_addr_end(addr, end);
2261 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
2264 } while (pud++, addr = next, addr != end);
2268 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2269 unsigned long addr, unsigned long end,
2270 pte_fn_t fn, void *data)
2276 p4d = p4d_alloc(mm, pgd, addr);
2280 next = p4d_addr_end(addr, end);
2281 err = apply_to_pud_range(mm, p4d, addr, next, fn, data);
2284 } while (p4d++, addr = next, addr != end);
2289 * Scan a region of virtual memory, filling in page tables as necessary
2290 * and calling a provided function on each leaf page table.
2292 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2293 unsigned long size, pte_fn_t fn, void *data)
2297 unsigned long end = addr + size;
2300 if (WARN_ON(addr >= end))
2303 pgd = pgd_offset(mm, addr);
2305 next = pgd_addr_end(addr, end);
2306 err = apply_to_p4d_range(mm, pgd, addr, next, fn, data);
2309 } while (pgd++, addr = next, addr != end);
2313 EXPORT_SYMBOL_GPL(apply_to_page_range);
2316 * handle_pte_fault chooses page fault handler according to an entry which was
2317 * read non-atomically. Before making any commitment, on those architectures
2318 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2319 * parts, do_swap_page must check under lock before unmapping the pte and
2320 * proceeding (but do_wp_page is only called after already making such a check;
2321 * and do_anonymous_page can safely check later on).
2323 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2324 pte_t *page_table, pte_t orig_pte)
2327 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
2328 if (sizeof(pte_t) > sizeof(unsigned long)) {
2329 spinlock_t *ptl = pte_lockptr(mm, pmd);
2331 same = pte_same(*page_table, orig_pte);
2335 pte_unmap(page_table);
2339 static inline bool cow_user_page(struct page *dst, struct page *src,
2340 struct vm_fault *vmf)
2345 bool locked = false;
2346 struct vm_area_struct *vma = vmf->vma;
2347 struct mm_struct *mm = vma->vm_mm;
2348 unsigned long addr = vmf->address;
2350 debug_dma_assert_idle(src);
2353 copy_user_highpage(dst, src, addr, vma);
2358 * If the source page was a PFN mapping, we don't have
2359 * a "struct page" for it. We do a best-effort copy by
2360 * just copying from the original user address. If that
2361 * fails, we just zero-fill it. Live with it.
2363 kaddr = kmap_atomic(dst);
2364 uaddr = (void __user *)(addr & PAGE_MASK);
2367 * On architectures with software "accessed" bits, we would
2368 * take a double page fault, so mark it accessed here.
2370 if (arch_faults_on_old_pte() && !pte_young(vmf->orig_pte)) {
2373 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2375 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2377 * Other thread has already handled the fault
2378 * and we don't need to do anything. If it's
2379 * not the case, the fault will be triggered
2380 * again on the same address.
2386 entry = pte_mkyoung(vmf->orig_pte);
2387 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2388 update_mmu_cache(vma, addr, vmf->pte);
2392 * This really shouldn't fail, because the page is there
2393 * in the page tables. But it might just be unreadable,
2394 * in which case we just give up and fill the result with
2397 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2401 /* Re-validate under PTL if the page is still mapped */
2402 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2404 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2405 /* The PTE changed under us. Retry page fault. */
2411 * The same page can be mapped back since last copy attampt.
2412 * Try to copy again under PTL.
2414 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2416 * Give a warn in case there can be some obscure
2429 pte_unmap_unlock(vmf->pte, vmf->ptl);
2430 kunmap_atomic(kaddr);
2431 flush_dcache_page(dst);
2436 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2438 struct file *vm_file = vma->vm_file;
2441 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2444 * Special mappings (e.g. VDSO) do not have any file so fake
2445 * a default GFP_KERNEL for them.
2451 * Notify the address space that the page is about to become writable so that
2452 * it can prohibit this or wait for the page to get into an appropriate state.
2454 * We do this without the lock held, so that it can sleep if it needs to.
2456 static int do_page_mkwrite(struct vm_fault *vmf)
2459 struct page *page = vmf->page;
2460 unsigned int old_flags = vmf->flags;
2462 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2464 ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2465 /* Restore original flags so that caller is not surprised */
2466 vmf->flags = old_flags;
2467 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2469 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2471 if (!page->mapping) {
2473 return 0; /* retry */
2475 ret |= VM_FAULT_LOCKED;
2477 VM_BUG_ON_PAGE(!PageLocked(page), page);
2482 * Handle dirtying of a page in shared file mapping on a write fault.
2484 * The function expects the page to be locked and unlocks it.
2486 static void fault_dirty_shared_page(struct vm_area_struct *vma,
2489 struct address_space *mapping;
2491 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2493 dirtied = set_page_dirty(page);
2494 VM_BUG_ON_PAGE(PageAnon(page), page);
2496 * Take a local copy of the address_space - page.mapping may be zeroed
2497 * by truncate after unlock_page(). The address_space itself remains
2498 * pinned by vma->vm_file's reference. We rely on unlock_page()'s
2499 * release semantics to prevent the compiler from undoing this copying.
2501 mapping = page_rmapping(page);
2504 if ((dirtied || page_mkwrite) && mapping) {
2506 * Some device drivers do not set page.mapping
2507 * but still dirty their pages
2509 balance_dirty_pages_ratelimited(mapping);
2513 file_update_time(vma->vm_file);
2517 * Handle write page faults for pages that can be reused in the current vma
2519 * This can happen either due to the mapping being with the VM_SHARED flag,
2520 * or due to us being the last reference standing to the page. In either
2521 * case, all we need to do here is to mark the page as writable and update
2522 * any related book-keeping.
2524 static inline void wp_page_reuse(struct vm_fault *vmf)
2525 __releases(vmf->ptl)
2527 struct vm_area_struct *vma = vmf->vma;
2528 struct page *page = vmf->page;
2531 * Clear the pages cpupid information as the existing
2532 * information potentially belongs to a now completely
2533 * unrelated process.
2536 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2538 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2539 entry = pte_mkyoung(vmf->orig_pte);
2540 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2541 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
2542 update_mmu_cache(vma, vmf->address, vmf->pte);
2543 pte_unmap_unlock(vmf->pte, vmf->ptl);
2547 * Handle the case of a page which we actually need to copy to a new page.
2549 * Called with mmap_sem locked and the old page referenced, but
2550 * without the ptl held.
2552 * High level logic flow:
2554 * - Allocate a page, copy the content of the old page to the new one.
2555 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2556 * - Take the PTL. If the pte changed, bail out and release the allocated page
2557 * - If the pte is still the way we remember it, update the page table and all
2558 * relevant references. This includes dropping the reference the page-table
2559 * held to the old page, as well as updating the rmap.
2560 * - In any case, unlock the PTL and drop the reference we took to the old page.
2562 static int wp_page_copy(struct vm_fault *vmf)
2564 struct vm_area_struct *vma = vmf->vma;
2565 struct mm_struct *mm = vma->vm_mm;
2566 struct page *old_page = vmf->page;
2567 struct page *new_page = NULL;
2569 int page_copied = 0;
2570 const unsigned long mmun_start = vmf->address & PAGE_MASK;
2571 const unsigned long mmun_end = mmun_start + PAGE_SIZE;
2572 struct mem_cgroup *memcg;
2574 if (unlikely(anon_vma_prepare(vma)))
2577 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
2578 new_page = alloc_zeroed_user_highpage_movable(vma,
2583 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2588 if (!cow_user_page(new_page, old_page, vmf)) {
2590 * COW failed, if the fault was solved by other,
2591 * it's fine. If not, userspace would re-fault on
2592 * the same address and we will handle the fault
2593 * from the second attempt.
2602 if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg, false))
2605 __SetPageUptodate(new_page);
2607 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2610 * Re-check the pte - we dropped the lock
2612 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
2613 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2615 if (!PageAnon(old_page)) {
2616 dec_mm_counter_fast(mm,
2617 mm_counter_file(old_page));
2618 inc_mm_counter_fast(mm, MM_ANONPAGES);
2621 inc_mm_counter_fast(mm, MM_ANONPAGES);
2623 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2624 entry = mk_pte(new_page, vma->vm_page_prot);
2625 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2627 * Clear the pte entry and flush it first, before updating the
2628 * pte with the new entry. This will avoid a race condition
2629 * seen in the presence of one thread doing SMC and another
2632 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
2633 page_add_new_anon_rmap(new_page, vma, vmf->address, false);
2634 mem_cgroup_commit_charge(new_page, memcg, false, false);
2635 lru_cache_add_active_or_unevictable(new_page, vma);
2637 * We call the notify macro here because, when using secondary
2638 * mmu page tables (such as kvm shadow page tables), we want the
2639 * new page to be mapped directly into the secondary page table.
2641 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
2642 update_mmu_cache(vma, vmf->address, vmf->pte);
2645 * Only after switching the pte to the new page may
2646 * we remove the mapcount here. Otherwise another
2647 * process may come and find the rmap count decremented
2648 * before the pte is switched to the new page, and
2649 * "reuse" the old page writing into it while our pte
2650 * here still points into it and can be read by other
2653 * The critical issue is to order this
2654 * page_remove_rmap with the ptp_clear_flush above.
2655 * Those stores are ordered by (if nothing else,)
2656 * the barrier present in the atomic_add_negative
2657 * in page_remove_rmap.
2659 * Then the TLB flush in ptep_clear_flush ensures that
2660 * no process can access the old page before the
2661 * decremented mapcount is visible. And the old page
2662 * cannot be reused until after the decremented
2663 * mapcount is visible. So transitively, TLBs to
2664 * old page will be flushed before it can be reused.
2666 page_remove_rmap(old_page, false);
2669 /* Free the old page.. */
2670 new_page = old_page;
2673 mem_cgroup_cancel_charge(new_page, memcg, false);
2679 pte_unmap_unlock(vmf->pte, vmf->ptl);
2680 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2683 * Don't let another task, with possibly unlocked vma,
2684 * keep the mlocked page.
2686 if (page_copied && (vma->vm_flags & VM_LOCKED)) {
2687 lock_page(old_page); /* LRU manipulation */
2688 if (PageMlocked(old_page))
2689 munlock_vma_page(old_page);
2690 unlock_page(old_page);
2694 return page_copied ? VM_FAULT_WRITE : 0;
2700 return VM_FAULT_OOM;
2704 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
2705 * writeable once the page is prepared
2707 * @vmf: structure describing the fault
2709 * This function handles all that is needed to finish a write page fault in a
2710 * shared mapping due to PTE being read-only once the mapped page is prepared.
2711 * It handles locking of PTE and modifying it. The function returns
2712 * VM_FAULT_WRITE on success, 0 when PTE got changed before we acquired PTE
2715 * The function expects the page to be locked or other protection against
2716 * concurrent faults / writeback (such as DAX radix tree locks).
2718 int finish_mkwrite_fault(struct vm_fault *vmf)
2720 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
2721 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
2724 * We might have raced with another page fault while we released the
2725 * pte_offset_map_lock.
2727 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2728 pte_unmap_unlock(vmf->pte, vmf->ptl);
2729 return VM_FAULT_NOPAGE;
2736 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2739 static int wp_pfn_shared(struct vm_fault *vmf)
2741 struct vm_area_struct *vma = vmf->vma;
2743 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2746 pte_unmap_unlock(vmf->pte, vmf->ptl);
2747 vmf->flags |= FAULT_FLAG_MKWRITE;
2748 ret = vma->vm_ops->pfn_mkwrite(vmf);
2749 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
2751 return finish_mkwrite_fault(vmf);
2754 return VM_FAULT_WRITE;
2757 static int wp_page_shared(struct vm_fault *vmf)
2758 __releases(vmf->ptl)
2760 struct vm_area_struct *vma = vmf->vma;
2762 get_page(vmf->page);
2764 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2767 pte_unmap_unlock(vmf->pte, vmf->ptl);
2768 tmp = do_page_mkwrite(vmf);
2769 if (unlikely(!tmp || (tmp &
2770 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
2771 put_page(vmf->page);
2774 tmp = finish_mkwrite_fault(vmf);
2775 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2776 unlock_page(vmf->page);
2777 put_page(vmf->page);
2782 lock_page(vmf->page);
2784 fault_dirty_shared_page(vma, vmf->page);
2785 put_page(vmf->page);
2787 return VM_FAULT_WRITE;
2791 * This routine handles present pages, when users try to write
2792 * to a shared page. It is done by copying the page to a new address
2793 * and decrementing the shared-page counter for the old page.
2795 * Note that this routine assumes that the protection checks have been
2796 * done by the caller (the low-level page fault routine in most cases).
2797 * Thus we can safely just mark it writable once we've done any necessary
2800 * We also mark the page dirty at this point even though the page will
2801 * change only once the write actually happens. This avoids a few races,
2802 * and potentially makes it more efficient.
2804 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2805 * but allow concurrent faults), with pte both mapped and locked.
2806 * We return with mmap_sem still held, but pte unmapped and unlocked.
2808 static int do_wp_page(struct vm_fault *vmf)
2809 __releases(vmf->ptl)
2811 struct vm_area_struct *vma = vmf->vma;
2813 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
2816 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
2819 * We should not cow pages in a shared writeable mapping.
2820 * Just mark the pages writable and/or call ops->pfn_mkwrite.
2822 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2823 (VM_WRITE|VM_SHARED))
2824 return wp_pfn_shared(vmf);
2826 pte_unmap_unlock(vmf->pte, vmf->ptl);
2827 return wp_page_copy(vmf);
2831 * Take out anonymous pages first, anonymous shared vmas are
2832 * not dirty accountable.
2834 if (PageAnon(vmf->page) && !PageKsm(vmf->page)) {
2835 int total_map_swapcount;
2836 if (!trylock_page(vmf->page)) {
2837 get_page(vmf->page);
2838 pte_unmap_unlock(vmf->pte, vmf->ptl);
2839 lock_page(vmf->page);
2840 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
2841 vmf->address, &vmf->ptl);
2842 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2843 unlock_page(vmf->page);
2844 pte_unmap_unlock(vmf->pte, vmf->ptl);
2845 put_page(vmf->page);
2848 put_page(vmf->page);
2850 if (reuse_swap_page(vmf->page, &total_map_swapcount)) {
2851 if (total_map_swapcount == 1) {
2853 * The page is all ours. Move it to
2854 * our anon_vma so the rmap code will
2855 * not search our parent or siblings.
2856 * Protected against the rmap code by
2859 page_move_anon_rmap(vmf->page, vma);
2861 unlock_page(vmf->page);
2863 return VM_FAULT_WRITE;
2865 unlock_page(vmf->page);
2866 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2867 (VM_WRITE|VM_SHARED))) {
2868 return wp_page_shared(vmf);
2872 * Ok, we need to copy. Oh, well..
2874 get_page(vmf->page);
2876 pte_unmap_unlock(vmf->pte, vmf->ptl);
2877 return wp_page_copy(vmf);
2880 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2881 unsigned long start_addr, unsigned long end_addr,
2882 struct zap_details *details)
2884 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2887 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
2888 struct zap_details *details)
2890 struct vm_area_struct *vma;
2891 pgoff_t vba, vea, zba, zea;
2893 vma_interval_tree_foreach(vma, root,
2894 details->first_index, details->last_index) {
2896 vba = vma->vm_pgoff;
2897 vea = vba + vma_pages(vma) - 1;
2898 zba = details->first_index;
2901 zea = details->last_index;
2905 unmap_mapping_range_vma(vma,
2906 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2907 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2913 * unmap_mapping_range - unmap the portion of all mmaps in the specified
2914 * address_space corresponding to the specified page range in the underlying
2917 * @mapping: the address space containing mmaps to be unmapped.
2918 * @holebegin: byte in first page to unmap, relative to the start of
2919 * the underlying file. This will be rounded down to a PAGE_SIZE
2920 * boundary. Note that this is different from truncate_pagecache(), which
2921 * must keep the partial page. In contrast, we must get rid of
2923 * @holelen: size of prospective hole in bytes. This will be rounded
2924 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
2926 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
2927 * but 0 when invalidating pagecache, don't throw away private data.
2929 void unmap_mapping_range(struct address_space *mapping,
2930 loff_t const holebegin, loff_t const holelen, int even_cows)
2932 struct zap_details details = { };
2933 pgoff_t hba = holebegin >> PAGE_SHIFT;
2934 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2936 /* Check for overflow. */
2937 if (sizeof(holelen) > sizeof(hlen)) {
2939 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2940 if (holeend & ~(long long)ULONG_MAX)
2941 hlen = ULONG_MAX - hba + 1;
2944 details.check_mapping = even_cows ? NULL : mapping;
2945 details.first_index = hba;
2946 details.last_index = hba + hlen - 1;
2947 if (details.last_index < details.first_index)
2948 details.last_index = ULONG_MAX;
2950 i_mmap_lock_write(mapping);
2951 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
2952 unmap_mapping_range_tree(&mapping->i_mmap, &details);
2953 i_mmap_unlock_write(mapping);
2955 EXPORT_SYMBOL(unmap_mapping_range);
2958 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2959 * but allow concurrent faults), and pte mapped but not yet locked.
2960 * We return with pte unmapped and unlocked.
2962 * We return with the mmap_sem locked or unlocked in the same cases
2963 * as does filemap_fault().
2965 int do_swap_page(struct vm_fault *vmf)
2967 struct vm_area_struct *vma = vmf->vma;
2968 struct page *page = NULL, *swapcache;
2969 struct mem_cgroup *memcg;
2970 struct vma_swap_readahead swap_ra;
2976 bool vma_readahead = swap_use_vma_readahead();
2979 page = swap_readahead_detect(vmf, &swap_ra);
2980 if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte)) {
2986 entry = pte_to_swp_entry(vmf->orig_pte);
2987 if (unlikely(non_swap_entry(entry))) {
2988 if (is_migration_entry(entry)) {
2989 migration_entry_wait(vma->vm_mm, vmf->pmd,
2991 } else if (is_device_private_entry(entry)) {
2993 * For un-addressable device memory we call the pgmap
2994 * fault handler callback. The callback must migrate
2995 * the page back to some CPU accessible page.
2997 ret = device_private_entry_fault(vma, vmf->address, entry,
2998 vmf->flags, vmf->pmd);
2999 } else if (is_hwpoison_entry(entry)) {
3000 ret = VM_FAULT_HWPOISON;
3002 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3003 ret = VM_FAULT_SIGBUS;
3007 delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3009 page = lookup_swap_cache(entry, vma_readahead ? vma : NULL,
3013 page = do_swap_page_readahead(entry,
3014 GFP_HIGHUSER_MOVABLE, vmf, &swap_ra);
3016 page = swapin_readahead(entry,
3017 GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3020 * Back out if somebody else faulted in this pte
3021 * while we released the pte lock.
3023 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3024 vmf->address, &vmf->ptl);
3025 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3027 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3031 /* Had to read the page from swap area: Major fault */
3032 ret = VM_FAULT_MAJOR;
3033 count_vm_event(PGMAJFAULT);
3034 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3035 } else if (PageHWPoison(page)) {
3037 * hwpoisoned dirty swapcache pages are kept for killing
3038 * owner processes (which may be unknown at hwpoison time)
3040 ret = VM_FAULT_HWPOISON;
3041 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3047 locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3049 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3051 ret |= VM_FAULT_RETRY;
3056 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3057 * release the swapcache from under us. The page pin, and pte_same
3058 * test below, are not enough to exclude that. Even if it is still
3059 * swapcache, we need to check that the page's swap has not changed.
3061 if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
3064 page = ksm_might_need_to_copy(page, vma, vmf->address);
3065 if (unlikely(!page)) {
3071 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
3078 * Back out if somebody else already faulted in this pte.
3080 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3082 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3085 if (unlikely(!PageUptodate(page))) {
3086 ret = VM_FAULT_SIGBUS;
3091 * The page isn't present yet, go ahead with the fault.
3093 * Be careful about the sequence of operations here.
3094 * To get its accounting right, reuse_swap_page() must be called
3095 * while the page is counted on swap but not yet in mapcount i.e.
3096 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3097 * must be called after the swap_free(), or it will never succeed.
3100 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3101 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3102 pte = mk_pte(page, vma->vm_page_prot);
3103 if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3104 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3105 vmf->flags &= ~FAULT_FLAG_WRITE;
3106 ret |= VM_FAULT_WRITE;
3107 exclusive = RMAP_EXCLUSIVE;
3109 flush_icache_page(vma, page);
3110 if (pte_swp_soft_dirty(vmf->orig_pte))
3111 pte = pte_mksoft_dirty(pte);
3112 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3113 vmf->orig_pte = pte;
3114 if (page == swapcache) {
3115 do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3116 mem_cgroup_commit_charge(page, memcg, true, false);
3117 activate_page(page);
3118 } else { /* ksm created a completely new copy */
3119 page_add_new_anon_rmap(page, vma, vmf->address, false);
3120 mem_cgroup_commit_charge(page, memcg, false, false);
3121 lru_cache_add_active_or_unevictable(page, vma);
3125 if (mem_cgroup_swap_full(page) ||
3126 (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3127 try_to_free_swap(page);
3129 if (page != swapcache) {
3131 * Hold the lock to avoid the swap entry to be reused
3132 * until we take the PT lock for the pte_same() check
3133 * (to avoid false positives from pte_same). For
3134 * further safety release the lock after the swap_free
3135 * so that the swap count won't change under a
3136 * parallel locked swapcache.
3138 unlock_page(swapcache);
3139 put_page(swapcache);
3142 if (vmf->flags & FAULT_FLAG_WRITE) {
3143 ret |= do_wp_page(vmf);
3144 if (ret & VM_FAULT_ERROR)
3145 ret &= VM_FAULT_ERROR;
3149 /* No need to invalidate - it was non-present before */
3150 update_mmu_cache(vma, vmf->address, vmf->pte);
3152 pte_unmap_unlock(vmf->pte, vmf->ptl);
3156 mem_cgroup_cancel_charge(page, memcg, false);
3157 pte_unmap_unlock(vmf->pte, vmf->ptl);
3162 if (page != swapcache) {
3163 unlock_page(swapcache);
3164 put_page(swapcache);
3170 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3171 * but allow concurrent faults), and pte mapped but not yet locked.
3172 * We return with mmap_sem still held, but pte unmapped and unlocked.
3174 static int do_anonymous_page(struct vm_fault *vmf)
3176 struct vm_area_struct *vma = vmf->vma;
3177 struct mem_cgroup *memcg;
3182 /* File mapping without ->vm_ops ? */
3183 if (vma->vm_flags & VM_SHARED)
3184 return VM_FAULT_SIGBUS;
3187 * Use pte_alloc() instead of pte_alloc_map(). We can't run
3188 * pte_offset_map() on pmds where a huge pmd might be created
3189 * from a different thread.
3191 * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
3192 * parallel threads are excluded by other means.
3194 * Here we only have down_read(mmap_sem).
3196 if (pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))
3197 return VM_FAULT_OOM;
3199 /* See the comment in pte_alloc_one_map() */
3200 if (unlikely(pmd_trans_unstable(vmf->pmd)))
3203 /* Use the zero-page for reads */
3204 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3205 !mm_forbids_zeropage(vma->vm_mm)) {
3206 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3207 vma->vm_page_prot));
3208 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3209 vmf->address, &vmf->ptl);
3210 if (!pte_none(*vmf->pte))
3212 ret = check_stable_address_space(vma->vm_mm);
3215 /* Deliver the page fault to userland, check inside PT lock */
3216 if (userfaultfd_missing(vma)) {
3217 pte_unmap_unlock(vmf->pte, vmf->ptl);
3218 return handle_userfault(vmf, VM_UFFD_MISSING);
3223 /* Allocate our own private page. */
3224 if (unlikely(anon_vma_prepare(vma)))
3226 page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3230 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
3234 * The memory barrier inside __SetPageUptodate makes sure that
3235 * preceeding stores to the page contents become visible before
3236 * the set_pte_at() write.
3238 __SetPageUptodate(page);
3240 entry = mk_pte(page, vma->vm_page_prot);
3241 if (vma->vm_flags & VM_WRITE)
3242 entry = pte_mkwrite(pte_mkdirty(entry));
3244 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3246 if (!pte_none(*vmf->pte))
3249 ret = check_stable_address_space(vma->vm_mm);
3253 /* Deliver the page fault to userland, check inside PT lock */
3254 if (userfaultfd_missing(vma)) {
3255 pte_unmap_unlock(vmf->pte, vmf->ptl);
3256 mem_cgroup_cancel_charge(page, memcg, false);
3258 return handle_userfault(vmf, VM_UFFD_MISSING);
3261 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3262 page_add_new_anon_rmap(page, vma, vmf->address, false);
3263 mem_cgroup_commit_charge(page, memcg, false, false);
3264 lru_cache_add_active_or_unevictable(page, vma);
3266 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3268 /* No need to invalidate - it was non-present before */
3269 update_mmu_cache(vma, vmf->address, vmf->pte);
3271 pte_unmap_unlock(vmf->pte, vmf->ptl);
3274 mem_cgroup_cancel_charge(page, memcg, false);
3280 return VM_FAULT_OOM;
3284 * The mmap_sem must have been held on entry, and may have been
3285 * released depending on flags and vma->vm_ops->fault() return value.
3286 * See filemap_fault() and __lock_page_retry().
3288 static int __do_fault(struct vm_fault *vmf)
3290 struct vm_area_struct *vma = vmf->vma;
3294 * Preallocate pte before we take page_lock because this might lead to
3295 * deadlocks for memcg reclaim which waits for pages under writeback:
3297 * SetPageWriteback(A)
3303 * wait_on_page_writeback(A)
3304 * SetPageWriteback(B)
3306 * # flush A, B to clear the writeback
3308 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3309 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
3311 if (!vmf->prealloc_pte)
3312 return VM_FAULT_OOM;
3313 smp_wmb(); /* See comment in __pte_alloc() */
3316 ret = vma->vm_ops->fault(vmf);
3317 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3318 VM_FAULT_DONE_COW)))
3321 if (unlikely(PageHWPoison(vmf->page))) {
3322 if (ret & VM_FAULT_LOCKED)
3323 unlock_page(vmf->page);
3324 put_page(vmf->page);
3326 return VM_FAULT_HWPOISON;
3329 if (unlikely(!(ret & VM_FAULT_LOCKED)))
3330 lock_page(vmf->page);
3332 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3338 * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3339 * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3340 * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3341 * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3343 static int pmd_devmap_trans_unstable(pmd_t *pmd)
3345 return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3348 static int pte_alloc_one_map(struct vm_fault *vmf)
3350 struct vm_area_struct *vma = vmf->vma;
3352 if (!pmd_none(*vmf->pmd))
3354 if (vmf->prealloc_pte) {
3355 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3356 if (unlikely(!pmd_none(*vmf->pmd))) {
3357 spin_unlock(vmf->ptl);
3361 atomic_long_inc(&vma->vm_mm->nr_ptes);
3362 pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3363 spin_unlock(vmf->ptl);
3364 vmf->prealloc_pte = NULL;
3365 } else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))) {
3366 return VM_FAULT_OOM;
3370 * If a huge pmd materialized under us just retry later. Use
3371 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3372 * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3373 * under us and then back to pmd_none, as a result of MADV_DONTNEED
3374 * running immediately after a huge pmd fault in a different thread of
3375 * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3376 * All we have to ensure is that it is a regular pmd that we can walk
3377 * with pte_offset_map() and we can do that through an atomic read in
3378 * C, which is what pmd_trans_unstable() provides.
3380 if (pmd_devmap_trans_unstable(vmf->pmd))
3381 return VM_FAULT_NOPAGE;
3384 * At this point we know that our vmf->pmd points to a page of ptes
3385 * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3386 * for the duration of the fault. If a racing MADV_DONTNEED runs and
3387 * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3388 * be valid and we will re-check to make sure the vmf->pte isn't
3389 * pte_none() under vmf->ptl protection when we return to
3392 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3397 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3399 #define HPAGE_CACHE_INDEX_MASK (HPAGE_PMD_NR - 1)
3400 static inline bool transhuge_vma_suitable(struct vm_area_struct *vma,
3401 unsigned long haddr)
3403 if (((vma->vm_start >> PAGE_SHIFT) & HPAGE_CACHE_INDEX_MASK) !=
3404 (vma->vm_pgoff & HPAGE_CACHE_INDEX_MASK))
3406 if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
3411 static void deposit_prealloc_pte(struct vm_fault *vmf)
3413 struct vm_area_struct *vma = vmf->vma;
3415 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3417 * We are going to consume the prealloc table,
3418 * count that as nr_ptes.
3420 atomic_long_inc(&vma->vm_mm->nr_ptes);
3421 vmf->prealloc_pte = NULL;
3424 static int do_set_pmd(struct vm_fault *vmf, struct page *page)
3426 struct vm_area_struct *vma = vmf->vma;
3427 bool write = vmf->flags & FAULT_FLAG_WRITE;
3428 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3432 if (!transhuge_vma_suitable(vma, haddr))
3433 return VM_FAULT_FALLBACK;
3435 ret = VM_FAULT_FALLBACK;
3436 page = compound_head(page);
3439 * Archs like ppc64 need additonal space to store information
3440 * related to pte entry. Use the preallocated table for that.
3442 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3443 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm, vmf->address);
3444 if (!vmf->prealloc_pte)
3445 return VM_FAULT_OOM;
3446 smp_wmb(); /* See comment in __pte_alloc() */
3449 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3450 if (unlikely(!pmd_none(*vmf->pmd)))
3453 for (i = 0; i < HPAGE_PMD_NR; i++)
3454 flush_icache_page(vma, page + i);
3456 entry = mk_huge_pmd(page, vma->vm_page_prot);
3458 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3460 add_mm_counter(vma->vm_mm, MM_FILEPAGES, HPAGE_PMD_NR);
3461 page_add_file_rmap(page, true);
3463 * deposit and withdraw with pmd lock held
3465 if (arch_needs_pgtable_deposit())
3466 deposit_prealloc_pte(vmf);
3468 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3470 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3472 /* fault is handled */
3474 count_vm_event(THP_FILE_MAPPED);
3476 spin_unlock(vmf->ptl);
3480 static int do_set_pmd(struct vm_fault *vmf, struct page *page)
3488 * alloc_set_pte - setup new PTE entry for given page and add reverse page
3489 * mapping. If needed, the fucntion allocates page table or use pre-allocated.
3491 * @vmf: fault environment
3492 * @memcg: memcg to charge page (only for private mappings)
3493 * @page: page to map
3495 * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
3498 * Target users are page handler itself and implementations of
3499 * vm_ops->map_pages.
3501 int alloc_set_pte(struct vm_fault *vmf, struct mem_cgroup *memcg,
3504 struct vm_area_struct *vma = vmf->vma;
3505 bool write = vmf->flags & FAULT_FLAG_WRITE;
3509 if (pmd_none(*vmf->pmd) && PageTransCompound(page) &&
3510 IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
3512 VM_BUG_ON_PAGE(memcg, page);
3514 ret = do_set_pmd(vmf, page);
3515 if (ret != VM_FAULT_FALLBACK)
3520 ret = pte_alloc_one_map(vmf);
3525 /* Re-check under ptl */
3526 if (unlikely(!pte_none(*vmf->pte)))
3527 return VM_FAULT_NOPAGE;
3529 flush_icache_page(vma, page);
3530 entry = mk_pte(page, vma->vm_page_prot);
3532 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3533 /* copy-on-write page */
3534 if (write && !(vma->vm_flags & VM_SHARED)) {
3535 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3536 page_add_new_anon_rmap(page, vma, vmf->address, false);
3537 mem_cgroup_commit_charge(page, memcg, false, false);
3538 lru_cache_add_active_or_unevictable(page, vma);
3540 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3541 page_add_file_rmap(page, false);
3543 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3545 /* no need to invalidate: a not-present page won't be cached */
3546 update_mmu_cache(vma, vmf->address, vmf->pte);
3553 * finish_fault - finish page fault once we have prepared the page to fault
3555 * @vmf: structure describing the fault
3557 * This function handles all that is needed to finish a page fault once the
3558 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
3559 * given page, adds reverse page mapping, handles memcg charges and LRU
3560 * addition. The function returns 0 on success, VM_FAULT_ code in case of
3563 * The function expects the page to be locked and on success it consumes a
3564 * reference of a page being mapped (for the PTE which maps it).
3566 int finish_fault(struct vm_fault *vmf)
3571 /* Did we COW the page? */
3572 if ((vmf->flags & FAULT_FLAG_WRITE) &&
3573 !(vmf->vma->vm_flags & VM_SHARED))
3574 page = vmf->cow_page;
3579 * check even for read faults because we might have lost our CoWed
3582 if (!(vmf->vma->vm_flags & VM_SHARED))
3583 ret = check_stable_address_space(vmf->vma->vm_mm);
3585 ret = alloc_set_pte(vmf, vmf->memcg, page);
3587 pte_unmap_unlock(vmf->pte, vmf->ptl);
3591 static unsigned long fault_around_bytes __read_mostly =
3592 rounddown_pow_of_two(65536);
3594 #ifdef CONFIG_DEBUG_FS
3595 static int fault_around_bytes_get(void *data, u64 *val)
3597 *val = fault_around_bytes;
3602 * fault_around_pages() and fault_around_mask() expects fault_around_bytes
3603 * rounded down to nearest page order. It's what do_fault_around() expects to
3606 static int fault_around_bytes_set(void *data, u64 val)
3608 if (val / PAGE_SIZE > PTRS_PER_PTE)
3610 if (val > PAGE_SIZE)
3611 fault_around_bytes = rounddown_pow_of_two(val);
3613 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
3616 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
3617 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
3619 static int __init fault_around_debugfs(void)
3623 ret = debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
3624 &fault_around_bytes_fops);
3626 pr_warn("Failed to create fault_around_bytes in debugfs");
3629 late_initcall(fault_around_debugfs);
3633 * do_fault_around() tries to map few pages around the fault address. The hope
3634 * is that the pages will be needed soon and this will lower the number of
3637 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
3638 * not ready to be mapped: not up-to-date, locked, etc.
3640 * This function is called with the page table lock taken. In the split ptlock
3641 * case the page table lock only protects only those entries which belong to
3642 * the page table corresponding to the fault address.
3644 * This function doesn't cross the VMA boundaries, in order to call map_pages()
3647 * fault_around_pages() defines how many pages we'll try to map.
3648 * do_fault_around() expects it to return a power of two less than or equal to
3651 * The virtual address of the area that we map is naturally aligned to the
3652 * fault_around_pages() value (and therefore to page order). This way it's
3653 * easier to guarantee that we don't cross page table boundaries.
3655 static int do_fault_around(struct vm_fault *vmf)
3657 unsigned long address = vmf->address, nr_pages, mask;
3658 pgoff_t start_pgoff = vmf->pgoff;
3662 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3663 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3665 vmf->address = max(address & mask, vmf->vma->vm_start);
3666 off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3670 * end_pgoff is either end of page table or end of vma
3671 * or fault_around_pages() from start_pgoff, depending what is nearest.
3673 end_pgoff = start_pgoff -
3674 ((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
3676 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
3677 start_pgoff + nr_pages - 1);
3679 if (pmd_none(*vmf->pmd)) {
3680 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
3682 if (!vmf->prealloc_pte)
3684 smp_wmb(); /* See comment in __pte_alloc() */
3687 vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
3689 /* Huge page is mapped? Page fault is solved */
3690 if (pmd_trans_huge(*vmf->pmd)) {
3691 ret = VM_FAULT_NOPAGE;
3695 /* ->map_pages() haven't done anything useful. Cold page cache? */
3699 /* check if the page fault is solved */
3700 vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
3701 if (!pte_none(*vmf->pte))
3702 ret = VM_FAULT_NOPAGE;
3703 pte_unmap_unlock(vmf->pte, vmf->ptl);
3705 vmf->address = address;
3710 static int do_read_fault(struct vm_fault *vmf)
3712 struct vm_area_struct *vma = vmf->vma;
3716 * Let's call ->map_pages() first and use ->fault() as fallback
3717 * if page by the offset is not ready to be mapped (cold cache or
3720 if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
3721 ret = do_fault_around(vmf);
3726 ret = __do_fault(vmf);
3727 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3730 ret |= finish_fault(vmf);
3731 unlock_page(vmf->page);
3732 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3733 put_page(vmf->page);
3737 static int do_cow_fault(struct vm_fault *vmf)
3739 struct vm_area_struct *vma = vmf->vma;
3742 if (unlikely(anon_vma_prepare(vma)))
3743 return VM_FAULT_OOM;
3745 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3747 return VM_FAULT_OOM;
3749 if (mem_cgroup_try_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL,
3750 &vmf->memcg, false)) {
3751 put_page(vmf->cow_page);
3752 return VM_FAULT_OOM;
3755 ret = __do_fault(vmf);
3756 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3758 if (ret & VM_FAULT_DONE_COW)
3761 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
3762 __SetPageUptodate(vmf->cow_page);
3764 ret |= finish_fault(vmf);
3765 unlock_page(vmf->page);
3766 put_page(vmf->page);
3767 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3771 mem_cgroup_cancel_charge(vmf->cow_page, vmf->memcg, false);
3772 put_page(vmf->cow_page);
3776 static int do_shared_fault(struct vm_fault *vmf)
3778 struct vm_area_struct *vma = vmf->vma;
3781 ret = __do_fault(vmf);
3782 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3786 * Check if the backing address space wants to know that the page is
3787 * about to become writable
3789 if (vma->vm_ops->page_mkwrite) {
3790 unlock_page(vmf->page);
3791 tmp = do_page_mkwrite(vmf);
3792 if (unlikely(!tmp ||
3793 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3794 put_page(vmf->page);
3799 ret |= finish_fault(vmf);
3800 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3802 unlock_page(vmf->page);
3803 put_page(vmf->page);
3807 fault_dirty_shared_page(vma, vmf->page);
3812 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3813 * but allow concurrent faults).
3814 * The mmap_sem may have been released depending on flags and our
3815 * return value. See filemap_fault() and __lock_page_or_retry().
3817 static int do_fault(struct vm_fault *vmf)
3819 struct vm_area_struct *vma = vmf->vma;
3823 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
3825 if (!vma->vm_ops->fault) {
3827 * If we find a migration pmd entry or a none pmd entry, which
3828 * should never happen, return SIGBUS
3830 if (unlikely(!pmd_present(*vmf->pmd)))
3831 ret = VM_FAULT_SIGBUS;
3833 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
3838 * Make sure this is not a temporary clearing of pte
3839 * by holding ptl and checking again. A R/M/W update
3840 * of pte involves: take ptl, clearing the pte so that
3841 * we don't have concurrent modification by hardware
3842 * followed by an update.
3844 if (unlikely(pte_none(*vmf->pte)))
3845 ret = VM_FAULT_SIGBUS;
3847 ret = VM_FAULT_NOPAGE;
3849 pte_unmap_unlock(vmf->pte, vmf->ptl);
3851 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
3852 ret = do_read_fault(vmf);
3853 else if (!(vma->vm_flags & VM_SHARED))
3854 ret = do_cow_fault(vmf);
3856 ret = do_shared_fault(vmf);
3858 /* preallocated pagetable is unused: free it */
3859 if (vmf->prealloc_pte) {
3860 pte_free(vma->vm_mm, vmf->prealloc_pte);
3861 vmf->prealloc_pte = NULL;
3866 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3867 unsigned long addr, int page_nid,
3872 count_vm_numa_event(NUMA_HINT_FAULTS);
3873 if (page_nid == numa_node_id()) {
3874 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3875 *flags |= TNF_FAULT_LOCAL;
3878 return mpol_misplaced(page, vma, addr);
3881 static int do_numa_page(struct vm_fault *vmf)
3883 struct vm_area_struct *vma = vmf->vma;
3884 struct page *page = NULL;
3888 bool migrated = false;
3890 bool was_writable = pte_savedwrite(vmf->orig_pte);
3894 * The "pte" at this point cannot be used safely without
3895 * validation through pte_unmap_same(). It's of NUMA type but
3896 * the pfn may be screwed if the read is non atomic.
3898 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
3899 spin_lock(vmf->ptl);
3900 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
3901 pte_unmap_unlock(vmf->pte, vmf->ptl);
3906 * Make it present again, Depending on how arch implementes non
3907 * accessible ptes, some can allow access by kernel mode.
3909 pte = ptep_modify_prot_start(vma->vm_mm, vmf->address, vmf->pte);
3910 pte = pte_modify(pte, vma->vm_page_prot);
3911 pte = pte_mkyoung(pte);
3913 pte = pte_mkwrite(pte);
3914 ptep_modify_prot_commit(vma->vm_mm, vmf->address, vmf->pte, pte);
3915 update_mmu_cache(vma, vmf->address, vmf->pte);
3917 page = vm_normal_page(vma, vmf->address, pte);
3919 pte_unmap_unlock(vmf->pte, vmf->ptl);
3923 /* TODO: handle PTE-mapped THP */
3924 if (PageCompound(page)) {
3925 pte_unmap_unlock(vmf->pte, vmf->ptl);
3930 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
3931 * much anyway since they can be in shared cache state. This misses
3932 * the case where a mapping is writable but the process never writes
3933 * to it but pte_write gets cleared during protection updates and
3934 * pte_dirty has unpredictable behaviour between PTE scan updates,
3935 * background writeback, dirty balancing and application behaviour.
3937 if (!pte_write(pte))
3938 flags |= TNF_NO_GROUP;
3941 * Flag if the page is shared between multiple address spaces. This
3942 * is later used when determining whether to group tasks together
3944 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
3945 flags |= TNF_SHARED;
3947 last_cpupid = page_cpupid_last(page);
3948 page_nid = page_to_nid(page);
3949 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
3951 pte_unmap_unlock(vmf->pte, vmf->ptl);
3952 if (target_nid == -1) {
3957 /* Migrate to the requested node */
3958 migrated = migrate_misplaced_page(page, vma, target_nid);
3960 page_nid = target_nid;
3961 flags |= TNF_MIGRATED;
3963 flags |= TNF_MIGRATE_FAIL;
3967 task_numa_fault(last_cpupid, page_nid, 1, flags);
3971 static inline int create_huge_pmd(struct vm_fault *vmf)
3973 if (vma_is_anonymous(vmf->vma))
3974 return do_huge_pmd_anonymous_page(vmf);
3975 if (vmf->vma->vm_ops->huge_fault)
3976 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
3977 return VM_FAULT_FALLBACK;
3980 static int wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
3982 if (vma_is_anonymous(vmf->vma))
3983 return do_huge_pmd_wp_page(vmf, orig_pmd);
3984 if (vmf->vma->vm_ops->huge_fault)
3985 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
3987 /* COW handled on pte level: split pmd */
3988 VM_BUG_ON_VMA(vmf->vma->vm_flags & VM_SHARED, vmf->vma);
3989 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
3991 return VM_FAULT_FALLBACK;
3994 static inline bool vma_is_accessible(struct vm_area_struct *vma)
3996 return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
3999 static int create_huge_pud(struct vm_fault *vmf)
4001 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4002 /* No support for anonymous transparent PUD pages yet */
4003 if (vma_is_anonymous(vmf->vma))
4004 return VM_FAULT_FALLBACK;
4005 if (vmf->vma->vm_ops->huge_fault)
4006 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4007 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4008 return VM_FAULT_FALLBACK;
4011 static int wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4013 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4014 /* No support for anonymous transparent PUD pages yet */
4015 if (vma_is_anonymous(vmf->vma))
4016 return VM_FAULT_FALLBACK;
4017 if (vmf->vma->vm_ops->huge_fault)
4018 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4019 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4020 return VM_FAULT_FALLBACK;
4024 * These routines also need to handle stuff like marking pages dirty
4025 * and/or accessed for architectures that don't do it in hardware (most
4026 * RISC architectures). The early dirtying is also good on the i386.
4028 * There is also a hook called "update_mmu_cache()" that architectures
4029 * with external mmu caches can use to update those (ie the Sparc or
4030 * PowerPC hashed page tables that act as extended TLBs).
4032 * We enter with non-exclusive mmap_sem (to exclude vma changes, but allow
4033 * concurrent faults).
4035 * The mmap_sem may have been released depending on flags and our return value.
4036 * See filemap_fault() and __lock_page_or_retry().
4038 static int handle_pte_fault(struct vm_fault *vmf)
4042 if (unlikely(pmd_none(*vmf->pmd))) {
4044 * Leave __pte_alloc() until later: because vm_ops->fault may
4045 * want to allocate huge page, and if we expose page table
4046 * for an instant, it will be difficult to retract from
4047 * concurrent faults and from rmap lookups.
4051 /* See comment in pte_alloc_one_map() */
4052 if (pmd_devmap_trans_unstable(vmf->pmd))
4055 * A regular pmd is established and it can't morph into a huge
4056 * pmd from under us anymore at this point because we hold the
4057 * mmap_sem read mode and khugepaged takes it in write mode.
4058 * So now it's safe to run pte_offset_map().
4060 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4061 vmf->orig_pte = *vmf->pte;
4064 * some architectures can have larger ptes than wordsize,
4065 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4066 * CONFIG_32BIT=y, so READ_ONCE or ACCESS_ONCE cannot guarantee
4067 * atomic accesses. The code below just needs a consistent
4068 * view for the ifs and we later double check anyway with the
4069 * ptl lock held. So here a barrier will do.
4072 if (pte_none(vmf->orig_pte)) {
4073 pte_unmap(vmf->pte);
4079 if (vma_is_anonymous(vmf->vma))
4080 return do_anonymous_page(vmf);
4082 return do_fault(vmf);
4085 if (!pte_present(vmf->orig_pte))
4086 return do_swap_page(vmf);
4088 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4089 return do_numa_page(vmf);
4091 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4092 spin_lock(vmf->ptl);
4093 entry = vmf->orig_pte;
4094 if (unlikely(!pte_same(*vmf->pte, entry)))
4096 if (vmf->flags & FAULT_FLAG_WRITE) {
4097 if (!pte_write(entry))
4098 return do_wp_page(vmf);
4099 entry = pte_mkdirty(entry);
4101 entry = pte_mkyoung(entry);
4102 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4103 vmf->flags & FAULT_FLAG_WRITE)) {
4104 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4107 * This is needed only for protection faults but the arch code
4108 * is not yet telling us if this is a protection fault or not.
4109 * This still avoids useless tlb flushes for .text page faults
4112 if (vmf->flags & FAULT_FLAG_WRITE)
4113 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4116 pte_unmap_unlock(vmf->pte, vmf->ptl);
4121 * By the time we get here, we already hold the mm semaphore
4123 * The mmap_sem may have been released depending on flags and our
4124 * return value. See filemap_fault() and __lock_page_or_retry().
4126 static int __handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4129 struct vm_fault vmf = {
4131 .address = address & PAGE_MASK,
4133 .pgoff = linear_page_index(vma, address),
4134 .gfp_mask = __get_fault_gfp_mask(vma),
4136 unsigned int dirty = flags & FAULT_FLAG_WRITE;
4137 struct mm_struct *mm = vma->vm_mm;
4142 pgd = pgd_offset(mm, address);
4143 p4d = p4d_alloc(mm, pgd, address);
4145 return VM_FAULT_OOM;
4147 vmf.pud = pud_alloc(mm, p4d, address);
4149 return VM_FAULT_OOM;
4150 if (pud_none(*vmf.pud) && transparent_hugepage_enabled(vma)) {
4151 ret = create_huge_pud(&vmf);
4152 if (!(ret & VM_FAULT_FALLBACK))
4155 pud_t orig_pud = *vmf.pud;
4158 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4160 /* NUMA case for anonymous PUDs would go here */
4162 if (dirty && !pud_write(orig_pud)) {
4163 ret = wp_huge_pud(&vmf, orig_pud);
4164 if (!(ret & VM_FAULT_FALLBACK))
4167 huge_pud_set_accessed(&vmf, orig_pud);
4173 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4175 return VM_FAULT_OOM;
4176 if (pmd_none(*vmf.pmd) && transparent_hugepage_enabled(vma)) {
4177 ret = create_huge_pmd(&vmf);
4178 if (!(ret & VM_FAULT_FALLBACK))
4181 pmd_t orig_pmd = *vmf.pmd;
4184 if (unlikely(is_swap_pmd(orig_pmd))) {
4185 VM_BUG_ON(thp_migration_supported() &&
4186 !is_pmd_migration_entry(orig_pmd));
4187 if (is_pmd_migration_entry(orig_pmd))
4188 pmd_migration_entry_wait(mm, vmf.pmd);
4191 if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
4192 if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
4193 return do_huge_pmd_numa_page(&vmf, orig_pmd);
4195 if (dirty && !pmd_write(orig_pmd)) {
4196 ret = wp_huge_pmd(&vmf, orig_pmd);
4197 if (!(ret & VM_FAULT_FALLBACK))
4200 huge_pmd_set_accessed(&vmf, orig_pmd);
4206 return handle_pte_fault(&vmf);
4210 * By the time we get here, we already hold the mm semaphore
4212 * The mmap_sem may have been released depending on flags and our
4213 * return value. See filemap_fault() and __lock_page_or_retry().
4215 int handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4220 __set_current_state(TASK_RUNNING);
4222 count_vm_event(PGFAULT);
4223 count_memcg_event_mm(vma->vm_mm, PGFAULT);
4225 /* do counter updates before entering really critical section. */
4226 check_sync_rss_stat(current);
4228 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4229 flags & FAULT_FLAG_INSTRUCTION,
4230 flags & FAULT_FLAG_REMOTE))
4231 return VM_FAULT_SIGSEGV;
4234 * Enable the memcg OOM handling for faults triggered in user
4235 * space. Kernel faults are handled more gracefully.
4237 if (flags & FAULT_FLAG_USER)
4238 mem_cgroup_oom_enable();
4240 if (unlikely(is_vm_hugetlb_page(vma)))
4241 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4243 ret = __handle_mm_fault(vma, address, flags);
4245 if (flags & FAULT_FLAG_USER) {
4246 mem_cgroup_oom_disable();
4248 * The task may have entered a memcg OOM situation but
4249 * if the allocation error was handled gracefully (no
4250 * VM_FAULT_OOM), there is no need to kill anything.
4251 * Just clean up the OOM state peacefully.
4253 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4254 mem_cgroup_oom_synchronize(false);
4259 EXPORT_SYMBOL_GPL(handle_mm_fault);
4261 #ifndef __PAGETABLE_P4D_FOLDED
4263 * Allocate p4d page table.
4264 * We've already handled the fast-path in-line.
4266 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4268 p4d_t *new = p4d_alloc_one(mm, address);
4272 smp_wmb(); /* See comment in __pte_alloc */
4274 spin_lock(&mm->page_table_lock);
4275 if (pgd_present(*pgd)) /* Another has populated it */
4278 pgd_populate(mm, pgd, new);
4279 spin_unlock(&mm->page_table_lock);
4282 #endif /* __PAGETABLE_P4D_FOLDED */
4284 #ifndef __PAGETABLE_PUD_FOLDED
4286 * Allocate page upper directory.
4287 * We've already handled the fast-path in-line.
4289 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4291 pud_t *new = pud_alloc_one(mm, address);
4295 smp_wmb(); /* See comment in __pte_alloc */
4297 spin_lock(&mm->page_table_lock);
4298 #ifndef __ARCH_HAS_5LEVEL_HACK
4299 if (p4d_present(*p4d)) /* Another has populated it */
4302 p4d_populate(mm, p4d, new);
4304 if (pgd_present(*p4d)) /* Another has populated it */
4307 pgd_populate(mm, p4d, new);
4308 #endif /* __ARCH_HAS_5LEVEL_HACK */
4309 spin_unlock(&mm->page_table_lock);
4312 #endif /* __PAGETABLE_PUD_FOLDED */
4314 #ifndef __PAGETABLE_PMD_FOLDED
4316 * Allocate page middle directory.
4317 * We've already handled the fast-path in-line.
4319 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4322 pmd_t *new = pmd_alloc_one(mm, address);
4326 smp_wmb(); /* See comment in __pte_alloc */
4328 ptl = pud_lock(mm, pud);
4329 #ifndef __ARCH_HAS_4LEVEL_HACK
4330 if (!pud_present(*pud)) {
4332 pud_populate(mm, pud, new);
4333 } else /* Another has populated it */
4336 if (!pgd_present(*pud)) {
4338 pgd_populate(mm, pud, new);
4339 } else /* Another has populated it */
4341 #endif /* __ARCH_HAS_4LEVEL_HACK */
4345 #endif /* __PAGETABLE_PMD_FOLDED */
4347 static int __follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4348 unsigned long *start, unsigned long *end,
4349 pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4357 pgd = pgd_offset(mm, address);
4358 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4361 p4d = p4d_offset(pgd, address);
4362 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4365 pud = pud_offset(p4d, address);
4366 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4369 pmd = pmd_offset(pud, address);
4370 VM_BUG_ON(pmd_trans_huge(*pmd));
4372 if (pmd_huge(*pmd)) {
4377 *start = address & PMD_MASK;
4378 *end = *start + PMD_SIZE;
4379 mmu_notifier_invalidate_range_start(mm, *start, *end);
4381 *ptlp = pmd_lock(mm, pmd);
4382 if (pmd_huge(*pmd)) {
4388 mmu_notifier_invalidate_range_end(mm, *start, *end);
4391 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4395 *start = address & PAGE_MASK;
4396 *end = *start + PAGE_SIZE;
4397 mmu_notifier_invalidate_range_start(mm, *start, *end);
4399 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4400 if (!pte_present(*ptep))
4405 pte_unmap_unlock(ptep, *ptlp);
4407 mmu_notifier_invalidate_range_end(mm, *start, *end);
4412 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4413 pte_t **ptepp, spinlock_t **ptlp)
4417 /* (void) is needed to make gcc happy */
4418 (void) __cond_lock(*ptlp,
4419 !(res = __follow_pte_pmd(mm, address, NULL, NULL,
4420 ptepp, NULL, ptlp)));
4424 int follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4425 unsigned long *start, unsigned long *end,
4426 pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4430 /* (void) is needed to make gcc happy */
4431 (void) __cond_lock(*ptlp,
4432 !(res = __follow_pte_pmd(mm, address, start, end,
4433 ptepp, pmdpp, ptlp)));
4436 EXPORT_SYMBOL(follow_pte_pmd);
4439 * follow_pfn - look up PFN at a user virtual address
4440 * @vma: memory mapping
4441 * @address: user virtual address
4442 * @pfn: location to store found PFN
4444 * Only IO mappings and raw PFN mappings are allowed.
4446 * Returns zero and the pfn at @pfn on success, -ve otherwise.
4448 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4455 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4458 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4461 *pfn = pte_pfn(*ptep);
4462 pte_unmap_unlock(ptep, ptl);
4465 EXPORT_SYMBOL(follow_pfn);
4467 #ifdef CONFIG_HAVE_IOREMAP_PROT
4468 int follow_phys(struct vm_area_struct *vma,
4469 unsigned long address, unsigned int flags,
4470 unsigned long *prot, resource_size_t *phys)
4476 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4479 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4483 if ((flags & FOLL_WRITE) && !pte_write(pte))
4486 *prot = pgprot_val(pte_pgprot(pte));
4487 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4491 pte_unmap_unlock(ptep, ptl);
4496 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4497 void *buf, int len, int write)
4499 resource_size_t phys_addr;
4500 unsigned long prot = 0;
4501 void __iomem *maddr;
4502 int offset = addr & (PAGE_SIZE-1);
4504 if (follow_phys(vma, addr, write, &prot, &phys_addr))
4507 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4512 memcpy_toio(maddr + offset, buf, len);
4514 memcpy_fromio(buf, maddr + offset, len);
4519 EXPORT_SYMBOL_GPL(generic_access_phys);
4523 * Access another process' address space as given in mm. If non-NULL, use the
4524 * given task for page fault accounting.
4526 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4527 unsigned long addr, void *buf, int len, unsigned int gup_flags)
4529 struct vm_area_struct *vma;
4530 void *old_buf = buf;
4531 int write = gup_flags & FOLL_WRITE;
4533 down_read(&mm->mmap_sem);
4534 /* ignore errors, just check how much was successfully transferred */
4536 int bytes, ret, offset;
4538 struct page *page = NULL;
4540 ret = get_user_pages_remote(tsk, mm, addr, 1,
4541 gup_flags, &page, &vma, NULL);
4543 #ifndef CONFIG_HAVE_IOREMAP_PROT
4547 * Check if this is a VM_IO | VM_PFNMAP VMA, which
4548 * we can access using slightly different code.
4550 vma = find_vma(mm, addr);
4551 if (!vma || vma->vm_start > addr)
4553 if (vma->vm_ops && vma->vm_ops->access)
4554 ret = vma->vm_ops->access(vma, addr, buf,
4562 offset = addr & (PAGE_SIZE-1);
4563 if (bytes > PAGE_SIZE-offset)
4564 bytes = PAGE_SIZE-offset;
4568 copy_to_user_page(vma, page, addr,
4569 maddr + offset, buf, bytes);
4570 set_page_dirty_lock(page);
4572 copy_from_user_page(vma, page, addr,
4573 buf, maddr + offset, bytes);
4582 up_read(&mm->mmap_sem);
4584 return buf - old_buf;
4588 * access_remote_vm - access another process' address space
4589 * @mm: the mm_struct of the target address space
4590 * @addr: start address to access
4591 * @buf: source or destination buffer
4592 * @len: number of bytes to transfer
4593 * @gup_flags: flags modifying lookup behaviour
4595 * The caller must hold a reference on @mm.
4597 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
4598 void *buf, int len, unsigned int gup_flags)
4600 return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
4604 * Access another process' address space.
4605 * Source/target buffer must be kernel space,
4606 * Do not walk the page table directly, use get_user_pages
4608 int access_process_vm(struct task_struct *tsk, unsigned long addr,
4609 void *buf, int len, unsigned int gup_flags)
4611 struct mm_struct *mm;
4614 mm = get_task_mm(tsk);
4618 ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
4624 EXPORT_SYMBOL_GPL(access_process_vm);
4627 * Print the name of a VMA.
4629 void print_vma_addr(char *prefix, unsigned long ip)
4631 struct mm_struct *mm = current->mm;
4632 struct vm_area_struct *vma;
4635 * Do not print if we are in atomic
4636 * contexts (in exception stacks, etc.):
4638 if (preempt_count())
4641 down_read(&mm->mmap_sem);
4642 vma = find_vma(mm, ip);
4643 if (vma && vma->vm_file) {
4644 struct file *f = vma->vm_file;
4645 char *buf = (char *)__get_free_page(GFP_KERNEL);
4649 p = file_path(f, buf, PAGE_SIZE);
4652 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
4654 vma->vm_end - vma->vm_start);
4655 free_page((unsigned long)buf);
4658 up_read(&mm->mmap_sem);
4661 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4662 void __might_fault(const char *file, int line)
4665 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4666 * holding the mmap_sem, this is safe because kernel memory doesn't
4667 * get paged out, therefore we'll never actually fault, and the
4668 * below annotations will generate false positives.
4670 if (uaccess_kernel())
4672 if (pagefault_disabled())
4674 __might_sleep(file, line, 0);
4675 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4677 might_lock_read(¤t->mm->mmap_sem);
4680 EXPORT_SYMBOL(__might_fault);
4683 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4684 static void clear_gigantic_page(struct page *page,
4686 unsigned int pages_per_huge_page)
4689 struct page *p = page;
4692 for (i = 0; i < pages_per_huge_page;
4693 i++, p = mem_map_next(p, page, i)) {
4695 clear_user_highpage(p, addr + i * PAGE_SIZE);
4698 void clear_huge_page(struct page *page,
4699 unsigned long addr_hint, unsigned int pages_per_huge_page)
4702 unsigned long addr = addr_hint &
4703 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4705 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4706 clear_gigantic_page(page, addr, pages_per_huge_page);
4710 /* Clear sub-page to access last to keep its cache lines hot */
4712 n = (addr_hint - addr) / PAGE_SIZE;
4713 if (2 * n <= pages_per_huge_page) {
4714 /* If sub-page to access in first half of huge page */
4717 /* Clear sub-pages at the end of huge page */
4718 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
4720 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4723 /* If sub-page to access in second half of huge page */
4724 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
4725 l = pages_per_huge_page - n;
4726 /* Clear sub-pages at the begin of huge page */
4727 for (i = 0; i < base; i++) {
4729 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4733 * Clear remaining sub-pages in left-right-left-right pattern
4734 * towards the sub-page to access
4736 for (i = 0; i < l; i++) {
4737 int left_idx = base + i;
4738 int right_idx = base + 2 * l - 1 - i;
4741 clear_user_highpage(page + left_idx,
4742 addr + left_idx * PAGE_SIZE);
4744 clear_user_highpage(page + right_idx,
4745 addr + right_idx * PAGE_SIZE);
4749 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4751 struct vm_area_struct *vma,
4752 unsigned int pages_per_huge_page)
4755 struct page *dst_base = dst;
4756 struct page *src_base = src;
4758 for (i = 0; i < pages_per_huge_page; ) {
4760 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4763 dst = mem_map_next(dst, dst_base, i);
4764 src = mem_map_next(src, src_base, i);
4768 void copy_user_huge_page(struct page *dst, struct page *src,
4769 unsigned long addr, struct vm_area_struct *vma,
4770 unsigned int pages_per_huge_page)
4774 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4775 copy_user_gigantic_page(dst, src, addr, vma,
4776 pages_per_huge_page);
4781 for (i = 0; i < pages_per_huge_page; i++) {
4783 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
4787 long copy_huge_page_from_user(struct page *dst_page,
4788 const void __user *usr_src,
4789 unsigned int pages_per_huge_page,
4790 bool allow_pagefault)
4792 void *src = (void *)usr_src;
4794 unsigned long i, rc = 0;
4795 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
4796 struct page *subpage = dst_page;
4798 for (i = 0; i < pages_per_huge_page;
4799 i++, subpage = mem_map_next(subpage, dst_page, i)) {
4800 if (allow_pagefault)
4801 page_kaddr = kmap(subpage);
4803 page_kaddr = kmap_atomic(subpage);
4804 rc = copy_from_user(page_kaddr,
4805 (const void __user *)(src + i * PAGE_SIZE),
4807 if (allow_pagefault)
4810 kunmap_atomic(page_kaddr);
4812 ret_val -= (PAGE_SIZE - rc);
4820 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
4822 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
4824 static struct kmem_cache *page_ptl_cachep;
4826 void __init ptlock_cache_init(void)
4828 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
4832 bool ptlock_alloc(struct page *page)
4836 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
4843 void ptlock_free(struct page *page)
4845 kmem_cache_free(page_ptl_cachep, page->ptl);