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/hugetlb.h>
44 #include <linux/mman.h>
45 #include <linux/swap.h>
46 #include <linux/highmem.h>
47 #include <linux/pagemap.h>
48 #include <linux/ksm.h>
49 #include <linux/rmap.h>
50 #include <linux/export.h>
51 #include <linux/delayacct.h>
52 #include <linux/init.h>
53 #include <linux/writeback.h>
54 #include <linux/memcontrol.h>
55 #include <linux/mmu_notifier.h>
56 #include <linux/kallsyms.h>
57 #include <linux/swapops.h>
58 #include <linux/elf.h>
59 #include <linux/gfp.h>
60 #include <linux/migrate.h>
61 #include <linux/string.h>
62 #include <linux/dma-contiguous.h>
65 #include <asm/pgalloc.h>
66 #include <asm/uaccess.h>
68 #include <asm/tlbflush.h>
69 #include <asm/pgtable.h>
73 #ifdef LAST_NID_NOT_IN_PAGE_FLAGS
74 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_nid.
77 #ifndef CONFIG_NEED_MULTIPLE_NODES
78 /* use the per-pgdat data instead for discontigmem - mbligh */
79 unsigned long max_mapnr;
82 EXPORT_SYMBOL(max_mapnr);
83 EXPORT_SYMBOL(mem_map);
86 unsigned long num_physpages;
88 * A number of key systems in x86 including ioremap() rely on the assumption
89 * that high_memory defines the upper bound on direct map memory, then end
90 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and
91 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
96 EXPORT_SYMBOL(num_physpages);
97 EXPORT_SYMBOL(high_memory);
100 * Randomize the address space (stacks, mmaps, brk, etc.).
102 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
103 * as ancient (libc5 based) binaries can segfault. )
105 int randomize_va_space __read_mostly =
106 #ifdef CONFIG_COMPAT_BRK
112 static int __init disable_randmaps(char *s)
114 randomize_va_space = 0;
117 __setup("norandmaps", disable_randmaps);
119 unsigned long zero_pfn __read_mostly;
120 unsigned long highest_memmap_pfn __read_mostly;
123 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
125 static int __init init_zero_pfn(void)
127 zero_pfn = page_to_pfn(ZERO_PAGE(0));
130 core_initcall(init_zero_pfn);
133 #if defined(SPLIT_RSS_COUNTING)
135 void sync_mm_rss(struct mm_struct *mm)
139 for (i = 0; i < NR_MM_COUNTERS; i++) {
140 if (current->rss_stat.count[i]) {
141 add_mm_counter(mm, i, current->rss_stat.count[i]);
142 current->rss_stat.count[i] = 0;
145 current->rss_stat.events = 0;
148 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
150 struct task_struct *task = current;
152 if (likely(task->mm == mm))
153 task->rss_stat.count[member] += val;
155 add_mm_counter(mm, member, val);
157 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
158 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
160 /* sync counter once per 64 page faults */
161 #define TASK_RSS_EVENTS_THRESH (64)
162 static void check_sync_rss_stat(struct task_struct *task)
164 if (unlikely(task != current))
166 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
167 sync_mm_rss(task->mm);
169 #else /* SPLIT_RSS_COUNTING */
171 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
172 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
174 static void check_sync_rss_stat(struct task_struct *task)
178 #endif /* SPLIT_RSS_COUNTING */
180 #ifdef HAVE_GENERIC_MMU_GATHER
182 static int tlb_next_batch(struct mmu_gather *tlb)
184 struct mmu_gather_batch *batch;
188 tlb->active = batch->next;
192 if (tlb->batch_count == MAX_GATHER_BATCH_COUNT)
195 batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0);
202 batch->max = MAX_GATHER_BATCH;
204 tlb->active->next = batch;
211 * Called to initialize an (on-stack) mmu_gather structure for page-table
212 * tear-down from @mm. The @fullmm argument is used when @mm is without
213 * users and we're going to destroy the full address space (exit/execve).
215 void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, unsigned long start, unsigned long end)
219 /* Is it from 0 to ~0? */
220 tlb->fullmm = !(start | (end+1));
221 tlb->need_flush_all = 0;
225 tlb->local.next = NULL;
227 tlb->local.max = ARRAY_SIZE(tlb->__pages);
228 tlb->active = &tlb->local;
229 tlb->batch_count = 0;
231 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
236 void tlb_flush_mmu(struct mmu_gather *tlb)
238 struct mmu_gather_batch *batch;
240 if (!tlb->need_flush)
244 mmu_notifier_invalidate_range(tlb->mm, tlb->start, tlb->end);
245 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
246 tlb_table_flush(tlb);
249 for (batch = &tlb->local; batch; batch = batch->next) {
250 free_pages_and_swap_cache(batch->pages, batch->nr);
253 tlb->active = &tlb->local;
257 * Called at the end of the shootdown operation to free up any resources
258 * that were required.
260 void tlb_finish_mmu(struct mmu_gather *tlb, unsigned long start, unsigned long end)
262 struct mmu_gather_batch *batch, *next;
266 /* keep the page table cache within bounds */
269 for (batch = tlb->local.next; batch; batch = next) {
271 free_pages((unsigned long)batch, 0);
273 tlb->local.next = NULL;
277 * Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while
278 * handling the additional races in SMP caused by other CPUs caching valid
279 * mappings in their TLBs. Returns the number of free page slots left.
280 * When out of page slots we must call tlb_flush_mmu().
282 int __tlb_remove_page(struct mmu_gather *tlb, struct page *page)
284 struct mmu_gather_batch *batch;
286 VM_BUG_ON(!tlb->need_flush);
289 batch->pages[batch->nr++] = page;
290 if (batch->nr == batch->max) {
291 if (!tlb_next_batch(tlb))
295 VM_BUG_ON(batch->nr > batch->max);
297 return batch->max - batch->nr;
300 #endif /* HAVE_GENERIC_MMU_GATHER */
302 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
305 * See the comment near struct mmu_table_batch.
308 static void tlb_remove_table_smp_sync(void *arg)
310 /* Simply deliver the interrupt */
313 static void tlb_remove_table_one(void *table)
316 * This isn't an RCU grace period and hence the page-tables cannot be
317 * assumed to be actually RCU-freed.
319 * It is however sufficient for software page-table walkers that rely on
320 * IRQ disabling. See the comment near struct mmu_table_batch.
322 smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
323 __tlb_remove_table(table);
326 static void tlb_remove_table_rcu(struct rcu_head *head)
328 struct mmu_table_batch *batch;
331 batch = container_of(head, struct mmu_table_batch, rcu);
333 for (i = 0; i < batch->nr; i++)
334 __tlb_remove_table(batch->tables[i]);
336 free_page((unsigned long)batch);
339 void tlb_table_flush(struct mmu_gather *tlb)
341 struct mmu_table_batch **batch = &tlb->batch;
344 call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
349 void tlb_remove_table(struct mmu_gather *tlb, void *table)
351 struct mmu_table_batch **batch = &tlb->batch;
356 * When there's less then two users of this mm there cannot be a
357 * concurrent page-table walk.
359 if (atomic_read(&tlb->mm->mm_users) < 2) {
360 __tlb_remove_table(table);
364 if (*batch == NULL) {
365 *batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
366 if (*batch == NULL) {
367 tlb_remove_table_one(table);
372 (*batch)->tables[(*batch)->nr++] = table;
373 if ((*batch)->nr == MAX_TABLE_BATCH)
374 tlb_table_flush(tlb);
377 #endif /* CONFIG_HAVE_RCU_TABLE_FREE */
380 * If a p?d_bad entry is found while walking page tables, report
381 * the error, before resetting entry to p?d_none. Usually (but
382 * very seldom) called out from the p?d_none_or_clear_bad macros.
385 void pgd_clear_bad(pgd_t *pgd)
391 void pud_clear_bad(pud_t *pud)
397 void pmd_clear_bad(pmd_t *pmd)
404 * Note: this doesn't free the actual pages themselves. That
405 * has been handled earlier when unmapping all the memory regions.
407 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
410 pgtable_t token = pmd_pgtable(*pmd);
412 pte_free_tlb(tlb, token, addr);
416 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
417 unsigned long addr, unsigned long end,
418 unsigned long floor, unsigned long ceiling)
425 pmd = pmd_offset(pud, addr);
427 next = pmd_addr_end(addr, end);
428 if (pmd_none_or_clear_bad(pmd))
430 free_pte_range(tlb, pmd, addr);
431 } while (pmd++, addr = next, addr != end);
441 if (end - 1 > ceiling - 1)
444 pmd = pmd_offset(pud, start);
446 pmd_free_tlb(tlb, pmd, start);
449 static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd,
450 unsigned long addr, unsigned long end,
451 unsigned long floor, unsigned long ceiling)
458 pud = pud_offset(pgd, addr);
460 next = pud_addr_end(addr, end);
461 if (pud_none_or_clear_bad(pud))
463 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
464 } while (pud++, addr = next, addr != end);
470 ceiling &= PGDIR_MASK;
474 if (end - 1 > ceiling - 1)
477 pud = pud_offset(pgd, start);
479 pud_free_tlb(tlb, pud, start);
483 * This function frees user-level page tables of a process.
485 * Must be called with pagetable lock held.
487 void free_pgd_range(struct mmu_gather *tlb,
488 unsigned long addr, unsigned long end,
489 unsigned long floor, unsigned long ceiling)
495 * The next few lines have given us lots of grief...
497 * Why are we testing PMD* at this top level? Because often
498 * there will be no work to do at all, and we'd prefer not to
499 * go all the way down to the bottom just to discover that.
501 * Why all these "- 1"s? Because 0 represents both the bottom
502 * of the address space and the top of it (using -1 for the
503 * top wouldn't help much: the masks would do the wrong thing).
504 * The rule is that addr 0 and floor 0 refer to the bottom of
505 * the address space, but end 0 and ceiling 0 refer to the top
506 * Comparisons need to use "end - 1" and "ceiling - 1" (though
507 * that end 0 case should be mythical).
509 * Wherever addr is brought up or ceiling brought down, we must
510 * be careful to reject "the opposite 0" before it confuses the
511 * subsequent tests. But what about where end is brought down
512 * by PMD_SIZE below? no, end can't go down to 0 there.
514 * Whereas we round start (addr) and ceiling down, by different
515 * masks at different levels, in order to test whether a table
516 * now has no other vmas using it, so can be freed, we don't
517 * bother to round floor or end up - the tests don't need that.
531 if (end - 1 > ceiling - 1)
536 pgd = pgd_offset(tlb->mm, addr);
538 next = pgd_addr_end(addr, end);
539 if (pgd_none_or_clear_bad(pgd))
541 free_pud_range(tlb, pgd, addr, next, floor, ceiling);
542 } while (pgd++, addr = next, addr != end);
545 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
546 unsigned long floor, unsigned long ceiling)
549 struct vm_area_struct *next = vma->vm_next;
550 unsigned long addr = vma->vm_start;
553 * Hide vma from rmap and truncate_pagecache before freeing
556 unlink_anon_vmas(vma);
557 unlink_file_vma(vma);
559 if (is_vm_hugetlb_page(vma)) {
560 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
561 floor, next? next->vm_start: ceiling);
564 * Optimization: gather nearby vmas into one call down
566 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
567 && !is_vm_hugetlb_page(next)) {
570 unlink_anon_vmas(vma);
571 unlink_file_vma(vma);
573 free_pgd_range(tlb, addr, vma->vm_end,
574 floor, next? next->vm_start: ceiling);
580 int __pte_alloc(struct mm_struct *mm, struct vm_area_struct *vma,
581 pmd_t *pmd, unsigned long address)
583 pgtable_t new = pte_alloc_one(mm, address);
584 int wait_split_huge_page;
589 * Ensure all pte setup (eg. pte page lock and page clearing) are
590 * visible before the pte is made visible to other CPUs by being
591 * put into page tables.
593 * The other side of the story is the pointer chasing in the page
594 * table walking code (when walking the page table without locking;
595 * ie. most of the time). Fortunately, these data accesses consist
596 * of a chain of data-dependent loads, meaning most CPUs (alpha
597 * being the notable exception) will already guarantee loads are
598 * seen in-order. See the alpha page table accessors for the
599 * smp_read_barrier_depends() barriers in page table walking code.
601 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
603 spin_lock(&mm->page_table_lock);
604 wait_split_huge_page = 0;
605 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
607 pmd_populate(mm, pmd, new);
609 } else if (unlikely(pmd_trans_splitting(*pmd)))
610 wait_split_huge_page = 1;
611 spin_unlock(&mm->page_table_lock);
614 if (wait_split_huge_page)
615 wait_split_huge_page(vma->anon_vma, pmd);
619 int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
621 pte_t *new = pte_alloc_one_kernel(&init_mm, address);
625 smp_wmb(); /* See comment in __pte_alloc */
627 spin_lock(&init_mm.page_table_lock);
628 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
629 pmd_populate_kernel(&init_mm, pmd, new);
632 VM_BUG_ON(pmd_trans_splitting(*pmd));
633 spin_unlock(&init_mm.page_table_lock);
635 pte_free_kernel(&init_mm, new);
639 static inline void init_rss_vec(int *rss)
641 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
644 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
648 if (current->mm == mm)
650 for (i = 0; i < NR_MM_COUNTERS; i++)
652 add_mm_counter(mm, i, rss[i]);
656 * This function is called to print an error when a bad pte
657 * is found. For example, we might have a PFN-mapped pte in
658 * a region that doesn't allow it.
660 * The calling function must still handle the error.
662 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
663 pte_t pte, struct page *page)
665 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
666 pud_t *pud = pud_offset(pgd, addr);
667 pmd_t *pmd = pmd_offset(pud, addr);
668 struct address_space *mapping;
670 static unsigned long resume;
671 static unsigned long nr_shown;
672 static unsigned long nr_unshown;
675 * Allow a burst of 60 reports, then keep quiet for that minute;
676 * or allow a steady drip of one report per second.
678 if (nr_shown == 60) {
679 if (time_before(jiffies, resume)) {
685 "BUG: Bad page map: %lu messages suppressed\n",
692 resume = jiffies + 60 * HZ;
694 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
695 index = linear_page_index(vma, addr);
698 "BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
700 (long long)pte_val(pte), (long long)pmd_val(*pmd));
704 "addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
705 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
707 * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y
710 printk(KERN_ALERT "vma->vm_ops->fault: %pSR\n",
712 if (vma->vm_file && vma->vm_file->f_op)
713 printk(KERN_ALERT "vma->vm_file->f_op->mmap: %pSR\n",
714 vma->vm_file->f_op->mmap);
716 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
719 static inline bool is_cow_mapping(vm_flags_t flags)
721 return (flags & (VM_SHARED | VM_MAYWRITE)) == VM_MAYWRITE;
725 * vm_normal_page -- This function gets the "struct page" associated with a pte.
727 * "Special" mappings do not wish to be associated with a "struct page" (either
728 * it doesn't exist, or it exists but they don't want to touch it). In this
729 * case, NULL is returned here. "Normal" mappings do have a struct page.
731 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
732 * pte bit, in which case this function is trivial. Secondly, an architecture
733 * may not have a spare pte bit, which requires a more complicated scheme,
736 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
737 * special mapping (even if there are underlying and valid "struct pages").
738 * COWed pages of a VM_PFNMAP are always normal.
740 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
741 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
742 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
743 * mapping will always honor the rule
745 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
747 * And for normal mappings this is false.
749 * This restricts such mappings to be a linear translation from virtual address
750 * to pfn. To get around this restriction, we allow arbitrary mappings so long
751 * as the vma is not a COW mapping; in that case, we know that all ptes are
752 * special (because none can have been COWed).
755 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
757 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
758 * page" backing, however the difference is that _all_ pages with a struct
759 * page (that is, those where pfn_valid is true) are refcounted and considered
760 * normal pages by the VM. The disadvantage is that pages are refcounted
761 * (which can be slower and simply not an option for some PFNMAP users). The
762 * advantage is that we don't have to follow the strict linearity rule of
763 * PFNMAP mappings in order to support COWable mappings.
766 #ifdef __HAVE_ARCH_PTE_SPECIAL
767 # define HAVE_PTE_SPECIAL 1
769 # define HAVE_PTE_SPECIAL 0
771 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
774 unsigned long pfn = pte_pfn(pte);
776 if (HAVE_PTE_SPECIAL) {
777 if (likely(!pte_special(pte)))
779 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
781 if (!is_zero_pfn(pfn))
782 print_bad_pte(vma, addr, pte, NULL);
786 /* !HAVE_PTE_SPECIAL case follows: */
788 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
789 if (vma->vm_flags & VM_MIXEDMAP) {
795 off = (addr - vma->vm_start) >> PAGE_SHIFT;
796 if (pfn == vma->vm_pgoff + off)
798 if (!is_cow_mapping(vma->vm_flags))
803 if (is_zero_pfn(pfn))
806 if (unlikely(pfn > highest_memmap_pfn)) {
807 print_bad_pte(vma, addr, pte, NULL);
812 * NOTE! We still have PageReserved() pages in the page tables.
813 * eg. VDSO mappings can cause them to exist.
816 return pfn_to_page(pfn);
820 * copy one vm_area from one task to the other. Assumes the page tables
821 * already present in the new task to be cleared in the whole range
822 * covered by this vma.
825 static inline unsigned long
826 copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
827 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
828 unsigned long addr, int *rss)
830 unsigned long vm_flags = vma->vm_flags;
831 pte_t pte = *src_pte;
834 /* pte contains position in swap or file, so copy. */
835 if (unlikely(!pte_present(pte))) {
836 if (!pte_file(pte)) {
837 swp_entry_t entry = pte_to_swp_entry(pte);
839 if (likely(!non_swap_entry(entry))) {
840 if (swap_duplicate(entry) < 0)
843 /* make sure dst_mm is on swapoff's mmlist. */
844 if (unlikely(list_empty(&dst_mm->mmlist))) {
845 spin_lock(&mmlist_lock);
846 if (list_empty(&dst_mm->mmlist))
847 list_add(&dst_mm->mmlist,
849 spin_unlock(&mmlist_lock);
852 } else if (is_migration_entry(entry)) {
853 page = migration_entry_to_page(entry);
860 if (is_write_migration_entry(entry) &&
861 is_cow_mapping(vm_flags)) {
863 * COW mappings require pages in both
864 * parent and child to be set to read.
866 make_migration_entry_read(&entry);
867 pte = swp_entry_to_pte(entry);
868 set_pte_at(src_mm, addr, src_pte, pte);
876 * If it's a COW mapping, write protect it both
877 * in the parent and the child
879 if (is_cow_mapping(vm_flags)) {
880 ptep_set_wrprotect(src_mm, addr, src_pte);
881 pte = pte_wrprotect(pte);
885 * If it's a shared mapping, mark it clean in
888 if (vm_flags & VM_SHARED)
889 pte = pte_mkclean(pte);
890 pte = pte_mkold(pte);
892 page = vm_normal_page(vma, addr, pte);
903 set_pte_at(dst_mm, addr, dst_pte, pte);
907 int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
908 pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
909 unsigned long addr, unsigned long end)
911 pte_t *orig_src_pte, *orig_dst_pte;
912 pte_t *src_pte, *dst_pte;
913 spinlock_t *src_ptl, *dst_ptl;
915 int rss[NR_MM_COUNTERS];
916 swp_entry_t entry = (swp_entry_t){0};
921 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
924 src_pte = pte_offset_map(src_pmd, addr);
925 src_ptl = pte_lockptr(src_mm, src_pmd);
926 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
927 orig_src_pte = src_pte;
928 orig_dst_pte = dst_pte;
929 arch_enter_lazy_mmu_mode();
933 * We are holding two locks at this point - either of them
934 * could generate latencies in another task on another CPU.
936 if (progress >= 32) {
938 if (need_resched() ||
939 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
942 if (pte_none(*src_pte)) {
946 entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
951 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
953 arch_leave_lazy_mmu_mode();
954 spin_unlock(src_ptl);
955 pte_unmap(orig_src_pte);
956 add_mm_rss_vec(dst_mm, rss);
957 pte_unmap_unlock(orig_dst_pte, dst_ptl);
961 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
970 static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
971 pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
972 unsigned long addr, unsigned long end)
974 pmd_t *src_pmd, *dst_pmd;
977 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
980 src_pmd = pmd_offset(src_pud, addr);
982 next = pmd_addr_end(addr, end);
983 if (pmd_trans_huge(*src_pmd)) {
985 VM_BUG_ON(next-addr != HPAGE_PMD_SIZE);
986 err = copy_huge_pmd(dst_mm, src_mm,
987 dst_pmd, src_pmd, addr, vma);
994 if (pmd_none_or_clear_bad(src_pmd))
996 if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
999 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1003 static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1004 pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
1005 unsigned long addr, unsigned long end)
1007 pud_t *src_pud, *dst_pud;
1010 dst_pud = pud_alloc(dst_mm, dst_pgd, addr);
1013 src_pud = pud_offset(src_pgd, addr);
1015 next = pud_addr_end(addr, end);
1016 if (pud_none_or_clear_bad(src_pud))
1018 if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
1021 } while (dst_pud++, src_pud++, addr = next, addr != end);
1025 int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1026 struct vm_area_struct *vma)
1028 pgd_t *src_pgd, *dst_pgd;
1030 unsigned long addr = vma->vm_start;
1031 unsigned long end = vma->vm_end;
1032 unsigned long mmun_start; /* For mmu_notifiers */
1033 unsigned long mmun_end; /* For mmu_notifiers */
1038 * Don't copy ptes where a page fault will fill them correctly.
1039 * Fork becomes much lighter when there are big shared or private
1040 * readonly mappings. The tradeoff is that copy_page_range is more
1041 * efficient than faulting.
1043 if (!(vma->vm_flags & (VM_HUGETLB | VM_NONLINEAR |
1044 VM_PFNMAP | VM_MIXEDMAP))) {
1049 if (is_vm_hugetlb_page(vma))
1050 return copy_hugetlb_page_range(dst_mm, src_mm, vma);
1052 if (unlikely(vma->vm_flags & VM_PFNMAP)) {
1054 * We do not free on error cases below as remove_vma
1055 * gets called on error from higher level routine
1057 ret = track_pfn_copy(vma);
1063 * We need to invalidate the secondary MMU mappings only when
1064 * there could be a permission downgrade on the ptes of the
1065 * parent mm. And a permission downgrade will only happen if
1066 * is_cow_mapping() returns true.
1068 is_cow = is_cow_mapping(vma->vm_flags);
1072 mmu_notifier_invalidate_range_start(vma, mmun_start,
1073 mmun_end, MMU_MIGRATE);
1076 dst_pgd = pgd_offset(dst_mm, addr);
1077 src_pgd = pgd_offset(src_mm, addr);
1079 next = pgd_addr_end(addr, end);
1080 if (pgd_none_or_clear_bad(src_pgd))
1082 if (unlikely(copy_pud_range(dst_mm, src_mm, dst_pgd, src_pgd,
1083 vma, addr, next))) {
1087 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1090 mmu_notifier_invalidate_range_end(vma, mmun_start,
1091 mmun_end, MMU_MIGRATE);
1095 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1096 struct vm_area_struct *vma, pmd_t *pmd,
1097 unsigned long addr, unsigned long end,
1098 struct zap_details *details)
1100 struct mm_struct *mm = tlb->mm;
1101 int force_flush = 0;
1102 int rss[NR_MM_COUNTERS];
1109 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1111 arch_enter_lazy_mmu_mode();
1114 if (pte_none(ptent)) {
1118 if (pte_present(ptent)) {
1121 page = vm_normal_page(vma, addr, ptent);
1122 if (unlikely(details) && page) {
1124 * unmap_shared_mapping_pages() wants to
1125 * invalidate cache without truncating:
1126 * unmap shared but keep private pages.
1128 if (details->check_mapping &&
1129 details->check_mapping != page->mapping)
1132 * Each page->index must be checked when
1133 * invalidating or truncating nonlinear.
1135 if (details->nonlinear_vma &&
1136 (page->index < details->first_index ||
1137 page->index > details->last_index))
1140 ptent = ptep_get_and_clear_full(mm, addr, pte,
1142 tlb_remove_tlb_entry(tlb, pte, addr);
1143 if (unlikely(!page))
1145 if (unlikely(details) && details->nonlinear_vma
1146 && linear_page_index(details->nonlinear_vma,
1147 addr) != page->index)
1148 set_pte_at(mm, addr, pte,
1149 pgoff_to_pte(page->index));
1151 rss[MM_ANONPAGES]--;
1153 if (pte_dirty(ptent))
1154 set_page_dirty(page);
1155 if (pte_young(ptent) &&
1156 likely(!VM_SequentialReadHint(vma)))
1157 mark_page_accessed(page);
1158 rss[MM_FILEPAGES]--;
1160 page_remove_rmap(page);
1161 if (unlikely(page_mapcount(page) < 0))
1162 print_bad_pte(vma, addr, ptent, page);
1163 force_flush = !__tlb_remove_page(tlb, page);
1169 * If details->check_mapping, we leave swap entries;
1170 * if details->nonlinear_vma, we leave file entries.
1172 if (unlikely(details))
1174 if (pte_file(ptent)) {
1175 if (unlikely(!(vma->vm_flags & VM_NONLINEAR)))
1176 print_bad_pte(vma, addr, ptent, NULL);
1178 swp_entry_t entry = pte_to_swp_entry(ptent);
1180 if (!non_swap_entry(entry))
1182 else if (is_migration_entry(entry)) {
1185 page = migration_entry_to_page(entry);
1188 rss[MM_ANONPAGES]--;
1190 rss[MM_FILEPAGES]--;
1192 if (unlikely(!free_swap_and_cache(entry)))
1193 print_bad_pte(vma, addr, ptent, NULL);
1195 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1196 } while (pte++, addr += PAGE_SIZE, addr != end);
1198 add_mm_rss_vec(mm, rss);
1199 arch_leave_lazy_mmu_mode();
1200 pte_unmap_unlock(start_pte, ptl);
1203 * mmu_gather ran out of room to batch pages, we break out of
1204 * the PTE lock to avoid doing the potential expensive TLB invalidate
1205 * and page-free while holding it.
1208 unsigned long old_end;
1213 * Flush the TLB just for the previous segment,
1214 * then update the range to be the remaining
1221 mmu_notifier_invalidate_range_free_pages(vma, tlb->start,
1234 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1235 struct vm_area_struct *vma, pud_t *pud,
1236 unsigned long addr, unsigned long end,
1237 struct zap_details *details)
1242 pmd = pmd_offset(pud, addr);
1244 next = pmd_addr_end(addr, end);
1245 if (pmd_trans_huge(*pmd)) {
1246 if (next - addr != HPAGE_PMD_SIZE) {
1247 #ifdef CONFIG_DEBUG_VM
1248 if (!rwsem_is_locked(&tlb->mm->mmap_sem)) {
1249 pr_err("%s: mmap_sem is unlocked! addr=0x%lx end=0x%lx vma->vm_start=0x%lx vma->vm_end=0x%lx\n",
1250 __func__, addr, end,
1256 split_huge_page_pmd(vma, addr, pmd);
1257 } else if (zap_huge_pmd(tlb, vma, pmd, addr))
1262 * Here there can be other concurrent MADV_DONTNEED or
1263 * trans huge page faults running, and if the pmd is
1264 * none or trans huge it can change under us. This is
1265 * because MADV_DONTNEED holds the mmap_sem in read
1268 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1270 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1273 } while (pmd++, addr = next, addr != end);
1278 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1279 struct vm_area_struct *vma, pgd_t *pgd,
1280 unsigned long addr, unsigned long end,
1281 struct zap_details *details)
1286 pud = pud_offset(pgd, addr);
1288 next = pud_addr_end(addr, end);
1289 if (pud_none_or_clear_bad(pud))
1291 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1292 } while (pud++, addr = next, addr != end);
1297 static void unmap_page_range(struct mmu_gather *tlb,
1298 struct vm_area_struct *vma,
1299 unsigned long addr, unsigned long end,
1300 struct zap_details *details)
1305 if (details && !details->check_mapping && !details->nonlinear_vma)
1308 BUG_ON(addr >= end);
1309 mem_cgroup_uncharge_start();
1310 tlb_start_vma(tlb, vma);
1311 /* Make sure tlb as proper range so intermediate call to mmu_notifier
1312 * have accurate informations.
1314 tlb->start = max(tlb->start, addr);
1315 pgd = pgd_offset(vma->vm_mm, addr);
1317 next = pgd_addr_end(addr, end);
1318 if (pgd_none_or_clear_bad(pgd))
1320 next = zap_pud_range(tlb, vma, pgd, addr, next, details);
1321 } while (pgd++, addr = next, addr != end);
1322 mmu_notifier_invalidate_range_free_pages(vma, tlb->start,
1323 min(end, tlb->end));
1324 tlb_end_vma(tlb, vma);
1325 mem_cgroup_uncharge_end();
1329 static void unmap_single_vma(struct mmu_gather *tlb,
1330 struct vm_area_struct *vma, unsigned long start_addr,
1331 unsigned long end_addr,
1332 struct zap_details *details)
1334 unsigned long start = max(vma->vm_start, start_addr);
1337 if (start >= vma->vm_end)
1339 end = min(vma->vm_end, end_addr);
1340 if (end <= vma->vm_start)
1343 mmu_notifier_invalidate_range_start(vma,
1344 max(start_addr, vma->vm_start),
1345 min(end_addr, vma->vm_end),
1349 uprobe_munmap(vma, start, end);
1351 if (unlikely(vma->vm_flags & VM_PFNMAP))
1352 untrack_pfn(vma, 0, 0);
1355 if (unlikely(is_vm_hugetlb_page(vma))) {
1357 * It is undesirable to test vma->vm_file as it
1358 * should be non-null for valid hugetlb area.
1359 * However, vm_file will be NULL in the error
1360 * cleanup path of do_mmap_pgoff. When
1361 * hugetlbfs ->mmap method fails,
1362 * do_mmap_pgoff() nullifies vma->vm_file
1363 * before calling this function to clean up.
1364 * Since no pte has actually been setup, it is
1365 * safe to do nothing in this case.
1368 mutex_lock(&vma->vm_file->f_mapping->i_mmap_mutex);
1369 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1370 mutex_unlock(&vma->vm_file->f_mapping->i_mmap_mutex);
1373 unmap_page_range(tlb, vma, start, end, details);
1376 mmu_notifier_invalidate_range_end(vma,
1377 max(start_addr, vma->vm_start),
1378 min(end_addr, vma->vm_end),
1383 * unmap_vmas - unmap a range of memory covered by a list of vma's
1384 * @tlb: address of the caller's struct mmu_gather
1385 * @vma: the starting vma
1386 * @start_addr: virtual address at which to start unmapping
1387 * @end_addr: virtual address at which to end unmapping
1389 * Unmap all pages in the vma list.
1391 * Only addresses between `start' and `end' will be unmapped.
1393 * The VMA list must be sorted in ascending virtual address order.
1395 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1396 * range after unmap_vmas() returns. So the only responsibility here is to
1397 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1398 * drops the lock and schedules.
1400 void unmap_vmas(struct mmu_gather *tlb,
1401 struct vm_area_struct *vma, unsigned long start_addr,
1402 unsigned long end_addr)
1404 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1405 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1409 * zap_page_range - remove user pages in a given range
1410 * @vma: vm_area_struct holding the applicable pages
1411 * @start: starting address of pages to zap
1412 * @size: number of bytes to zap
1413 * @details: details of nonlinear truncation or shared cache invalidation
1415 * Caller must protect the VMA list
1417 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1418 unsigned long size, struct zap_details *details)
1420 struct mm_struct *mm = vma->vm_mm;
1421 struct mmu_gather tlb;
1422 unsigned long end = start + size;
1425 tlb_gather_mmu(&tlb, mm, start, end);
1426 update_hiwater_rss(mm);
1427 for ( ; vma && vma->vm_start < end; vma = vma->vm_next)
1428 unmap_single_vma(&tlb, vma, start, end, details);
1429 tlb_finish_mmu(&tlb, start, end);
1433 * zap_page_range_single - remove user pages in a given range
1434 * @vma: vm_area_struct holding the applicable pages
1435 * @address: starting address of pages to zap
1436 * @size: number of bytes to zap
1437 * @details: details of nonlinear truncation or shared cache invalidation
1439 * The range must fit into one VMA.
1441 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1442 unsigned long size, struct zap_details *details)
1444 struct mm_struct *mm = vma->vm_mm;
1445 struct mmu_gather tlb;
1446 unsigned long end = address + size;
1449 tlb_gather_mmu(&tlb, mm, address, end);
1450 update_hiwater_rss(mm);
1451 unmap_single_vma(&tlb, vma, address, end, details);
1452 tlb_finish_mmu(&tlb, address, end);
1456 * zap_vma_ptes - remove ptes mapping the vma
1457 * @vma: vm_area_struct holding ptes to be zapped
1458 * @address: starting address of pages to zap
1459 * @size: number of bytes to zap
1461 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1463 * The entire address range must be fully contained within the vma.
1465 * Returns 0 if successful.
1467 int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1470 if (address < vma->vm_start || address + size > vma->vm_end ||
1471 !(vma->vm_flags & VM_PFNMAP))
1473 zap_page_range_single(vma, address, size, NULL);
1476 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1478 #define FOLL_CMA 0x10000000
1481 * FOLL_FORCE can write to even unwritable pte's, but only
1482 * after we've gone through a COW cycle and they are dirty.
1484 static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
1486 return pte_write(pte) ||
1487 ((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
1491 * follow_page_mask - look up a page descriptor from a user-virtual address
1492 * @vma: vm_area_struct mapping @address
1493 * @address: virtual address to look up
1494 * @flags: flags modifying lookup behaviour
1495 * @page_mask: on output, *page_mask is set according to the size of the page
1497 * @flags can have FOLL_ flags set, defined in <linux/mm.h>
1499 * Returns the mapped (struct page *), %NULL if no mapping exists, or
1500 * an error pointer if there is a mapping to something not represented
1501 * by a page descriptor (see also vm_normal_page()).
1503 struct page *follow_page_mask(struct vm_area_struct *vma,
1504 unsigned long address, unsigned int flags,
1505 unsigned int *page_mask)
1513 struct mm_struct *mm = vma->vm_mm;
1514 bool replace_page = false;
1518 page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
1519 if (!IS_ERR(page)) {
1520 BUG_ON(flags & FOLL_GET);
1525 pgd = pgd_offset(mm, address);
1526 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
1529 pud = pud_offset(pgd, address);
1532 if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) {
1533 BUG_ON(flags & FOLL_GET);
1534 page = follow_huge_pud(mm, address, pud, flags & FOLL_WRITE);
1537 if (unlikely(pud_bad(*pud)))
1540 pmd = pmd_offset(pud, address);
1543 if (pmd_huge(*pmd) && vma->vm_flags & VM_HUGETLB) {
1544 BUG_ON(flags & FOLL_GET);
1545 page = follow_huge_pmd(mm, address, pmd, flags & FOLL_WRITE);
1548 if ((flags & FOLL_NUMA) && pmd_numa(*pmd))
1550 if (pmd_trans_huge(*pmd)) {
1551 if (flags & FOLL_SPLIT) {
1552 split_huge_page_pmd(vma, address, pmd);
1553 goto split_fallthrough;
1555 spin_lock(&mm->page_table_lock);
1556 if (likely(pmd_trans_huge(*pmd))) {
1557 if (unlikely(pmd_trans_splitting(*pmd))) {
1558 spin_unlock(&mm->page_table_lock);
1559 wait_split_huge_page(vma->anon_vma, pmd);
1561 page = follow_trans_huge_pmd(vma, address,
1563 spin_unlock(&mm->page_table_lock);
1564 *page_mask = HPAGE_PMD_NR - 1;
1568 spin_unlock(&mm->page_table_lock);
1572 if (unlikely(pmd_bad(*pmd)))
1575 ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
1578 if (!pte_present(pte)) {
1581 * KSM's break_ksm() relies upon recognizing a ksm page
1582 * even while it is being migrated, so for that case we
1583 * need migration_entry_wait().
1585 if (likely(!(flags & FOLL_MIGRATION)))
1587 if (pte_none(pte) || pte_file(pte))
1589 entry = pte_to_swp_entry(pte);
1590 if (!is_migration_entry(entry))
1592 pte_unmap_unlock(ptep, ptl);
1593 migration_entry_wait(mm, pmd, address);
1594 goto split_fallthrough;
1596 if ((flags & FOLL_NUMA) && pte_numa(pte))
1598 if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags))
1601 page = vm_normal_page(vma, address, pte);
1602 if (unlikely(!page)) {
1603 if ((flags & FOLL_DUMP) ||
1604 !is_zero_pfn(pte_pfn(pte)))
1606 page = pte_page(pte);
1609 if ((flags & FOLL_CMA) && (flags & FOLL_GET) &&
1610 dma_contiguous_should_replace_page(page))
1612 * Don't get ref on page.
1613 * Let __get_user_pages replace the CMA page with non-CMA.
1615 replace_page = true;
1616 else if (flags & FOLL_GET)
1617 get_page_foll(page);
1619 if (flags & FOLL_TOUCH) {
1620 if ((flags & FOLL_WRITE) &&
1621 !pte_dirty(pte) && !PageDirty(page))
1622 set_page_dirty(page);
1624 * pte_mkyoung() would be more correct here, but atomic care
1625 * is needed to avoid losing the dirty bit: it is easier to use
1626 * mark_page_accessed().
1628 mark_page_accessed(page);
1630 if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
1632 * The preliminary mapping check is mainly to avoid the
1633 * pointless overhead of lock_page on the ZERO_PAGE
1634 * which might bounce very badly if there is contention.
1636 * If the page is already locked, we don't need to
1637 * handle it now - vmscan will handle it later if and
1638 * when it attempts to reclaim the page.
1640 if (page->mapping && trylock_page(page)) {
1641 lru_add_drain(); /* push cached pages to LRU */
1643 * Because we lock page here, and migration is
1644 * blocked by the pte's page reference, and we
1645 * know the page is still mapped, we don't even
1646 * need to check for file-cache page truncation.
1648 mlock_vma_page(page);
1653 pte_unmap_unlock(ptep, ptl);
1656 return (struct page *)((ulong)page + 1);
1660 pte_unmap_unlock(ptep, ptl);
1661 return ERR_PTR(-EFAULT);
1664 pte_unmap_unlock(ptep, ptl);
1670 * When core dumping an enormous anonymous area that nobody
1671 * has touched so far, we don't want to allocate unnecessary pages or
1672 * page tables. Return error instead of NULL to skip handle_mm_fault,
1673 * then get_dump_page() will return NULL to leave a hole in the dump.
1674 * But we can only make this optimization where a hole would surely
1675 * be zero-filled if handle_mm_fault() actually did handle it.
1677 if ((flags & FOLL_DUMP) &&
1678 (!vma->vm_ops || !vma->vm_ops->fault))
1679 return ERR_PTR(-EFAULT);
1683 static inline int stack_guard_page(struct vm_area_struct *vma, unsigned long addr)
1685 return stack_guard_page_start(vma, addr) ||
1686 stack_guard_page_end(vma, addr+PAGE_SIZE);
1690 * replace_cma_page() - migrate page out of CMA page blocks
1691 * @page: source page to be migrated
1693 * Returns either the old page (if migration was not possible) or the pointer
1694 * to the newly allocated page (with additional reference taken).
1696 * get_user_pages() might take a reference to a page for a long period of time,
1697 * what prevent such page from migration. This is fatal to the preffered usage
1698 * pattern of CMA pageblocks. This function replaces the given user page with
1699 * a new one allocated from NON-MOVABLE pageblock, so locking CMA page can be
1702 static inline struct page *migrate_replace_cma_page(struct page *page)
1704 struct page *newpage = alloc_page(GFP_HIGHUSER);
1710 * Take additional reference to the new page to ensure it won't get
1711 * freed after migration procedure end.
1713 get_page_foll(newpage);
1715 if (migrate_replace_page(page, newpage) == 0) {
1721 __free_page(newpage);
1724 * Migration errors in case of get_user_pages() might not
1725 * be fatal to CMA itself, so better don't fail here.
1731 * __get_user_pages() - pin user pages in memory
1732 * @tsk: task_struct of target task
1733 * @mm: mm_struct of target mm
1734 * @start: starting user address
1735 * @nr_pages: number of pages from start to pin
1736 * @gup_flags: flags modifying pin behaviour
1737 * @pages: array that receives pointers to the pages pinned.
1738 * Should be at least nr_pages long. Or NULL, if caller
1739 * only intends to ensure the pages are faulted in.
1740 * @vmas: array of pointers to vmas corresponding to each page.
1741 * Or NULL if the caller does not require them.
1742 * @nonblocking: whether waiting for disk IO or mmap_sem contention
1744 * Returns number of pages pinned. This may be fewer than the number
1745 * requested. If nr_pages is 0 or negative, returns 0. If no pages
1746 * were pinned, returns -errno. Each page returned must be released
1747 * with a put_page() call when it is finished with. vmas will only
1748 * remain valid while mmap_sem is held.
1750 * Must be called with mmap_sem held for read or write.
1752 * __get_user_pages walks a process's page tables and takes a reference to
1753 * each struct page that each user address corresponds to at a given
1754 * instant. That is, it takes the page that would be accessed if a user
1755 * thread accesses the given user virtual address at that instant.
1757 * This does not guarantee that the page exists in the user mappings when
1758 * __get_user_pages returns, and there may even be a completely different
1759 * page there in some cases (eg. if mmapped pagecache has been invalidated
1760 * and subsequently re faulted). However it does guarantee that the page
1761 * won't be freed completely. And mostly callers simply care that the page
1762 * contains data that was valid *at some point in time*. Typically, an IO
1763 * or similar operation cannot guarantee anything stronger anyway because
1764 * locks can't be held over the syscall boundary.
1766 * If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
1767 * the page is written to, set_page_dirty (or set_page_dirty_lock, as
1768 * appropriate) must be called after the page is finished with, and
1769 * before put_page is called.
1771 * If @nonblocking != NULL, __get_user_pages will not wait for disk IO
1772 * or mmap_sem contention, and if waiting is needed to pin all pages,
1773 * *@nonblocking will be set to 0.
1775 * In most cases, get_user_pages or get_user_pages_fast should be used
1776 * instead of __get_user_pages. __get_user_pages should be used only if
1777 * you need some special @gup_flags.
1779 long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
1780 unsigned long start, unsigned long nr_pages,
1781 unsigned int gup_flags, struct page **pages,
1782 struct vm_area_struct **vmas, int *nonblocking)
1785 unsigned long vm_flags;
1786 unsigned int page_mask;
1791 VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
1794 * Require read or write permissions.
1795 * If FOLL_FORCE is set, we only require the "MAY" flags.
1797 vm_flags = (gup_flags & FOLL_WRITE) ?
1798 (VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
1799 vm_flags &= (gup_flags & FOLL_FORCE) ?
1800 (VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
1803 * If FOLL_FORCE and FOLL_NUMA are both set, handle_mm_fault
1804 * would be called on PROT_NONE ranges. We must never invoke
1805 * handle_mm_fault on PROT_NONE ranges or the NUMA hinting
1806 * page faults would unprotect the PROT_NONE ranges if
1807 * _PAGE_NUMA and _PAGE_PROTNONE are sharing the same pte/pmd
1808 * bitflag. So to avoid that, don't set FOLL_NUMA if
1809 * FOLL_FORCE is set.
1811 if (!(gup_flags & FOLL_FORCE))
1812 gup_flags |= FOLL_NUMA;
1817 struct vm_area_struct *vma;
1819 vma = find_extend_vma(mm, start);
1820 if (!vma && in_gate_area(mm, start)) {
1821 unsigned long pg = start & PAGE_MASK;
1827 /* user gate pages are read-only */
1828 if (gup_flags & FOLL_WRITE)
1829 return i ? : -EFAULT;
1831 pgd = pgd_offset_k(pg);
1833 pgd = pgd_offset_gate(mm, pg);
1834 BUG_ON(pgd_none(*pgd));
1835 pud = pud_offset(pgd, pg);
1836 BUG_ON(pud_none(*pud));
1837 pmd = pmd_offset(pud, pg);
1839 return i ? : -EFAULT;
1840 VM_BUG_ON(pmd_trans_huge(*pmd));
1841 pte = pte_offset_map(pmd, pg);
1842 if (pte_none(*pte)) {
1844 return i ? : -EFAULT;
1846 vma = get_gate_vma(mm);
1850 page = vm_normal_page(vma, start, *pte);
1852 if (!(gup_flags & FOLL_DUMP) &&
1853 is_zero_pfn(pte_pfn(*pte)))
1854 page = pte_page(*pte);
1857 return i ? : -EFAULT;
1869 (vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
1870 !(vm_flags & vma->vm_flags))
1871 return i ? : -EFAULT;
1873 if (is_vm_hugetlb_page(vma)) {
1874 i = follow_hugetlb_page(mm, vma, pages, vmas,
1875 &start, &nr_pages, i, gup_flags);
1881 unsigned int foll_flags = gup_flags;
1882 unsigned int page_increm;
1883 static DEFINE_MUTEX(s_follow_page_lock);
1887 * If we have a pending SIGKILL, don't keep faulting
1888 * pages and potentially allocating memory.
1890 if (unlikely(fatal_signal_pending(current)))
1891 return i ? i : -ERESTARTSYS;
1894 while (!(page = follow_page_mask(vma, start,
1895 foll_flags | FOLL_CMA, &page_mask))) {
1897 unsigned int fault_flags = 0;
1899 fault_flags = FAULT_FLAG_NO_CMA;
1901 /* For mlock, just skip the stack guard page. */
1902 if (foll_flags & FOLL_MLOCK) {
1903 if (stack_guard_page(vma, start))
1906 if (foll_flags & FOLL_WRITE)
1907 fault_flags |= FAULT_FLAG_WRITE;
1909 fault_flags |= FAULT_FLAG_ALLOW_RETRY;
1910 if (foll_flags & FOLL_NOWAIT)
1911 fault_flags |= (FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT);
1913 ret = handle_mm_fault(mm, vma, start,
1916 if (ret & VM_FAULT_ERROR) {
1917 if (ret & VM_FAULT_OOM)
1918 return i ? i : -ENOMEM;
1919 if (ret & (VM_FAULT_HWPOISON |
1920 VM_FAULT_HWPOISON_LARGE)) {
1923 else if (gup_flags & FOLL_HWPOISON)
1928 if (ret & (VM_FAULT_SIGBUS |
1930 return i ? i : -EFAULT;
1935 if (ret & VM_FAULT_MAJOR)
1941 if (ret & VM_FAULT_RETRY) {
1948 * The VM_FAULT_WRITE bit tells us that
1949 * do_wp_page has broken COW when necessary,
1950 * even if maybe_mkwrite decided not to set
1951 * pte_write. We can thus safely do subsequent
1952 * page lookups as if they were reads. But only
1953 * do so when looping for pte_write is futile:
1954 * in some cases userspace may also be wanting
1955 * to write to the gotten user page, which a
1956 * read fault here might prevent (a readonly
1957 * page might get reCOWed by userspace write).
1959 if ((ret & VM_FAULT_WRITE) &&
1960 !(vma->vm_flags & VM_WRITE))
1961 foll_flags |= FOLL_COW;
1966 return i ? i : PTR_ERR(page);
1968 /* Page would have lsb set when CMA page need replacement. */
1969 if (((ulong)page & 0x1) == 0x1) {
1970 struct page *old_page;
1971 unsigned int fault_flags = 0;
1973 mutex_lock(&s_follow_page_lock);
1974 page = (struct page *)((ulong)page & ~0x1);
1976 wait_on_page_locked_timeout(page);
1977 page = migrate_replace_cma_page(page);
1978 /* migration might be successful. vma mapping
1979 * might have changed if there had been a write
1980 * fault from other accesses before migration
1981 * code locked the page. Follow the page again
1982 * to get the latest mapping. If migration was
1983 * successful, follow again would get
1984 * non-CMA page. If there had been a write
1985 * page fault, follow page and CMA page
1986 * replacement(if necessary) would restart with
1989 if (page == old_page)
1990 wait_on_page_locked_timeout(page);
1991 if (foll_flags & FOLL_WRITE) {
1992 /* page would be marked as old during
1993 * migration. To make it young, call
1995 * This to avoid the sanity check
1996 * failures in the calling code, which
1997 * check for pte write permission
2000 fault_flags |= FAULT_FLAG_WRITE;
2001 handle_mm_fault(mm, vma,
2002 start, fault_flags);
2004 foll_flags = gup_flags;
2005 mutex_unlock(&s_follow_page_lock);
2006 goto follow_page_again;
2009 BUG_ON(dma_contiguous_should_replace_page(page) &&
2010 (foll_flags & FOLL_GET));
2015 flush_anon_page(vma, page, start);
2016 flush_dcache_page(page);
2024 page_increm = 1 + (~(start >> PAGE_SHIFT) & page_mask);
2025 if (page_increm > nr_pages)
2026 page_increm = nr_pages;
2028 start += page_increm * PAGE_SIZE;
2029 nr_pages -= page_increm;
2030 } while (nr_pages && start < vma->vm_end);
2034 EXPORT_SYMBOL(__get_user_pages);
2037 * fixup_user_fault() - manually resolve a user page fault
2038 * @tsk: the task_struct to use for page fault accounting, or
2039 * NULL if faults are not to be recorded.
2040 * @mm: mm_struct of target mm
2041 * @address: user address
2042 * @fault_flags:flags to pass down to handle_mm_fault()
2044 * This is meant to be called in the specific scenario where for locking reasons
2045 * we try to access user memory in atomic context (within a pagefault_disable()
2046 * section), this returns -EFAULT, and we want to resolve the user fault before
2049 * Typically this is meant to be used by the futex code.
2051 * The main difference with get_user_pages() is that this function will
2052 * unconditionally call handle_mm_fault() which will in turn perform all the
2053 * necessary SW fixup of the dirty and young bits in the PTE, while
2054 * handle_mm_fault() only guarantees to update these in the struct page.
2056 * This is important for some architectures where those bits also gate the
2057 * access permission to the page because they are maintained in software. On
2058 * such architectures, gup() will not be enough to make a subsequent access
2061 * This should be called with the mm_sem held for read.
2063 int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
2064 unsigned long address, unsigned int fault_flags)
2066 struct vm_area_struct *vma;
2067 vm_flags_t vm_flags;
2070 vma = find_extend_vma(mm, address);
2071 if (!vma || address < vma->vm_start)
2074 vm_flags = (fault_flags & FAULT_FLAG_WRITE) ? VM_WRITE : VM_READ;
2075 if (!(vm_flags & vma->vm_flags))
2078 ret = handle_mm_fault(mm, vma, address, fault_flags);
2079 if (ret & VM_FAULT_ERROR) {
2080 if (ret & VM_FAULT_OOM)
2082 if (ret & (VM_FAULT_HWPOISON | VM_FAULT_HWPOISON_LARGE))
2084 if (ret & (VM_FAULT_SIGBUS | VM_FAULT_SIGSEGV))
2089 if (ret & VM_FAULT_MAJOR)
2098 * get_dump_page() - pin user page in memory while writing it to core dump
2099 * @addr: user address
2101 * Returns struct page pointer of user page pinned for dump,
2102 * to be freed afterwards by page_cache_release() or put_page().
2104 * Returns NULL on any kind of failure - a hole must then be inserted into
2105 * the corefile, to preserve alignment with its headers; and also returns
2106 * NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
2107 * allowing a hole to be left in the corefile to save diskspace.
2109 * Called without mmap_sem, but after all other threads have been killed.
2111 #ifdef CONFIG_ELF_CORE
2112 struct page *get_dump_page(unsigned long addr)
2114 struct vm_area_struct *vma;
2117 if (__get_user_pages(current, current->mm, addr, 1,
2118 FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
2121 flush_cache_page(vma, addr, page_to_pfn(page));
2124 #endif /* CONFIG_ELF_CORE */
2126 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
2129 pgd_t * pgd = pgd_offset(mm, addr);
2130 pud_t * pud = pud_alloc(mm, pgd, addr);
2132 pmd_t * pmd = pmd_alloc(mm, pud, addr);
2134 VM_BUG_ON(pmd_trans_huge(*pmd));
2135 return pte_alloc_map_lock(mm, pmd, addr, ptl);
2142 * This is the old fallback for page remapping.
2144 * For historical reasons, it only allows reserved pages. Only
2145 * old drivers should use this, and they needed to mark their
2146 * pages reserved for the old functions anyway.
2148 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
2149 struct page *page, pgprot_t prot)
2151 struct mm_struct *mm = vma->vm_mm;
2160 flush_dcache_page(page);
2161 pte = get_locked_pte(mm, addr, &ptl);
2165 if (!pte_none(*pte))
2168 /* Ok, finally just insert the thing.. */
2170 inc_mm_counter_fast(mm, MM_FILEPAGES);
2171 page_add_file_rmap(page);
2172 set_pte_at(mm, addr, pte, mk_pte(page, prot));
2175 pte_unmap_unlock(pte, ptl);
2178 pte_unmap_unlock(pte, ptl);
2184 * vm_insert_page - insert single page into user vma
2185 * @vma: user vma to map to
2186 * @addr: target user address of this page
2187 * @page: source kernel page
2189 * This allows drivers to insert individual pages they've allocated
2192 * The page has to be a nice clean _individual_ kernel allocation.
2193 * If you allocate a compound page, you need to have marked it as
2194 * such (__GFP_COMP), or manually just split the page up yourself
2195 * (see split_page()).
2197 * NOTE! Traditionally this was done with "remap_pfn_range()" which
2198 * took an arbitrary page protection parameter. This doesn't allow
2199 * that. Your vma protection will have to be set up correctly, which
2200 * means that if you want a shared writable mapping, you'd better
2201 * ask for a shared writable mapping!
2203 * The page does not need to be reserved.
2205 * Usually this function is called from f_op->mmap() handler
2206 * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
2207 * Caller must set VM_MIXEDMAP on vma if it wants to call this
2208 * function from other places, for example from page-fault handler.
2210 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
2213 if (addr < vma->vm_start || addr >= vma->vm_end)
2215 if (!page_count(page))
2217 if (!(vma->vm_flags & VM_MIXEDMAP)) {
2218 BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
2219 BUG_ON(vma->vm_flags & VM_PFNMAP);
2220 vma->vm_flags |= VM_MIXEDMAP;
2222 return insert_page(vma, addr, page, vma->vm_page_prot);
2224 EXPORT_SYMBOL(vm_insert_page);
2226 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2227 unsigned long pfn, pgprot_t prot)
2229 struct mm_struct *mm = vma->vm_mm;
2235 pte = get_locked_pte(mm, addr, &ptl);
2239 if (!pte_none(*pte))
2242 /* Ok, finally just insert the thing.. */
2243 entry = pte_mkspecial(pfn_pte(pfn, prot));
2244 set_pte_at(mm, addr, pte, entry);
2245 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2249 pte_unmap_unlock(pte, ptl);
2255 * vm_insert_pfn - insert single pfn into user vma
2256 * @vma: user vma to map to
2257 * @addr: target user address of this page
2258 * @pfn: source kernel pfn
2260 * Similar to vm_insert_page, this allows drivers to insert individual pages
2261 * they've allocated into a user vma. Same comments apply.
2263 * This function should only be called from a vm_ops->fault handler, and
2264 * in that case the handler should return NULL.
2266 * vma cannot be a COW mapping.
2268 * As this is called only for pages that do not currently exist, we
2269 * do not need to flush old virtual caches or the TLB.
2271 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2275 pgprot_t pgprot = vma->vm_page_prot;
2277 * Technically, architectures with pte_special can avoid all these
2278 * restrictions (same for remap_pfn_range). However we would like
2279 * consistency in testing and feature parity among all, so we should
2280 * try to keep these invariants in place for everybody.
2282 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2283 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2284 (VM_PFNMAP|VM_MIXEDMAP));
2285 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2286 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2288 if (addr < vma->vm_start || addr >= vma->vm_end)
2290 if (track_pfn_insert(vma, &pgprot, pfn))
2293 ret = insert_pfn(vma, addr, pfn, pgprot);
2297 EXPORT_SYMBOL(vm_insert_pfn);
2299 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2302 BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
2304 if (addr < vma->vm_start || addr >= vma->vm_end)
2308 * If we don't have pte special, then we have to use the pfn_valid()
2309 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2310 * refcount the page if pfn_valid is true (hence insert_page rather
2311 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
2312 * without pte special, it would there be refcounted as a normal page.
2314 if (!HAVE_PTE_SPECIAL && pfn_valid(pfn)) {
2317 page = pfn_to_page(pfn);
2318 return insert_page(vma, addr, page, vma->vm_page_prot);
2320 return insert_pfn(vma, addr, pfn, vma->vm_page_prot);
2322 EXPORT_SYMBOL(vm_insert_mixed);
2325 * maps a range of physical memory into the requested pages. the old
2326 * mappings are removed. any references to nonexistent pages results
2327 * in null mappings (currently treated as "copy-on-access")
2329 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2330 unsigned long addr, unsigned long end,
2331 unsigned long pfn, pgprot_t prot)
2336 pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2339 arch_enter_lazy_mmu_mode();
2341 BUG_ON(!pte_none(*pte));
2342 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2344 } while (pte++, addr += PAGE_SIZE, addr != end);
2345 arch_leave_lazy_mmu_mode();
2346 pte_unmap_unlock(pte - 1, ptl);
2350 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2351 unsigned long addr, unsigned long end,
2352 unsigned long pfn, pgprot_t prot)
2357 pfn -= addr >> PAGE_SHIFT;
2358 pmd = pmd_alloc(mm, pud, addr);
2361 VM_BUG_ON(pmd_trans_huge(*pmd));
2363 next = pmd_addr_end(addr, end);
2364 if (remap_pte_range(mm, pmd, addr, next,
2365 pfn + (addr >> PAGE_SHIFT), prot))
2367 } while (pmd++, addr = next, addr != end);
2371 static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd,
2372 unsigned long addr, unsigned long end,
2373 unsigned long pfn, pgprot_t prot)
2378 pfn -= addr >> PAGE_SHIFT;
2379 pud = pud_alloc(mm, pgd, addr);
2383 next = pud_addr_end(addr, end);
2384 if (remap_pmd_range(mm, pud, addr, next,
2385 pfn + (addr >> PAGE_SHIFT), prot))
2387 } while (pud++, addr = next, addr != end);
2392 * remap_pfn_range - remap kernel memory to userspace
2393 * @vma: user vma to map to
2394 * @addr: target user address to start at
2395 * @pfn: physical address of kernel memory
2396 * @size: size of map area
2397 * @prot: page protection flags for this mapping
2399 * Note: this is only safe if the mm semaphore is held when called.
2401 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2402 unsigned long pfn, unsigned long size, pgprot_t prot)
2406 unsigned long end = addr + PAGE_ALIGN(size);
2407 struct mm_struct *mm = vma->vm_mm;
2411 * Physically remapped pages are special. Tell the
2412 * rest of the world about it:
2413 * VM_IO tells people not to look at these pages
2414 * (accesses can have side effects).
2415 * VM_PFNMAP tells the core MM that the base pages are just
2416 * raw PFN mappings, and do not have a "struct page" associated
2419 * Disable vma merging and expanding with mremap().
2421 * Omit vma from core dump, even when VM_IO turned off.
2423 * There's a horrible special case to handle copy-on-write
2424 * behaviour that some programs depend on. We mark the "original"
2425 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2426 * See vm_normal_page() for details.
2428 if (is_cow_mapping(vma->vm_flags)) {
2429 if (addr != vma->vm_start || end != vma->vm_end)
2431 vma->vm_pgoff = pfn;
2434 err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2438 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2440 BUG_ON(addr >= end);
2441 pfn -= addr >> PAGE_SHIFT;
2442 pgd = pgd_offset(mm, addr);
2443 flush_cache_range(vma, addr, end);
2445 next = pgd_addr_end(addr, end);
2446 err = remap_pud_range(mm, pgd, addr, next,
2447 pfn + (addr >> PAGE_SHIFT), prot);
2450 } while (pgd++, addr = next, addr != end);
2453 untrack_pfn(vma, pfn, PAGE_ALIGN(size));
2457 EXPORT_SYMBOL(remap_pfn_range);
2460 * vm_iomap_memory - remap memory to userspace
2461 * @vma: user vma to map to
2462 * @start: start of area
2463 * @len: size of area
2465 * This is a simplified io_remap_pfn_range() for common driver use. The
2466 * driver just needs to give us the physical memory range to be mapped,
2467 * we'll figure out the rest from the vma information.
2469 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2470 * whatever write-combining details or similar.
2472 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2474 unsigned long vm_len, pfn, pages;
2476 /* Check that the physical memory area passed in looks valid */
2477 if (start + len < start)
2480 * You *really* shouldn't map things that aren't page-aligned,
2481 * but we've historically allowed it because IO memory might
2482 * just have smaller alignment.
2484 len += start & ~PAGE_MASK;
2485 pfn = start >> PAGE_SHIFT;
2486 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2487 if (pfn + pages < pfn)
2490 /* We start the mapping 'vm_pgoff' pages into the area */
2491 if (vma->vm_pgoff > pages)
2493 pfn += vma->vm_pgoff;
2494 pages -= vma->vm_pgoff;
2496 /* Can we fit all of the mapping? */
2497 vm_len = vma->vm_end - vma->vm_start;
2498 if (vm_len >> PAGE_SHIFT > pages)
2501 /* Ok, let it rip */
2502 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2504 EXPORT_SYMBOL(vm_iomap_memory);
2506 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2507 unsigned long addr, unsigned long end,
2508 pte_fn_t fn, void *data)
2513 spinlock_t *uninitialized_var(ptl);
2515 pte = (mm == &init_mm) ?
2516 pte_alloc_kernel(pmd, addr) :
2517 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2521 BUG_ON(pmd_huge(*pmd));
2523 arch_enter_lazy_mmu_mode();
2525 token = pmd_pgtable(*pmd);
2528 err = fn(pte++, token, addr, data);
2531 } while (addr += PAGE_SIZE, addr != end);
2533 arch_leave_lazy_mmu_mode();
2536 pte_unmap_unlock(pte-1, ptl);
2540 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2541 unsigned long addr, unsigned long end,
2542 pte_fn_t fn, void *data)
2548 BUG_ON(pud_huge(*pud));
2550 pmd = pmd_alloc(mm, pud, addr);
2554 next = pmd_addr_end(addr, end);
2555 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
2558 } while (pmd++, addr = next, addr != end);
2562 static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd,
2563 unsigned long addr, unsigned long end,
2564 pte_fn_t fn, void *data)
2570 pud = pud_alloc(mm, pgd, addr);
2574 next = pud_addr_end(addr, end);
2575 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
2578 } while (pud++, addr = next, addr != end);
2583 * Scan a region of virtual memory, filling in page tables as necessary
2584 * and calling a provided function on each leaf page table.
2586 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2587 unsigned long size, pte_fn_t fn, void *data)
2591 unsigned long end = addr + size;
2594 BUG_ON(addr >= end);
2595 pgd = pgd_offset(mm, addr);
2597 next = pgd_addr_end(addr, end);
2598 err = apply_to_pud_range(mm, pgd, addr, next, fn, data);
2601 } while (pgd++, addr = next, addr != end);
2605 EXPORT_SYMBOL_GPL(apply_to_page_range);
2608 * handle_pte_fault chooses page fault handler according to an entry
2609 * which was read non-atomically. Before making any commitment, on
2610 * those architectures or configurations (e.g. i386 with PAE) which
2611 * might give a mix of unmatched parts, do_swap_page and do_nonlinear_fault
2612 * must check under lock before unmapping the pte and proceeding
2613 * (but do_wp_page is only called after already making such a check;
2614 * and do_anonymous_page can safely check later on).
2616 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2617 pte_t *page_table, pte_t orig_pte)
2620 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
2621 if (sizeof(pte_t) > sizeof(unsigned long)) {
2622 spinlock_t *ptl = pte_lockptr(mm, pmd);
2624 same = pte_same(*page_table, orig_pte);
2628 pte_unmap(page_table);
2632 static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
2635 * If the source page was a PFN mapping, we don't have
2636 * a "struct page" for it. We do a best-effort copy by
2637 * just copying from the original user address. If that
2638 * fails, we just zero-fill it. Live with it.
2640 if (unlikely(!src)) {
2641 void *kaddr = kmap_atomic(dst);
2642 void __user *uaddr = (void __user *)(va & PAGE_MASK);
2645 * This really shouldn't fail, because the page is there
2646 * in the page tables. But it might just be unreadable,
2647 * in which case we just give up and fill the result with
2650 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
2652 kunmap_atomic(kaddr);
2653 flush_dcache_page(dst);
2655 copy_user_highpage(dst, src, va, vma);
2659 * This routine handles present pages, when users try to write
2660 * to a shared page. It is done by copying the page to a new address
2661 * and decrementing the shared-page counter for the old page.
2663 * Note that this routine assumes that the protection checks have been
2664 * done by the caller (the low-level page fault routine in most cases).
2665 * Thus we can safely just mark it writable once we've done any necessary
2668 * We also mark the page dirty at this point even though the page will
2669 * change only once the write actually happens. This avoids a few races,
2670 * and potentially makes it more efficient.
2672 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2673 * but allow concurrent faults), with pte both mapped and locked.
2674 * We return with mmap_sem still held, but pte unmapped and unlocked.
2676 static int do_wp_page(struct mm_struct *mm, struct vm_area_struct *vma,
2677 unsigned long address, pte_t *page_table, pmd_t *pmd,
2678 spinlock_t *ptl, pte_t orig_pte, unsigned int flags)
2681 struct page *old_page, *new_page = NULL;
2684 int page_mkwrite = 0;
2685 struct page *dirty_page = NULL;
2686 unsigned long mmun_start = 0; /* For mmu_notifiers */
2687 unsigned long mmun_end = 0; /* For mmu_notifiers */
2688 gfp_t gfp = GFP_HIGHUSER_MOVABLE;
2690 if (IS_ENABLED(CONFIG_CMA) && (flags & FAULT_FLAG_NO_CMA))
2691 gfp &= ~__GFP_MOVABLE;
2693 old_page = vm_normal_page(vma, address, orig_pte);
2696 * VM_MIXEDMAP !pfn_valid() case
2698 * We should not cow pages in a shared writeable mapping.
2699 * Just mark the pages writable as we can't do any dirty
2700 * accounting on raw pfn maps.
2702 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2703 (VM_WRITE|VM_SHARED))
2709 * Take out anonymous pages first, anonymous shared vmas are
2710 * not dirty accountable.
2712 if (PageAnon(old_page) && !PageKsm(old_page)) {
2713 if (!trylock_page(old_page)) {
2714 page_cache_get(old_page);
2715 pte_unmap_unlock(page_table, ptl);
2716 lock_page(old_page);
2717 page_table = pte_offset_map_lock(mm, pmd, address,
2719 if (!pte_same(*page_table, orig_pte)) {
2720 unlock_page(old_page);
2723 page_cache_release(old_page);
2725 if (reuse_swap_page(old_page)) {
2727 * The page is all ours. Move it to our anon_vma so
2728 * the rmap code will not search our parent or siblings.
2729 * Protected against the rmap code by the page lock.
2731 page_move_anon_rmap(old_page, vma, address);
2732 unlock_page(old_page);
2735 unlock_page(old_page);
2736 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2737 (VM_WRITE|VM_SHARED))) {
2739 * Only catch write-faults on shared writable pages,
2740 * read-only shared pages can get COWed by
2741 * get_user_pages(.write=1, .force=1).
2743 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2744 struct vm_fault vmf;
2747 vmf.virtual_address = (void __user *)(address &
2749 vmf.pgoff = old_page->index;
2750 vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2751 vmf.page = old_page;
2754 * Notify the address space that the page is about to
2755 * become writable so that it can prohibit this or wait
2756 * for the page to get into an appropriate state.
2758 * We do this without the lock held, so that it can
2759 * sleep if it needs to.
2761 page_cache_get(old_page);
2762 pte_unmap_unlock(page_table, ptl);
2764 tmp = vma->vm_ops->page_mkwrite(vma, &vmf);
2766 (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2768 goto unwritable_page;
2770 if (unlikely(!(tmp & VM_FAULT_LOCKED))) {
2771 lock_page(old_page);
2772 if (!old_page->mapping) {
2773 ret = 0; /* retry the fault */
2774 unlock_page(old_page);
2775 goto unwritable_page;
2778 VM_BUG_ON(!PageLocked(old_page));
2781 * Since we dropped the lock we need to revalidate
2782 * the PTE as someone else may have changed it. If
2783 * they did, we just return, as we can count on the
2784 * MMU to tell us if they didn't also make it writable.
2786 page_table = pte_offset_map_lock(mm, pmd, address,
2788 if (!pte_same(*page_table, orig_pte)) {
2789 unlock_page(old_page);
2795 dirty_page = old_page;
2796 get_page(dirty_page);
2799 flush_cache_page(vma, address, pte_pfn(orig_pte));
2800 entry = pte_mkyoung(orig_pte);
2801 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2802 if (ptep_set_access_flags(vma, address, page_table, entry,1))
2803 update_mmu_cache(vma, address, page_table);
2804 pte_unmap_unlock(page_table, ptl);
2805 ret |= VM_FAULT_WRITE;
2811 * Yes, Virginia, this is actually required to prevent a race
2812 * with clear_page_dirty_for_io() from clearing the page dirty
2813 * bit after it clear all dirty ptes, but before a racing
2814 * do_wp_page installs a dirty pte.
2816 * __do_fault is protected similarly.
2818 if (!page_mkwrite) {
2819 wait_on_page_locked(dirty_page);
2820 set_page_dirty_balance(dirty_page, page_mkwrite);
2821 /* file_update_time outside page_lock */
2823 file_update_time(vma->vm_file);
2825 put_page(dirty_page);
2827 struct address_space *mapping = dirty_page->mapping;
2829 set_page_dirty(dirty_page);
2830 unlock_page(dirty_page);
2831 page_cache_release(dirty_page);
2834 * Some device drivers do not set page.mapping
2835 * but still dirty their pages
2837 balance_dirty_pages_ratelimited(mapping);
2845 * Ok, we need to copy. Oh, well..
2847 page_cache_get(old_page);
2849 pte_unmap_unlock(page_table, ptl);
2851 if (unlikely(anon_vma_prepare(vma)))
2854 if (is_zero_pfn(pte_pfn(orig_pte))) {
2855 new_page = alloc_zeroed_user_highpage(gfp, vma, address);
2859 new_page = alloc_page_vma(gfp, vma, address);
2862 cow_user_page(new_page, old_page, address, vma);
2864 __SetPageUptodate(new_page);
2866 if (mem_cgroup_newpage_charge(new_page, mm, GFP_KERNEL))
2869 mmun_start = address & PAGE_MASK;
2870 mmun_end = mmun_start + PAGE_SIZE;
2871 mmu_notifier_invalidate_range_start(vma, mmun_start,
2872 mmun_end, MMU_MIGRATE);
2875 * Re-check the pte - we dropped the lock
2877 page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
2878 if (likely(pte_same(*page_table, orig_pte))) {
2880 if (!PageAnon(old_page)) {
2881 dec_mm_counter_fast(mm, MM_FILEPAGES);
2882 inc_mm_counter_fast(mm, MM_ANONPAGES);
2885 inc_mm_counter_fast(mm, MM_ANONPAGES);
2886 flush_cache_page(vma, address, pte_pfn(orig_pte));
2887 entry = mk_pte(new_page, vma->vm_page_prot);
2888 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2890 * Clear the pte entry and flush it first, before updating the
2891 * pte with the new entry. This will avoid a race condition
2892 * seen in the presence of one thread doing SMC and another
2895 ptep_clear_flush_notify(vma, address, page_table);
2896 page_add_new_anon_rmap(new_page, vma, address);
2898 * We call the notify macro here because, when using secondary
2899 * mmu page tables (such as kvm shadow page tables), we want the
2900 * new page to be mapped directly into the secondary page table.
2902 set_pte_at_notify(mm, address, page_table, entry, MMU_MIGRATE);
2903 update_mmu_cache(vma, address, page_table);
2906 * Only after switching the pte to the new page may
2907 * we remove the mapcount here. Otherwise another
2908 * process may come and find the rmap count decremented
2909 * before the pte is switched to the new page, and
2910 * "reuse" the old page writing into it while our pte
2911 * here still points into it and can be read by other
2914 * The critical issue is to order this
2915 * page_remove_rmap with the ptp_clear_flush above.
2916 * Those stores are ordered by (if nothing else,)
2917 * the barrier present in the atomic_add_negative
2918 * in page_remove_rmap.
2920 * Then the TLB flush in ptep_clear_flush ensures that
2921 * no process can access the old page before the
2922 * decremented mapcount is visible. And the old page
2923 * cannot be reused until after the decremented
2924 * mapcount is visible. So transitively, TLBs to
2925 * old page will be flushed before it can be reused.
2927 page_remove_rmap(old_page);
2930 /* Free the old page.. */
2931 new_page = old_page;
2932 ret |= VM_FAULT_WRITE;
2934 mem_cgroup_uncharge_page(new_page);
2937 page_cache_release(new_page);
2939 pte_unmap_unlock(page_table, ptl);
2940 if (mmun_end > mmun_start)
2941 mmu_notifier_invalidate_range_end(vma, mmun_start,
2942 mmun_end, MMU_MIGRATE);
2945 * Don't let another task, with possibly unlocked vma,
2946 * keep the mlocked page.
2948 if ((ret & VM_FAULT_WRITE) && (vma->vm_flags & VM_LOCKED)) {
2949 lock_page(old_page); /* LRU manipulation */
2950 munlock_vma_page(old_page);
2951 unlock_page(old_page);
2953 page_cache_release(old_page);
2957 page_cache_release(new_page);
2960 page_cache_release(old_page);
2961 return VM_FAULT_OOM;
2964 page_cache_release(old_page);
2968 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2969 unsigned long start_addr, unsigned long end_addr,
2970 struct zap_details *details)
2972 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2975 static inline void unmap_mapping_range_tree(struct rb_root *root,
2976 struct zap_details *details)
2978 struct vm_area_struct *vma;
2979 pgoff_t vba, vea, zba, zea;
2981 vma_interval_tree_foreach(vma, root,
2982 details->first_index, details->last_index) {
2984 vba = vma->vm_pgoff;
2985 vea = vba + ((vma->vm_end - vma->vm_start) >> PAGE_SHIFT) - 1;
2986 /* Assume for now that PAGE_CACHE_SHIFT == PAGE_SHIFT */
2987 zba = details->first_index;
2990 zea = details->last_index;
2994 unmap_mapping_range_vma(vma,
2995 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2996 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3001 static inline void unmap_mapping_range_list(struct list_head *head,
3002 struct zap_details *details)
3004 struct vm_area_struct *vma;
3007 * In nonlinear VMAs there is no correspondence between virtual address
3008 * offset and file offset. So we must perform an exhaustive search
3009 * across *all* the pages in each nonlinear VMA, not just the pages
3010 * whose virtual address lies outside the file truncation point.
3012 list_for_each_entry(vma, head, shared.nonlinear) {
3013 details->nonlinear_vma = vma;
3014 unmap_mapping_range_vma(vma, vma->vm_start, vma->vm_end, details);
3019 * unmap_mapping_range - unmap the portion of all mmaps in the specified address_space corresponding to the specified page range in the underlying file.
3020 * @mapping: the address space containing mmaps to be unmapped.
3021 * @holebegin: byte in first page to unmap, relative to the start of
3022 * the underlying file. This will be rounded down to a PAGE_SIZE
3023 * boundary. Note that this is different from truncate_pagecache(), which
3024 * must keep the partial page. In contrast, we must get rid of
3026 * @holelen: size of prospective hole in bytes. This will be rounded
3027 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
3029 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3030 * but 0 when invalidating pagecache, don't throw away private data.
3032 void unmap_mapping_range(struct address_space *mapping,
3033 loff_t const holebegin, loff_t const holelen, int even_cows)
3035 struct zap_details details;
3036 pgoff_t hba = holebegin >> PAGE_SHIFT;
3037 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3039 /* Check for overflow. */
3040 if (sizeof(holelen) > sizeof(hlen)) {
3042 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3043 if (holeend & ~(long long)ULONG_MAX)
3044 hlen = ULONG_MAX - hba + 1;
3047 details.check_mapping = even_cows? NULL: mapping;
3048 details.nonlinear_vma = NULL;
3049 details.first_index = hba;
3050 details.last_index = hba + hlen - 1;
3051 if (details.last_index < details.first_index)
3052 details.last_index = ULONG_MAX;
3055 mutex_lock(&mapping->i_mmap_mutex);
3056 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap)))
3057 unmap_mapping_range_tree(&mapping->i_mmap, &details);
3058 if (unlikely(!list_empty(&mapping->i_mmap_nonlinear)))
3059 unmap_mapping_range_list(&mapping->i_mmap_nonlinear, &details);
3060 mutex_unlock(&mapping->i_mmap_mutex);
3062 EXPORT_SYMBOL(unmap_mapping_range);
3065 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3066 * but allow concurrent faults), and pte mapped but not yet locked.
3067 * We return with mmap_sem still held, but pte unmapped and unlocked.
3069 static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma,
3070 unsigned long address, pte_t *page_table, pmd_t *pmd,
3071 unsigned int flags, pte_t orig_pte)
3074 struct page *page, *swapcache;
3078 struct mem_cgroup *ptr;
3082 if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
3085 entry = pte_to_swp_entry(orig_pte);
3086 if (unlikely(non_swap_entry(entry))) {
3087 if (is_migration_entry(entry)) {
3088 migration_entry_wait(mm, pmd, address);
3089 } else if (is_hwpoison_entry(entry)) {
3090 ret = VM_FAULT_HWPOISON;
3092 print_bad_pte(vma, address, orig_pte, NULL);
3093 ret = VM_FAULT_SIGBUS;
3097 delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3098 page = lookup_swap_cache(entry);
3100 page = swapin_readahead(entry,
3101 GFP_HIGHUSER_MOVABLE, vma, address);
3104 * Back out if somebody else faulted in this pte
3105 * while we released the pte lock.
3107 page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3108 if (likely(pte_same(*page_table, orig_pte)))
3110 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3114 /* Had to read the page from swap area: Major fault */
3115 ret = VM_FAULT_MAJOR;
3116 count_vm_event(PGMAJFAULT);
3117 mem_cgroup_count_vm_event(mm, PGMAJFAULT);
3118 } else if (PageHWPoison(page)) {
3120 * hwpoisoned dirty swapcache pages are kept for killing
3121 * owner processes (which may be unknown at hwpoison time)
3123 ret = VM_FAULT_HWPOISON;
3124 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3130 locked = lock_page_or_retry(page, mm, flags);
3132 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3134 ret |= VM_FAULT_RETRY;
3139 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3140 * release the swapcache from under us. The page pin, and pte_same
3141 * test below, are not enough to exclude that. Even if it is still
3142 * swapcache, we need to check that the page's swap has not changed.
3144 if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
3147 page = ksm_might_need_to_copy(page, vma, address);
3148 if (unlikely(!page)) {
3154 if (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) {
3160 * Back out if somebody else already faulted in this pte.
3162 page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3163 if (unlikely(!pte_same(*page_table, orig_pte)))
3166 if (unlikely(!PageUptodate(page))) {
3167 ret = VM_FAULT_SIGBUS;
3172 * The page isn't present yet, go ahead with the fault.
3174 * Be careful about the sequence of operations here.
3175 * To get its accounting right, reuse_swap_page() must be called
3176 * while the page is counted on swap but not yet in mapcount i.e.
3177 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3178 * must be called after the swap_free(), or it will never succeed.
3179 * Because delete_from_swap_page() may be called by reuse_swap_page(),
3180 * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry
3181 * in page->private. In this case, a record in swap_cgroup is silently
3182 * discarded at swap_free().
3185 inc_mm_counter_fast(mm, MM_ANONPAGES);
3186 dec_mm_counter_fast(mm, MM_SWAPENTS);
3187 pte = mk_pte(page, vma->vm_page_prot);
3188 if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) {
3189 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3190 flags &= ~FAULT_FLAG_WRITE;
3191 ret |= VM_FAULT_WRITE;
3194 flush_icache_page(vma, page);
3195 set_pte_at(mm, address, page_table, pte);
3196 if (page == swapcache)
3197 do_page_add_anon_rmap(page, vma, address, exclusive);
3198 else /* ksm created a completely new copy */
3199 page_add_new_anon_rmap(page, vma, address);
3200 /* It's better to call commit-charge after rmap is established */
3201 mem_cgroup_commit_charge_swapin(page, ptr);
3204 if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3205 try_to_free_swap(page);
3207 if (page != swapcache) {
3209 * Hold the lock to avoid the swap entry to be reused
3210 * until we take the PT lock for the pte_same() check
3211 * (to avoid false positives from pte_same). For
3212 * further safety release the lock after the swap_free
3213 * so that the swap count won't change under a
3214 * parallel locked swapcache.
3216 unlock_page(swapcache);
3217 page_cache_release(swapcache);
3220 if (flags & FAULT_FLAG_WRITE) {
3221 ret |= do_wp_page(mm, vma, address, page_table, pmd,
3223 if (ret & VM_FAULT_ERROR)
3224 ret &= VM_FAULT_ERROR;
3228 /* No need to invalidate - it was non-present before */
3229 update_mmu_cache(vma, address, page_table);
3231 pte_unmap_unlock(page_table, ptl);
3235 mem_cgroup_cancel_charge_swapin(ptr);
3236 pte_unmap_unlock(page_table, ptl);
3240 page_cache_release(page);
3241 if (page != swapcache) {
3242 unlock_page(swapcache);
3243 page_cache_release(swapcache);
3249 * This is like a special single-page "expand_{down|up}wards()",
3250 * except we must first make sure that 'address{-|+}PAGE_SIZE'
3251 * doesn't hit another vma.
3253 static inline int check_stack_guard_page(struct vm_area_struct *vma, unsigned long address)
3255 address &= PAGE_MASK;
3256 if ((vma->vm_flags & VM_GROWSDOWN) && address == vma->vm_start) {
3257 struct vm_area_struct *prev = vma->vm_prev;
3260 * Is there a mapping abutting this one below?
3262 * That's only ok if it's the same stack mapping
3263 * that has gotten split..
3265 if (prev && prev->vm_end == address)
3266 return prev->vm_flags & VM_GROWSDOWN ? 0 : -ENOMEM;
3268 return expand_downwards(vma, address - PAGE_SIZE);
3270 if ((vma->vm_flags & VM_GROWSUP) && address + PAGE_SIZE == vma->vm_end) {
3271 struct vm_area_struct *next = vma->vm_next;
3273 /* As VM_GROWSDOWN but s/below/above/ */
3274 if (next && next->vm_start == address + PAGE_SIZE)
3275 return next->vm_flags & VM_GROWSUP ? 0 : -ENOMEM;
3277 return expand_upwards(vma, address + PAGE_SIZE);
3282 bool is_vma_temporary_stack(struct vm_area_struct *vma);
3284 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3285 * but allow concurrent faults), and pte mapped but not yet locked.
3286 * We return with mmap_sem still held, but pte unmapped and unlocked.
3288 static int do_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
3289 unsigned long address, pte_t *page_table, pmd_t *pmd,
3296 pte_unmap(page_table);
3298 /* File mapping without ->vm_ops ? */
3299 if (vma->vm_flags & VM_SHARED)
3300 return VM_FAULT_SIGBUS;
3302 /* Check if we need to add a guard page to the stack */
3303 if (check_stack_guard_page(vma, address) < 0)
3304 return VM_FAULT_SIGSEGV;
3306 /* Use the zero-page for reads */
3307 if (!(flags & FAULT_FLAG_WRITE)) {
3308 entry = pte_mkspecial(pfn_pte(my_zero_pfn(address),
3309 vma->vm_page_prot));
3310 page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3311 if (!pte_none(*page_table))
3316 /* Allocate our own private page. */
3317 if (unlikely(anon_vma_prepare(vma)))
3319 if (vma->vm_flags & VM_LOCKED || flags & FAULT_FLAG_NO_CMA ||
3320 is_vma_temporary_stack(vma)) {
3321 page = alloc_zeroed_user_highpage(GFP_HIGHUSER, vma, address);
3323 page = alloc_zeroed_user_highpage_movable(vma, address);
3328 * The memory barrier inside __SetPageUptodate makes sure that
3329 * preceeding stores to the page contents become visible before
3330 * the set_pte_at() write.
3332 __SetPageUptodate(page);
3334 if (mem_cgroup_newpage_charge(page, mm, GFP_KERNEL))
3337 entry = mk_pte(page, vma->vm_page_prot);
3338 if (vma->vm_flags & VM_WRITE)
3339 entry = pte_mkwrite(pte_mkdirty(entry));
3341 page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3342 if (!pte_none(*page_table))
3345 inc_mm_counter_fast(mm, MM_ANONPAGES);
3346 page_add_new_anon_rmap(page, vma, address);
3348 set_pte_at(mm, address, page_table, entry);
3350 /* No need to invalidate - it was non-present before */
3351 update_mmu_cache(vma, address, page_table);
3353 pte_unmap_unlock(page_table, ptl);
3356 mem_cgroup_uncharge_page(page);
3357 page_cache_release(page);
3360 page_cache_release(page);
3362 return VM_FAULT_OOM;
3365 void do_set_pte(struct vm_area_struct *vma, unsigned long address,
3366 struct page *page, pte_t *pte, bool write, bool anon)
3370 flush_icache_page(vma, page);
3371 entry = mk_pte(page, vma->vm_page_prot);
3373 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3375 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3376 page_add_new_anon_rmap(page, vma, address);
3378 inc_mm_counter_fast(vma->vm_mm, MM_FILEPAGES);
3379 page_add_file_rmap(page);
3381 set_pte_at(vma->vm_mm, address, pte, entry);
3383 /* no need to invalidate: a not-present page won't be cached */
3384 update_mmu_cache(vma, address, pte);
3388 * __do_fault() tries to create a new page mapping. It aggressively
3389 * tries to share with existing pages, but makes a separate copy if
3390 * the FAULT_FLAG_WRITE is set in the flags parameter in order to avoid
3391 * the next page fault.
3393 * As this is called only for pages that do not currently exist, we
3394 * do not need to flush old virtual caches or the TLB.
3396 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3397 * but allow concurrent faults), and pte neither mapped nor locked.
3398 * We return with mmap_sem still held, but pte unmapped and unlocked.
3400 static int __do_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3401 unsigned long address, pmd_t *pmd,
3402 pgoff_t pgoff, unsigned int flags, pte_t orig_pte)
3407 struct page *cow_page;
3410 struct page *dirty_page = NULL;
3411 struct vm_fault vmf;
3413 int page_mkwrite = 0;
3414 gfp_t gfp = GFP_HIGHUSER_MOVABLE;
3416 if (IS_ENABLED(CONFIG_CMA) && (flags & FAULT_FLAG_NO_CMA))
3417 gfp &= ~__GFP_MOVABLE;
3421 * If we do COW later, allocate page befor taking lock_page()
3422 * on the file cache page. This will reduce lock holding time.
3424 if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) {
3426 if (unlikely(anon_vma_prepare(vma)))
3427 return VM_FAULT_OOM;
3429 cow_page = alloc_page_vma(gfp, vma, address);
3431 return VM_FAULT_OOM;
3433 if (mem_cgroup_newpage_charge(cow_page, mm, GFP_KERNEL)) {
3434 page_cache_release(cow_page);
3435 return VM_FAULT_OOM;
3440 vmf.virtual_address = (void __user *)(address & PAGE_MASK);
3445 ret = vma->vm_ops->fault(vma, &vmf);
3446 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3450 if (unlikely(PageHWPoison(vmf.page))) {
3451 if (ret & VM_FAULT_LOCKED)
3452 unlock_page(vmf.page);
3453 ret = VM_FAULT_HWPOISON;
3458 * For consistency in subsequent calls, make the faulted page always
3461 if (unlikely(!(ret & VM_FAULT_LOCKED)))
3462 lock_page(vmf.page);
3464 VM_BUG_ON(!PageLocked(vmf.page));
3467 * Should we do an early C-O-W break?
3470 if (flags & FAULT_FLAG_WRITE) {
3471 if (!(vma->vm_flags & VM_SHARED)) {
3474 copy_user_highpage(page, vmf.page, address, vma);
3475 __SetPageUptodate(page);
3478 * If the page will be shareable, see if the backing
3479 * address space wants to know that the page is about
3480 * to become writable
3482 if (vma->vm_ops->page_mkwrite) {
3486 vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
3487 tmp = vma->vm_ops->page_mkwrite(vma, &vmf);
3489 (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3491 goto unwritable_page;
3493 if (unlikely(!(tmp & VM_FAULT_LOCKED))) {
3495 if (!page->mapping) {
3496 ret = 0; /* retry the fault */
3498 goto unwritable_page;
3501 VM_BUG_ON(!PageLocked(page));
3508 page_table = pte_offset_map_lock(mm, pmd, address, &ptl);
3511 * This silly early PAGE_DIRTY setting removes a race
3512 * due to the bad i386 page protection. But it's valid
3513 * for other architectures too.
3515 * Note that if FAULT_FLAG_WRITE is set, we either now have
3516 * an exclusive copy of the page, or this is a shared mapping,
3517 * so we can make it writable and dirty to avoid having to
3518 * handle that later.
3520 /* Only go through if we didn't race with anybody else... */
3521 if (likely(pte_same(*page_table, orig_pte))) {
3522 flush_icache_page(vma, page);
3523 entry = mk_pte(page, vma->vm_page_prot);
3524 if (flags & FAULT_FLAG_WRITE)
3525 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3527 inc_mm_counter_fast(mm, MM_ANONPAGES);
3528 page_add_new_anon_rmap(page, vma, address);
3530 inc_mm_counter_fast(mm, MM_FILEPAGES);
3531 page_add_file_rmap(page);
3532 if (flags & FAULT_FLAG_WRITE) {
3534 get_page(dirty_page);
3537 set_pte_at(mm, address, page_table, entry);
3539 /* no need to invalidate: a not-present page won't be cached */
3540 update_mmu_cache(vma, address, page_table);
3543 mem_cgroup_uncharge_page(cow_page);
3545 page_cache_release(page);
3547 anon = 1; /* no anon but release faulted_page */
3550 pte_unmap_unlock(page_table, ptl);
3553 struct address_space *mapping = page->mapping;
3556 if (set_page_dirty(dirty_page))
3558 unlock_page(dirty_page);
3559 put_page(dirty_page);
3560 if ((dirtied || page_mkwrite) && mapping) {
3562 * Some device drivers do not set page.mapping but still
3565 balance_dirty_pages_ratelimited(mapping);
3568 /* file_update_time outside page_lock */
3569 if (vma->vm_file && !page_mkwrite)
3570 file_update_time(vma->vm_file);
3572 unlock_page(vmf.page);
3574 page_cache_release(vmf.page);
3580 page_cache_release(page);
3583 /* fs's fault handler get error */
3585 mem_cgroup_uncharge_page(cow_page);
3586 page_cache_release(cow_page);
3591 static int do_linear_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3592 unsigned long address, pte_t *page_table, pmd_t *pmd,
3593 unsigned int flags, pte_t orig_pte)
3595 pgoff_t pgoff = (((address & PAGE_MASK)
3596 - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
3598 pte_unmap(page_table);
3599 /* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */
3600 if (!vma->vm_ops->fault)
3601 return VM_FAULT_SIGBUS;
3602 return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
3606 * Fault of a previously existing named mapping. Repopulate the pte
3607 * from the encoded file_pte if possible. This enables swappable
3610 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3611 * but allow concurrent faults), and pte mapped but not yet locked.
3612 * We return with mmap_sem still held, but pte unmapped and unlocked.
3614 static int do_nonlinear_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3615 unsigned long address, pte_t *page_table, pmd_t *pmd,
3616 unsigned int flags, pte_t orig_pte)
3620 flags |= FAULT_FLAG_NONLINEAR;
3622 if (!pte_unmap_same(mm, pmd, page_table, orig_pte))
3625 if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) {
3627 * Page table corrupted: show pte and kill process.
3629 print_bad_pte(vma, address, orig_pte, NULL);
3630 return VM_FAULT_SIGBUS;
3633 pgoff = pte_to_pgoff(orig_pte);
3634 return __do_fault(mm, vma, address, pmd, pgoff, flags, orig_pte);
3637 int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3638 unsigned long addr, int page_nid)
3642 count_vm_numa_event(NUMA_HINT_FAULTS);
3643 if (page_nid == numa_node_id())
3644 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3646 return mpol_misplaced(page, vma, addr);
3649 int do_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3650 unsigned long addr, pte_t pte, pte_t *ptep, pmd_t *pmd)
3652 struct page *page = NULL;
3656 bool migrated = false;
3659 * The "pte" at this point cannot be used safely without
3660 * validation through pte_unmap_same(). It's of NUMA type but
3661 * the pfn may be screwed if the read is non atomic.
3663 * ptep_modify_prot_start is not called as this is clearing
3664 * the _PAGE_NUMA bit and it is not really expected that there
3665 * would be concurrent hardware modifications to the PTE.
3667 ptl = pte_lockptr(mm, pmd);
3669 if (unlikely(!pte_same(*ptep, pte))) {
3670 pte_unmap_unlock(ptep, ptl);
3674 pte = pte_mknonnuma(pte);
3675 set_pte_at(mm, addr, ptep, pte);
3676 update_mmu_cache(vma, addr, ptep);
3678 page = vm_normal_page(vma, addr, pte);
3680 pte_unmap_unlock(ptep, ptl);
3684 page_nid = page_to_nid(page);
3685 target_nid = numa_migrate_prep(page, vma, addr, page_nid);
3686 pte_unmap_unlock(ptep, ptl);
3687 if (target_nid == -1) {
3692 /* Migrate to the requested node */
3693 migrated = migrate_misplaced_page(page, target_nid);
3695 page_nid = target_nid;
3699 task_numa_fault(page_nid, 1, migrated);
3703 /* NUMA hinting page fault entry point for regular pmds */
3704 #ifdef CONFIG_NUMA_BALANCING
3705 static int do_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3706 unsigned long addr, pmd_t *pmdp)
3709 pte_t *pte, *orig_pte;
3710 unsigned long _addr = addr & PMD_MASK;
3711 unsigned long offset;
3715 spin_lock(&mm->page_table_lock);
3717 if (pmd_numa(pmd)) {
3718 set_pmd_at(mm, _addr, pmdp, pmd_mknonnuma(pmd));
3721 spin_unlock(&mm->page_table_lock);
3726 /* we're in a page fault so some vma must be in the range */
3728 BUG_ON(vma->vm_start >= _addr + PMD_SIZE);
3729 offset = max(_addr, vma->vm_start) & ~PMD_MASK;
3730 VM_BUG_ON(offset >= PMD_SIZE);
3731 orig_pte = pte = pte_offset_map_lock(mm, pmdp, _addr, &ptl);
3732 pte += offset >> PAGE_SHIFT;
3733 for (addr = _addr + offset; addr < _addr + PMD_SIZE; pte++, addr += PAGE_SIZE) {
3734 pte_t pteval = *pte;
3738 bool migrated = false;
3740 if (!pte_present(pteval))
3742 if (!pte_numa(pteval))
3744 if (addr >= vma->vm_end) {
3745 vma = find_vma(mm, addr);
3746 /* there's a pte present so there must be a vma */
3748 BUG_ON(addr < vma->vm_start);
3750 if (pte_numa(pteval)) {
3751 pteval = pte_mknonnuma(pteval);
3752 set_pte_at(mm, addr, pte, pteval);
3754 page = vm_normal_page(vma, addr, pteval);
3755 if (unlikely(!page))
3757 /* only check non-shared pages */
3758 if (unlikely(page_mapcount(page) != 1))
3761 page_nid = page_to_nid(page);
3762 target_nid = numa_migrate_prep(page, vma, addr, page_nid);
3763 pte_unmap_unlock(pte, ptl);
3764 if (target_nid != -1) {
3765 migrated = migrate_misplaced_page(page, target_nid);
3767 page_nid = target_nid;
3773 task_numa_fault(page_nid, 1, migrated);
3775 pte = pte_offset_map_lock(mm, pmdp, addr, &ptl);
3777 pte_unmap_unlock(orig_pte, ptl);
3782 static int do_pmd_numa_page(struct mm_struct *mm, struct vm_area_struct *vma,
3783 unsigned long addr, pmd_t *pmdp)
3788 #endif /* CONFIG_NUMA_BALANCING */
3791 * These routines also need to handle stuff like marking pages dirty
3792 * and/or accessed for architectures that don't do it in hardware (most
3793 * RISC architectures). The early dirtying is also good on the i386.
3795 * There is also a hook called "update_mmu_cache()" that architectures
3796 * with external mmu caches can use to update those (ie the Sparc or
3797 * PowerPC hashed page tables that act as extended TLBs).
3799 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3800 * but allow concurrent faults), and pte mapped but not yet locked.
3801 * We return with mmap_sem still held, but pte unmapped and unlocked.
3803 int handle_pte_fault(struct mm_struct *mm,
3804 struct vm_area_struct *vma, unsigned long address,
3805 pte_t *pte, pmd_t *pmd, unsigned int flags)
3809 bool fix_prot = false;
3812 if (!pte_present(entry)) {
3813 if (pte_none(entry)) {
3815 return do_linear_fault(mm, vma, address,
3816 pte, pmd, flags, entry);
3817 return do_anonymous_page(mm, vma, address,
3820 if (pte_file(entry))
3821 return do_nonlinear_fault(mm, vma, address,
3822 pte, pmd, flags, entry);
3823 return do_swap_page(mm, vma, address,
3824 pte, pmd, flags, entry);
3827 if (pte_numa(entry))
3828 return do_numa_page(mm, vma, address, entry, pte, pmd);
3830 if (vma->vm_ops && vma->vm_ops->fixup_prot && vma->vm_ops->fault &&
3831 (entry == pte_modify(entry, vm_get_page_prot(VM_NONE)))) {
3832 pgoff_t pgoff = (((address & PAGE_MASK)
3833 - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
3834 if (!vma->vm_ops->fixup_prot(vma, address & PAGE_MASK, pgoff))
3835 return VM_FAULT_SIGSEGV; /* access not granted */
3839 ptl = pte_lockptr(mm, pmd);
3841 if (unlikely(!pte_same(*pte, entry)))
3844 entry = pte_modify(entry, vma->vm_page_prot);
3845 vm_stat_account(mm, VM_NONE, vma->vm_file, -1);
3846 vm_stat_account(mm, vma->vm_flags, vma->vm_file, 1);
3848 if (flags & FAULT_FLAG_WRITE) {
3849 if (!pte_write(entry))
3850 return do_wp_page(mm, vma, address,
3851 pte, pmd, ptl, entry, flags);
3852 entry = pte_mkdirty(entry);
3854 entry = pte_mkyoung(entry);
3855 if (ptep_set_access_flags(vma, address, pte, entry, flags & FAULT_FLAG_WRITE)) {
3856 update_mmu_cache(vma, address, pte);
3859 * This is needed only for protection faults but the arch code
3860 * is not yet telling us if this is a protection fault or not.
3861 * This still avoids useless tlb flushes for .text page faults
3864 if (flags & FAULT_FLAG_WRITE)
3865 flush_tlb_fix_spurious_fault(vma, address);
3868 pte_unmap_unlock(pte, ptl);
3873 * By the time we get here, we already hold the mm semaphore
3875 static int __handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3876 unsigned long address, unsigned int flags)
3883 if (unlikely(is_vm_hugetlb_page(vma)))
3884 return hugetlb_fault(mm, vma, address, flags);
3887 pgd = pgd_offset(mm, address);
3888 pud = pud_alloc(mm, pgd, address);
3890 return VM_FAULT_OOM;
3891 pmd = pmd_alloc(mm, pud, address);
3893 return VM_FAULT_OOM;
3894 if (pmd_none(*pmd) && transparent_hugepage_enabled(vma)) {
3896 return do_huge_pmd_anonymous_page(mm, vma, address,
3899 pmd_t orig_pmd = *pmd;
3903 if (pmd_trans_huge(orig_pmd)) {
3904 unsigned int dirty = flags & FAULT_FLAG_WRITE;
3907 * If the pmd is splitting, return and retry the
3908 * the fault. Alternative: wait until the split
3909 * is done, and goto retry.
3911 if (pmd_trans_splitting(orig_pmd))
3914 if (pmd_numa(orig_pmd))
3915 return do_huge_pmd_numa_page(mm, vma, address,
3918 if (dirty && !pmd_write(orig_pmd)) {
3919 ret = do_huge_pmd_wp_page(mm, vma, address, pmd,
3922 * If COW results in an oom, the huge pmd will
3923 * have been split, so retry the fault on the
3924 * pte for a smaller charge.
3926 if (unlikely(ret & VM_FAULT_OOM))
3930 huge_pmd_set_accessed(mm, vma, address, pmd,
3939 return do_pmd_numa_page(mm, vma, address, pmd);
3942 * Use __pte_alloc instead of pte_alloc_map, because we can't
3943 * run pte_offset_map on the pmd, if an huge pmd could
3944 * materialize from under us from a different thread.
3946 if (unlikely(pmd_none(*pmd)) &&
3947 unlikely(__pte_alloc(mm, vma, pmd, address)))
3948 return VM_FAULT_OOM;
3949 /* if an huge pmd materialized from under us just retry later */
3950 if (unlikely(pmd_trans_huge(*pmd)))
3953 * A regular pmd is established and it can't morph into a huge pmd
3954 * from under us anymore at this point because we hold the mmap_sem
3955 * read mode and khugepaged takes it in write mode. So now it's
3956 * safe to run pte_offset_map().
3958 pte = pte_offset_map(pmd, address);
3960 return handle_pte_fault(mm, vma, address, pte, pmd, flags);
3963 int handle_mm_fault(struct mm_struct *mm, struct vm_area_struct *vma,
3964 unsigned long address, unsigned int flags)
3968 __set_current_state(TASK_RUNNING);
3970 count_vm_event(PGFAULT);
3971 mem_cgroup_count_vm_event(mm, PGFAULT);
3973 /* do counter updates before entering really critical section. */
3974 check_sync_rss_stat(current);
3977 * Enable the memcg OOM handling for faults triggered in user
3978 * space. Kernel faults are handled more gracefully.
3980 if (flags & FAULT_FLAG_USER)
3981 mem_cgroup_oom_enable();
3983 ret = __handle_mm_fault(mm, vma, address, flags);
3985 if (flags & FAULT_FLAG_USER) {
3986 mem_cgroup_oom_disable();
3988 * The task may have entered a memcg OOM situation but
3989 * if the allocation error was handled gracefully (no
3990 * VM_FAULT_OOM), there is no need to kill anything.
3991 * Just clean up the OOM state peacefully.
3993 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
3994 mem_cgroup_oom_synchronize(false);
4000 #ifndef __PAGETABLE_PUD_FOLDED
4002 * Allocate page upper directory.
4003 * We've already handled the fast-path in-line.
4005 int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4007 pud_t *new = pud_alloc_one(mm, address);
4011 smp_wmb(); /* See comment in __pte_alloc */
4013 spin_lock(&mm->page_table_lock);
4014 if (pgd_present(*pgd)) /* Another has populated it */
4017 pgd_populate(mm, pgd, new);
4018 spin_unlock(&mm->page_table_lock);
4021 #endif /* __PAGETABLE_PUD_FOLDED */
4023 #ifndef __PAGETABLE_PMD_FOLDED
4025 * Allocate page middle directory.
4026 * We've already handled the fast-path in-line.
4028 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4030 pmd_t *new = pmd_alloc_one(mm, address);
4034 smp_wmb(); /* See comment in __pte_alloc */
4036 spin_lock(&mm->page_table_lock);
4037 #ifndef __ARCH_HAS_4LEVEL_HACK
4038 if (pud_present(*pud)) /* Another has populated it */
4041 pud_populate(mm, pud, new);
4043 if (pgd_present(*pud)) /* Another has populated it */
4046 pgd_populate(mm, pud, new);
4047 #endif /* __ARCH_HAS_4LEVEL_HACK */
4048 spin_unlock(&mm->page_table_lock);
4051 #endif /* __PAGETABLE_PMD_FOLDED */
4053 #if !defined(__HAVE_ARCH_GATE_AREA)
4055 #if defined(AT_SYSINFO_EHDR)
4056 static struct vm_area_struct gate_vma;
4058 static int __init gate_vma_init(void)
4060 gate_vma.vm_mm = NULL;
4061 gate_vma.vm_start = FIXADDR_USER_START;
4062 gate_vma.vm_end = FIXADDR_USER_END;
4063 gate_vma.vm_flags = VM_READ | VM_MAYREAD | VM_EXEC | VM_MAYEXEC;
4064 gate_vma.vm_page_prot = __P101;
4068 __initcall(gate_vma_init);
4071 struct vm_area_struct *get_gate_vma(struct mm_struct *mm)
4073 #ifdef AT_SYSINFO_EHDR
4080 int in_gate_area_no_mm(unsigned long addr)
4082 #ifdef AT_SYSINFO_EHDR
4083 if ((addr >= FIXADDR_USER_START) && (addr < FIXADDR_USER_END))
4089 #endif /* __HAVE_ARCH_GATE_AREA */
4091 static int __follow_pte(struct mm_struct *mm, unsigned long address,
4092 pte_t **ptepp, spinlock_t **ptlp)
4099 pgd = pgd_offset(mm, address);
4100 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4103 pud = pud_offset(pgd, address);
4104 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4107 pmd = pmd_offset(pud, address);
4108 VM_BUG_ON(pmd_trans_huge(*pmd));
4109 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4112 /* We cannot handle huge page PFN maps. Luckily they don't exist. */
4116 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4119 if (!pte_present(*ptep))
4124 pte_unmap_unlock(ptep, *ptlp);
4129 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4130 pte_t **ptepp, spinlock_t **ptlp)
4134 /* (void) is needed to make gcc happy */
4135 (void) __cond_lock(*ptlp,
4136 !(res = __follow_pte(mm, address, ptepp, ptlp)));
4141 * follow_pfn - look up PFN at a user virtual address
4142 * @vma: memory mapping
4143 * @address: user virtual address
4144 * @pfn: location to store found PFN
4146 * Only IO mappings and raw PFN mappings are allowed.
4148 * Returns zero and the pfn at @pfn on success, -ve otherwise.
4150 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4157 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4160 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4163 *pfn = pte_pfn(*ptep);
4164 pte_unmap_unlock(ptep, ptl);
4167 EXPORT_SYMBOL(follow_pfn);
4169 #ifdef CONFIG_HAVE_IOREMAP_PROT
4170 int follow_phys(struct vm_area_struct *vma,
4171 unsigned long address, unsigned int flags,
4172 unsigned long *prot, resource_size_t *phys)
4178 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4181 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4185 if ((flags & FOLL_WRITE) && !pte_write(pte))
4188 *prot = pgprot_val(pte_pgprot(pte));
4189 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4193 pte_unmap_unlock(ptep, ptl);
4198 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4199 void *buf, int len, int write)
4201 resource_size_t phys_addr;
4202 unsigned long prot = 0;
4203 void __iomem *maddr;
4204 int offset = addr & (PAGE_SIZE-1);
4206 if (follow_phys(vma, addr, write, &prot, &phys_addr))
4209 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4211 memcpy_toio(maddr + offset, buf, len);
4213 memcpy_fromio(buf, maddr + offset, len);
4218 EXPORT_SYMBOL_GPL(generic_access_phys);
4222 * Access another process' address space as given in mm. If non-NULL, use the
4223 * given task for page fault accounting.
4225 static int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4226 unsigned long addr, void *buf, int len, int write)
4228 struct vm_area_struct *vma;
4229 void *old_buf = buf;
4231 down_read(&mm->mmap_sem);
4232 /* ignore errors, just check how much was successfully transferred */
4234 int bytes, ret, offset;
4236 struct page *page = NULL;
4238 ret = get_user_pages(tsk, mm, addr, 1,
4239 write, 1, &page, &vma);
4242 * Check if this is a VM_IO | VM_PFNMAP VMA, which
4243 * we can access using slightly different code.
4245 #ifdef CONFIG_HAVE_IOREMAP_PROT
4246 vma = find_vma(mm, addr);
4247 if (!vma || vma->vm_start > addr)
4249 if (vma->vm_ops && vma->vm_ops->access)
4250 ret = vma->vm_ops->access(vma, addr, buf,
4258 offset = addr & (PAGE_SIZE-1);
4259 if (bytes > PAGE_SIZE-offset)
4260 bytes = PAGE_SIZE-offset;
4264 copy_to_user_page(vma, page, addr,
4265 maddr + offset, buf, bytes);
4266 set_page_dirty_lock(page);
4268 copy_from_user_page(vma, page, addr,
4269 buf, maddr + offset, bytes);
4272 page_cache_release(page);
4278 up_read(&mm->mmap_sem);
4280 return buf - old_buf;
4284 * access_remote_vm - access another process' address space
4285 * @mm: the mm_struct of the target address space
4286 * @addr: start address to access
4287 * @buf: source or destination buffer
4288 * @len: number of bytes to transfer
4289 * @write: whether the access is a write
4291 * The caller must hold a reference on @mm.
4293 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
4294 void *buf, int len, int write)
4296 return __access_remote_vm(NULL, mm, addr, buf, len, write);
4300 * Access another process' address space.
4301 * Source/target buffer must be kernel space,
4302 * Do not walk the page table directly, use get_user_pages
4304 int access_process_vm(struct task_struct *tsk, unsigned long addr,
4305 void *buf, int len, int write)
4307 struct mm_struct *mm;
4310 mm = get_task_mm(tsk);
4314 ret = __access_remote_vm(tsk, mm, addr, buf, len, write);
4321 * Print the name of a VMA.
4323 void print_vma_addr(char *prefix, unsigned long ip)
4325 struct mm_struct *mm = current->mm;
4326 struct vm_area_struct *vma;
4329 * Do not print if we are in atomic
4330 * contexts (in exception stacks, etc.):
4332 if (preempt_count())
4335 down_read(&mm->mmap_sem);
4336 vma = find_vma(mm, ip);
4337 if (vma && vma->vm_file) {
4338 struct file *f = vma->vm_file;
4339 char *buf = (char *)__get_free_page(GFP_KERNEL);
4343 p = d_path(&f->f_path, buf, PAGE_SIZE);
4346 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
4348 vma->vm_end - vma->vm_start);
4349 free_page((unsigned long)buf);
4352 up_read(&mm->mmap_sem);
4355 #ifdef CONFIG_PROVE_LOCKING
4356 void might_fault(void)
4359 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4360 * holding the mmap_sem, this is safe because kernel memory doesn't
4361 * get paged out, therefore we'll never actually fault, and the
4362 * below annotations will generate false positives.
4364 if (segment_eq(get_fs(), KERNEL_DS))
4369 * it would be nicer only to annotate paths which are not under
4370 * pagefault_disable, however that requires a larger audit and
4371 * providing helpers like get_user_atomic.
4373 if (!in_atomic() && current->mm)
4374 might_lock_read(¤t->mm->mmap_sem);
4376 EXPORT_SYMBOL(might_fault);
4379 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4380 static void clear_gigantic_page(struct page *page,
4382 unsigned int pages_per_huge_page)
4385 struct page *p = page;
4388 for (i = 0; i < pages_per_huge_page;
4389 i++, p = mem_map_next(p, page, i)) {
4391 clear_user_highpage(p, addr + i * PAGE_SIZE);
4394 void clear_huge_page(struct page *page,
4395 unsigned long addr, unsigned int pages_per_huge_page)
4399 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4400 clear_gigantic_page(page, addr, pages_per_huge_page);
4405 for (i = 0; i < pages_per_huge_page; i++) {
4407 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4411 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4413 struct vm_area_struct *vma,
4414 unsigned int pages_per_huge_page)
4417 struct page *dst_base = dst;
4418 struct page *src_base = src;
4420 for (i = 0; i < pages_per_huge_page; ) {
4422 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4425 dst = mem_map_next(dst, dst_base, i);
4426 src = mem_map_next(src, src_base, i);
4430 void copy_user_huge_page(struct page *dst, struct page *src,
4431 unsigned long addr, struct vm_area_struct *vma,
4432 unsigned int pages_per_huge_page)
4436 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4437 copy_user_gigantic_page(dst, src, addr, vma,
4438 pages_per_huge_page);
4443 for (i = 0; i < pages_per_huge_page; i++) {
4445 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
4448 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */