4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
8 * demand-loading started 01.12.91 - seems it is high on the list of
9 * things wanted, and it should be easy to implement. - Linus
13 * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
14 * pages started 02.12.91, seems to work. - Linus.
16 * Tested sharing by executing about 30 /bin/sh: under the old kernel it
17 * would have taken more than the 6M I have free, but it worked well as
20 * Also corrected some "invalidate()"s - I wasn't doing enough of them.
24 * Real VM (paging to/from disk) started 18.12.91. Much more work and
25 * thought has to go into this. Oh, well..
26 * 19.12.91 - works, somewhat. Sometimes I get faults, don't know why.
27 * Found it. Everything seems to work now.
28 * 20.12.91 - Ok, making the swap-device changeable like the root.
32 * 05.04.94 - Multi-page memory management added for v1.1.
33 * Idea by Alex Bligh (alex@cconcepts.co.uk)
35 * 16.07.99 - Support of BIGMEM added by Gerhard Wichert, Siemens AG
36 * (Gerhard.Wichert@pdb.siemens.de)
38 * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
41 #include <linux/kernel_stat.h>
43 #include <linux/sched/mm.h>
44 #include <linux/sched/coredump.h>
45 #include <linux/sched/numa_balancing.h>
46 #include <linux/sched/task.h>
47 #include <linux/hugetlb.h>
48 #include <linux/mman.h>
49 #include <linux/swap.h>
50 #include <linux/highmem.h>
51 #include <linux/pagemap.h>
52 #include <linux/memremap.h>
53 #include <linux/ksm.h>
54 #include <linux/rmap.h>
55 #include <linux/export.h>
56 #include <linux/delayacct.h>
57 #include <linux/init.h>
58 #include <linux/pfn_t.h>
59 #include <linux/writeback.h>
60 #include <linux/memcontrol.h>
61 #include <linux/mmu_notifier.h>
62 #include <linux/swapops.h>
63 #include <linux/elf.h>
64 #include <linux/gfp.h>
65 #include <linux/migrate.h>
66 #include <linux/string.h>
67 #include <linux/dma-debug.h>
68 #include <linux/debugfs.h>
69 #include <linux/userfaultfd_k.h>
70 #include <linux/dax.h>
71 #include <linux/oom.h>
74 #include <asm/mmu_context.h>
75 #include <asm/pgalloc.h>
76 #include <linux/uaccess.h>
78 #include <asm/tlbflush.h>
79 #include <asm/pgtable.h>
83 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
84 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
87 #ifndef CONFIG_NEED_MULTIPLE_NODES
88 /* use the per-pgdat data instead for discontigmem - mbligh */
89 unsigned long max_mapnr;
90 EXPORT_SYMBOL(max_mapnr);
93 EXPORT_SYMBOL(mem_map);
97 * A number of key systems in x86 including ioremap() rely on the assumption
98 * that high_memory defines the upper bound on direct map memory, then end
99 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and
100 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
104 EXPORT_SYMBOL(high_memory);
107 * Randomize the address space (stacks, mmaps, brk, etc.).
109 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
110 * as ancient (libc5 based) binaries can segfault. )
112 int randomize_va_space __read_mostly =
113 #ifdef CONFIG_COMPAT_BRK
119 #ifndef arch_faults_on_old_pte
120 static inline bool arch_faults_on_old_pte(void)
123 * Those arches which don't have hw access flag feature need to
124 * implement their own helper. By default, "true" means pagefault
125 * will be hit on old pte.
131 static int __init disable_randmaps(char *s)
133 randomize_va_space = 0;
136 __setup("norandmaps", disable_randmaps);
138 unsigned long zero_pfn __read_mostly;
139 EXPORT_SYMBOL(zero_pfn);
141 unsigned long highest_memmap_pfn __read_mostly;
144 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
146 static int __init init_zero_pfn(void)
148 zero_pfn = page_to_pfn(ZERO_PAGE(0));
151 early_initcall(init_zero_pfn);
154 #if defined(SPLIT_RSS_COUNTING)
156 void sync_mm_rss(struct mm_struct *mm)
160 for (i = 0; i < NR_MM_COUNTERS; i++) {
161 if (current->rss_stat.count[i]) {
162 add_mm_counter(mm, i, current->rss_stat.count[i]);
163 current->rss_stat.count[i] = 0;
166 current->rss_stat.events = 0;
169 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
171 struct task_struct *task = current;
173 if (likely(task->mm == mm))
174 task->rss_stat.count[member] += val;
176 add_mm_counter(mm, member, val);
178 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
179 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
181 /* sync counter once per 64 page faults */
182 #define TASK_RSS_EVENTS_THRESH (64)
183 static void check_sync_rss_stat(struct task_struct *task)
185 if (unlikely(task != current))
187 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
188 sync_mm_rss(task->mm);
190 #else /* SPLIT_RSS_COUNTING */
192 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
193 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
195 static void check_sync_rss_stat(struct task_struct *task)
199 #endif /* SPLIT_RSS_COUNTING */
201 #ifdef HAVE_GENERIC_MMU_GATHER
203 static bool tlb_next_batch(struct mmu_gather *tlb)
205 struct mmu_gather_batch *batch;
209 tlb->active = batch->next;
213 if (tlb->batch_count == MAX_GATHER_BATCH_COUNT)
216 batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0);
223 batch->max = MAX_GATHER_BATCH;
225 tlb->active->next = batch;
231 void arch_tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm,
232 unsigned long start, unsigned long end)
236 /* Is it from 0 to ~0? */
237 tlb->fullmm = !(start | (end+1));
238 tlb->need_flush_all = 0;
239 tlb->local.next = NULL;
241 tlb->local.max = ARRAY_SIZE(tlb->__pages);
242 tlb->active = &tlb->local;
243 tlb->batch_count = 0;
245 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
250 __tlb_reset_range(tlb);
253 static void tlb_flush_mmu_free(struct mmu_gather *tlb)
255 struct mmu_gather_batch *batch;
257 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
258 tlb_table_flush(tlb);
260 for (batch = &tlb->local; batch && batch->nr; batch = batch->next) {
261 free_pages_and_swap_cache(batch->pages, batch->nr);
264 tlb->active = &tlb->local;
267 void tlb_flush_mmu(struct mmu_gather *tlb)
269 tlb_flush_mmu_tlbonly(tlb);
270 tlb_flush_mmu_free(tlb);
274 * Called at the end of the shootdown operation to free up any resources
275 * that were required.
277 void arch_tlb_finish_mmu(struct mmu_gather *tlb,
278 unsigned long start, unsigned long end, bool force)
280 struct mmu_gather_batch *batch, *next;
283 __tlb_adjust_range(tlb, start, end - start);
287 /* keep the page table cache within bounds */
290 for (batch = tlb->local.next; batch; batch = next) {
292 free_pages((unsigned long)batch, 0);
294 tlb->local.next = NULL;
298 * Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while
299 * handling the additional races in SMP caused by other CPUs caching valid
300 * mappings in their TLBs. Returns the number of free page slots left.
301 * When out of page slots we must call tlb_flush_mmu().
302 *returns true if the caller should flush.
304 bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, int page_size)
306 struct mmu_gather_batch *batch;
308 VM_BUG_ON(!tlb->end);
309 VM_WARN_ON(tlb->page_size != page_size);
313 * Add the page and check if we are full. If so
316 batch->pages[batch->nr++] = page;
317 if (batch->nr == batch->max) {
318 if (!tlb_next_batch(tlb))
322 VM_BUG_ON_PAGE(batch->nr > batch->max, page);
327 void tlb_flush_pmd_range(struct mmu_gather *tlb, unsigned long address,
330 if (tlb->page_size != 0 && tlb->page_size != PMD_SIZE)
333 tlb->page_size = PMD_SIZE;
334 tlb->start = min(tlb->start, address);
335 tlb->end = max(tlb->end, address + size);
337 #endif /* HAVE_GENERIC_MMU_GATHER */
339 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
342 * See the comment near struct mmu_table_batch.
346 * If we want tlb_remove_table() to imply TLB invalidates.
348 static inline void tlb_table_invalidate(struct mmu_gather *tlb)
350 #ifdef CONFIG_HAVE_RCU_TABLE_INVALIDATE
352 * Invalidate page-table caches used by hardware walkers. Then we still
353 * need to RCU-sched wait while freeing the pages because software
354 * walkers can still be in-flight.
356 tlb_flush_mmu_tlbonly(tlb);
360 static void tlb_remove_table_smp_sync(void *arg)
362 /* Simply deliver the interrupt */
365 void tlb_remove_table_sync_one(void)
367 smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
370 static void tlb_remove_table_one(void *table)
373 * This isn't an RCU grace period and hence the page-tables cannot be
374 * assumed to be actually RCU-freed.
376 * It is however sufficient for software page-table walkers that rely on
377 * IRQ disabling. See the comment near struct mmu_table_batch.
379 smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
380 __tlb_remove_table(table);
383 static void tlb_remove_table_rcu(struct rcu_head *head)
385 struct mmu_table_batch *batch;
388 batch = container_of(head, struct mmu_table_batch, rcu);
390 for (i = 0; i < batch->nr; i++)
391 __tlb_remove_table(batch->tables[i]);
393 free_page((unsigned long)batch);
396 void tlb_table_flush(struct mmu_gather *tlb)
398 struct mmu_table_batch **batch = &tlb->batch;
401 tlb_table_invalidate(tlb);
402 call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
407 void tlb_remove_table(struct mmu_gather *tlb, void *table)
409 struct mmu_table_batch **batch = &tlb->batch;
411 if (*batch == NULL) {
412 *batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
413 if (*batch == NULL) {
414 tlb_table_invalidate(tlb);
415 tlb_remove_table_one(table);
421 (*batch)->tables[(*batch)->nr++] = table;
422 if ((*batch)->nr == MAX_TABLE_BATCH)
423 tlb_table_flush(tlb);
426 #endif /* CONFIG_HAVE_RCU_TABLE_FREE */
429 * tlb_gather_mmu - initialize an mmu_gather structure for page-table tear-down
430 * @tlb: the mmu_gather structure to initialize
431 * @mm: the mm_struct of the target address space
432 * @start: start of the region that will be removed from the page-table
433 * @end: end of the region that will be removed from the page-table
435 * Called to initialize an (on-stack) mmu_gather structure for page-table
436 * tear-down from @mm. The @start and @end are set to 0 and -1
437 * respectively when @mm is without users and we're going to destroy
438 * the full address space (exit/execve).
440 void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm,
441 unsigned long start, unsigned long end)
443 arch_tlb_gather_mmu(tlb, mm, start, end);
444 inc_tlb_flush_pending(tlb->mm);
447 void tlb_finish_mmu(struct mmu_gather *tlb,
448 unsigned long start, unsigned long end)
451 * If there are parallel threads are doing PTE changes on same range
452 * under non-exclusive lock(e.g., mmap_sem read-side) but defer TLB
453 * flush by batching, a thread has stable TLB entry can fail to flush
454 * the TLB by observing pte_none|!pte_dirty, for example so flush TLB
455 * forcefully if we detect parallel PTE batching threads.
457 bool force = mm_tlb_flush_nested(tlb->mm);
459 arch_tlb_finish_mmu(tlb, start, end, force);
460 dec_tlb_flush_pending(tlb->mm);
464 * Note: this doesn't free the actual pages themselves. That
465 * has been handled earlier when unmapping all the memory regions.
467 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
470 pgtable_t token = pmd_pgtable(*pmd);
472 pte_free_tlb(tlb, token, addr);
473 mm_dec_nr_ptes(tlb->mm);
476 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
477 unsigned long addr, unsigned long end,
478 unsigned long floor, unsigned long ceiling)
485 pmd = pmd_offset(pud, addr);
487 next = pmd_addr_end(addr, end);
488 if (pmd_none_or_clear_bad(pmd))
490 free_pte_range(tlb, pmd, addr);
491 } while (pmd++, addr = next, addr != end);
501 if (end - 1 > ceiling - 1)
504 pmd = pmd_offset(pud, start);
506 pmd_free_tlb(tlb, pmd, start);
507 mm_dec_nr_pmds(tlb->mm);
510 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
511 unsigned long addr, unsigned long end,
512 unsigned long floor, unsigned long ceiling)
519 pud = pud_offset(p4d, addr);
521 next = pud_addr_end(addr, end);
522 if (pud_none_or_clear_bad(pud))
524 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
525 } while (pud++, addr = next, addr != end);
535 if (end - 1 > ceiling - 1)
538 pud = pud_offset(p4d, start);
540 pud_free_tlb(tlb, pud, start);
541 mm_dec_nr_puds(tlb->mm);
544 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
545 unsigned long addr, unsigned long end,
546 unsigned long floor, unsigned long ceiling)
553 p4d = p4d_offset(pgd, addr);
555 next = p4d_addr_end(addr, end);
556 if (p4d_none_or_clear_bad(p4d))
558 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
559 } while (p4d++, addr = next, addr != end);
565 ceiling &= PGDIR_MASK;
569 if (end - 1 > ceiling - 1)
572 p4d = p4d_offset(pgd, start);
574 p4d_free_tlb(tlb, p4d, start);
578 * This function frees user-level page tables of a process.
580 void free_pgd_range(struct mmu_gather *tlb,
581 unsigned long addr, unsigned long end,
582 unsigned long floor, unsigned long ceiling)
588 * The next few lines have given us lots of grief...
590 * Why are we testing PMD* at this top level? Because often
591 * there will be no work to do at all, and we'd prefer not to
592 * go all the way down to the bottom just to discover that.
594 * Why all these "- 1"s? Because 0 represents both the bottom
595 * of the address space and the top of it (using -1 for the
596 * top wouldn't help much: the masks would do the wrong thing).
597 * The rule is that addr 0 and floor 0 refer to the bottom of
598 * the address space, but end 0 and ceiling 0 refer to the top
599 * Comparisons need to use "end - 1" and "ceiling - 1" (though
600 * that end 0 case should be mythical).
602 * Wherever addr is brought up or ceiling brought down, we must
603 * be careful to reject "the opposite 0" before it confuses the
604 * subsequent tests. But what about where end is brought down
605 * by PMD_SIZE below? no, end can't go down to 0 there.
607 * Whereas we round start (addr) and ceiling down, by different
608 * masks at different levels, in order to test whether a table
609 * now has no other vmas using it, so can be freed, we don't
610 * bother to round floor or end up - the tests don't need that.
624 if (end - 1 > ceiling - 1)
629 * We add page table cache pages with PAGE_SIZE,
630 * (see pte_free_tlb()), flush the tlb if we need
632 tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
633 pgd = pgd_offset(tlb->mm, addr);
635 next = pgd_addr_end(addr, end);
636 if (pgd_none_or_clear_bad(pgd))
638 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
639 } while (pgd++, addr = next, addr != end);
642 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
643 unsigned long floor, unsigned long ceiling)
646 struct vm_area_struct *next = vma->vm_next;
647 unsigned long addr = vma->vm_start;
650 * Hide vma from rmap and truncate_pagecache before freeing
653 unlink_anon_vmas(vma);
654 unlink_file_vma(vma);
656 if (is_vm_hugetlb_page(vma)) {
657 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
658 floor, next ? next->vm_start : ceiling);
661 * Optimization: gather nearby vmas into one call down
663 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
664 && !is_vm_hugetlb_page(next)) {
667 unlink_anon_vmas(vma);
668 unlink_file_vma(vma);
670 free_pgd_range(tlb, addr, vma->vm_end,
671 floor, next ? next->vm_start : ceiling);
677 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd, unsigned long address)
680 pgtable_t new = pte_alloc_one(mm, address);
685 * Ensure all pte setup (eg. pte page lock and page clearing) are
686 * visible before the pte is made visible to other CPUs by being
687 * put into page tables.
689 * The other side of the story is the pointer chasing in the page
690 * table walking code (when walking the page table without locking;
691 * ie. most of the time). Fortunately, these data accesses consist
692 * of a chain of data-dependent loads, meaning most CPUs (alpha
693 * being the notable exception) will already guarantee loads are
694 * seen in-order. See the alpha page table accessors for the
695 * smp_read_barrier_depends() barriers in page table walking code.
697 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
699 ptl = pmd_lock(mm, pmd);
700 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
702 pmd_populate(mm, pmd, new);
711 int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
713 pte_t *new = pte_alloc_one_kernel(&init_mm, address);
717 smp_wmb(); /* See comment in __pte_alloc */
719 spin_lock(&init_mm.page_table_lock);
720 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
721 pmd_populate_kernel(&init_mm, pmd, new);
724 spin_unlock(&init_mm.page_table_lock);
726 pte_free_kernel(&init_mm, new);
730 static inline void init_rss_vec(int *rss)
732 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
735 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
739 if (current->mm == mm)
741 for (i = 0; i < NR_MM_COUNTERS; i++)
743 add_mm_counter(mm, i, rss[i]);
747 * This function is called to print an error when a bad pte
748 * is found. For example, we might have a PFN-mapped pte in
749 * a region that doesn't allow it.
751 * The calling function must still handle the error.
753 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
754 pte_t pte, struct page *page)
756 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
757 p4d_t *p4d = p4d_offset(pgd, addr);
758 pud_t *pud = pud_offset(p4d, addr);
759 pmd_t *pmd = pmd_offset(pud, addr);
760 struct address_space *mapping;
762 static unsigned long resume;
763 static unsigned long nr_shown;
764 static unsigned long nr_unshown;
767 * Allow a burst of 60 reports, then keep quiet for that minute;
768 * or allow a steady drip of one report per second.
770 if (nr_shown == 60) {
771 if (time_before(jiffies, resume)) {
776 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
783 resume = jiffies + 60 * HZ;
785 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
786 index = linear_page_index(vma, addr);
788 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
790 (long long)pte_val(pte), (long long)pmd_val(*pmd));
792 dump_page(page, "bad pte");
793 pr_alert("addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
794 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
795 pr_alert("file:%pD fault:%pf mmap:%pf readpage:%pf\n",
797 vma->vm_ops ? vma->vm_ops->fault : NULL,
798 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
799 mapping ? mapping->a_ops->readpage : NULL);
801 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
805 * vm_normal_page -- This function gets the "struct page" associated with a pte.
807 * "Special" mappings do not wish to be associated with a "struct page" (either
808 * it doesn't exist, or it exists but they don't want to touch it). In this
809 * case, NULL is returned here. "Normal" mappings do have a struct page.
811 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
812 * pte bit, in which case this function is trivial. Secondly, an architecture
813 * may not have a spare pte bit, which requires a more complicated scheme,
816 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
817 * special mapping (even if there are underlying and valid "struct pages").
818 * COWed pages of a VM_PFNMAP are always normal.
820 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
821 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
822 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
823 * mapping will always honor the rule
825 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
827 * And for normal mappings this is false.
829 * This restricts such mappings to be a linear translation from virtual address
830 * to pfn. To get around this restriction, we allow arbitrary mappings so long
831 * as the vma is not a COW mapping; in that case, we know that all ptes are
832 * special (because none can have been COWed).
835 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
837 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
838 * page" backing, however the difference is that _all_ pages with a struct
839 * page (that is, those where pfn_valid is true) are refcounted and considered
840 * normal pages by the VM. The disadvantage is that pages are refcounted
841 * (which can be slower and simply not an option for some PFNMAP users). The
842 * advantage is that we don't have to follow the strict linearity rule of
843 * PFNMAP mappings in order to support COWable mappings.
846 struct page *_vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
847 pte_t pte, bool with_public_device)
849 unsigned long pfn = pte_pfn(pte);
851 if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
852 if (likely(!pte_special(pte)))
854 if (vma->vm_ops && vma->vm_ops->find_special_page)
855 return vma->vm_ops->find_special_page(vma, addr);
856 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
858 if (is_zero_pfn(pfn))
862 * Device public pages are special pages (they are ZONE_DEVICE
863 * pages but different from persistent memory). They behave
864 * allmost like normal pages. The difference is that they are
865 * not on the lru and thus should never be involve with any-
866 * thing that involve lru manipulation (mlock, numa balancing,
869 * This is why we still want to return NULL for such page from
870 * vm_normal_page() so that we do not have to special case all
871 * call site of vm_normal_page().
873 if (likely(pfn <= highest_memmap_pfn)) {
874 struct page *page = pfn_to_page(pfn);
876 if (is_device_public_page(page)) {
877 if (with_public_device)
886 print_bad_pte(vma, addr, pte, NULL);
890 /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
892 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
893 if (vma->vm_flags & VM_MIXEDMAP) {
899 off = (addr - vma->vm_start) >> PAGE_SHIFT;
900 if (pfn == vma->vm_pgoff + off)
902 if (!is_cow_mapping(vma->vm_flags))
907 if (is_zero_pfn(pfn))
911 if (unlikely(pfn > highest_memmap_pfn)) {
912 print_bad_pte(vma, addr, pte, NULL);
917 * NOTE! We still have PageReserved() pages in the page tables.
918 * eg. VDSO mappings can cause them to exist.
921 return pfn_to_page(pfn);
924 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
925 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
928 unsigned long pfn = pmd_pfn(pmd);
931 * There is no pmd_special() but there may be special pmds, e.g.
932 * in a direct-access (dax) mapping, so let's just replicate the
933 * !CONFIG_ARCH_HAS_PTE_SPECIAL case from vm_normal_page() here.
935 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
936 if (vma->vm_flags & VM_MIXEDMAP) {
942 off = (addr - vma->vm_start) >> PAGE_SHIFT;
943 if (pfn == vma->vm_pgoff + off)
945 if (!is_cow_mapping(vma->vm_flags))
952 if (is_zero_pfn(pfn))
954 if (unlikely(pfn > highest_memmap_pfn))
958 * NOTE! We still have PageReserved() pages in the page tables.
959 * eg. VDSO mappings can cause them to exist.
962 return pfn_to_page(pfn);
967 * copy one vm_area from one task to the other. Assumes the page tables
968 * already present in the new task to be cleared in the whole range
969 * covered by this vma.
972 static inline unsigned long
973 copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
974 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
975 unsigned long addr, int *rss)
977 unsigned long vm_flags = vma->vm_flags;
978 pte_t pte = *src_pte;
981 /* pte contains position in swap or file, so copy. */
982 if (unlikely(!pte_present(pte))) {
983 swp_entry_t entry = pte_to_swp_entry(pte);
985 if (likely(!non_swap_entry(entry))) {
986 if (swap_duplicate(entry) < 0)
989 /* make sure dst_mm is on swapoff's mmlist. */
990 if (unlikely(list_empty(&dst_mm->mmlist))) {
991 spin_lock(&mmlist_lock);
992 if (list_empty(&dst_mm->mmlist))
993 list_add(&dst_mm->mmlist,
995 spin_unlock(&mmlist_lock);
998 } else if (is_migration_entry(entry)) {
999 page = migration_entry_to_page(entry);
1001 rss[mm_counter(page)]++;
1003 if (is_write_migration_entry(entry) &&
1004 is_cow_mapping(vm_flags)) {
1006 * COW mappings require pages in both
1007 * parent and child to be set to read.
1009 make_migration_entry_read(&entry);
1010 pte = swp_entry_to_pte(entry);
1011 if (pte_swp_soft_dirty(*src_pte))
1012 pte = pte_swp_mksoft_dirty(pte);
1013 set_pte_at(src_mm, addr, src_pte, pte);
1015 } else if (is_device_private_entry(entry)) {
1016 page = device_private_entry_to_page(entry);
1019 * Update rss count even for unaddressable pages, as
1020 * they should treated just like normal pages in this
1023 * We will likely want to have some new rss counters
1024 * for unaddressable pages, at some point. But for now
1025 * keep things as they are.
1028 rss[mm_counter(page)]++;
1029 page_dup_rmap(page, false);
1032 * We do not preserve soft-dirty information, because so
1033 * far, checkpoint/restore is the only feature that
1034 * requires that. And checkpoint/restore does not work
1035 * when a device driver is involved (you cannot easily
1036 * save and restore device driver state).
1038 if (is_write_device_private_entry(entry) &&
1039 is_cow_mapping(vm_flags)) {
1040 make_device_private_entry_read(&entry);
1041 pte = swp_entry_to_pte(entry);
1042 set_pte_at(src_mm, addr, src_pte, pte);
1049 * If it's a COW mapping, write protect it both
1050 * in the parent and the child
1052 if (is_cow_mapping(vm_flags) && pte_write(pte)) {
1053 ptep_set_wrprotect(src_mm, addr, src_pte);
1054 pte = pte_wrprotect(pte);
1058 * If it's a shared mapping, mark it clean in
1061 if (vm_flags & VM_SHARED)
1062 pte = pte_mkclean(pte);
1063 pte = pte_mkold(pte);
1065 page = vm_normal_page(vma, addr, pte);
1068 page_dup_rmap(page, false);
1069 rss[mm_counter(page)]++;
1070 } else if (pte_devmap(pte)) {
1071 page = pte_page(pte);
1074 * Cache coherent device memory behave like regular page and
1075 * not like persistent memory page. For more informations see
1076 * MEMORY_DEVICE_CACHE_COHERENT in memory_hotplug.h
1078 if (is_device_public_page(page)) {
1080 page_dup_rmap(page, false);
1081 rss[mm_counter(page)]++;
1086 set_pte_at(dst_mm, addr, dst_pte, pte);
1090 static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1091 pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
1092 unsigned long addr, unsigned long end)
1094 pte_t *orig_src_pte, *orig_dst_pte;
1095 pte_t *src_pte, *dst_pte;
1096 spinlock_t *src_ptl, *dst_ptl;
1098 int rss[NR_MM_COUNTERS];
1099 swp_entry_t entry = (swp_entry_t){0};
1104 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
1107 src_pte = pte_offset_map(src_pmd, addr);
1108 src_ptl = pte_lockptr(src_mm, src_pmd);
1109 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1110 orig_src_pte = src_pte;
1111 orig_dst_pte = dst_pte;
1112 arch_enter_lazy_mmu_mode();
1116 * We are holding two locks at this point - either of them
1117 * could generate latencies in another task on another CPU.
1119 if (progress >= 32) {
1121 if (need_resched() ||
1122 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
1125 if (pte_none(*src_pte)) {
1129 entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
1134 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
1136 arch_leave_lazy_mmu_mode();
1137 spin_unlock(src_ptl);
1138 pte_unmap(orig_src_pte);
1139 add_mm_rss_vec(dst_mm, rss);
1140 pte_unmap_unlock(orig_dst_pte, dst_ptl);
1144 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
1153 static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1154 pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
1155 unsigned long addr, unsigned long end)
1157 pmd_t *src_pmd, *dst_pmd;
1160 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1163 src_pmd = pmd_offset(src_pud, addr);
1165 next = pmd_addr_end(addr, end);
1166 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1167 || pmd_devmap(*src_pmd)) {
1169 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, vma);
1170 err = copy_huge_pmd(dst_mm, src_mm,
1171 dst_pmd, src_pmd, addr, vma);
1178 if (pmd_none_or_clear_bad(src_pmd))
1180 if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
1183 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1187 static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1188 p4d_t *dst_p4d, p4d_t *src_p4d, struct vm_area_struct *vma,
1189 unsigned long addr, unsigned long end)
1191 pud_t *src_pud, *dst_pud;
1194 dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1197 src_pud = pud_offset(src_p4d, addr);
1199 next = pud_addr_end(addr, end);
1200 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1203 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, vma);
1204 err = copy_huge_pud(dst_mm, src_mm,
1205 dst_pud, src_pud, addr, vma);
1212 if (pud_none_or_clear_bad(src_pud))
1214 if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
1217 } while (dst_pud++, src_pud++, addr = next, addr != end);
1221 static inline int copy_p4d_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1222 pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
1223 unsigned long addr, unsigned long end)
1225 p4d_t *src_p4d, *dst_p4d;
1228 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1231 src_p4d = p4d_offset(src_pgd, addr);
1233 next = p4d_addr_end(addr, end);
1234 if (p4d_none_or_clear_bad(src_p4d))
1236 if (copy_pud_range(dst_mm, src_mm, dst_p4d, src_p4d,
1239 } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1243 int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1244 struct vm_area_struct *vma)
1246 pgd_t *src_pgd, *dst_pgd;
1248 unsigned long addr = vma->vm_start;
1249 unsigned long end = vma->vm_end;
1250 unsigned long mmun_start; /* For mmu_notifiers */
1251 unsigned long mmun_end; /* For mmu_notifiers */
1256 * Don't copy ptes where a page fault will fill them correctly.
1257 * Fork becomes much lighter when there are big shared or private
1258 * readonly mappings. The tradeoff is that copy_page_range is more
1259 * efficient than faulting.
1261 if (!(vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1265 if (is_vm_hugetlb_page(vma))
1266 return copy_hugetlb_page_range(dst_mm, src_mm, vma);
1268 if (unlikely(vma->vm_flags & VM_PFNMAP)) {
1270 * We do not free on error cases below as remove_vma
1271 * gets called on error from higher level routine
1273 ret = track_pfn_copy(vma);
1279 * We need to invalidate the secondary MMU mappings only when
1280 * there could be a permission downgrade on the ptes of the
1281 * parent mm. And a permission downgrade will only happen if
1282 * is_cow_mapping() returns true.
1284 is_cow = is_cow_mapping(vma->vm_flags);
1288 mmu_notifier_invalidate_range_start(src_mm, mmun_start,
1292 dst_pgd = pgd_offset(dst_mm, addr);
1293 src_pgd = pgd_offset(src_mm, addr);
1295 next = pgd_addr_end(addr, end);
1296 if (pgd_none_or_clear_bad(src_pgd))
1298 if (unlikely(copy_p4d_range(dst_mm, src_mm, dst_pgd, src_pgd,
1299 vma, addr, next))) {
1303 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1306 mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end);
1310 /* Whether we should zap all COWed (private) pages too */
1311 static inline bool should_zap_cows(struct zap_details *details)
1313 /* By default, zap all pages */
1317 /* Or, we zap COWed pages only if the caller wants to */
1318 return !details->check_mapping;
1321 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1322 struct vm_area_struct *vma, pmd_t *pmd,
1323 unsigned long addr, unsigned long end,
1324 struct zap_details *details)
1326 struct mm_struct *mm = tlb->mm;
1327 int force_flush = 0;
1328 int rss[NR_MM_COUNTERS];
1334 tlb_remove_check_page_size_change(tlb, PAGE_SIZE);
1337 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1339 flush_tlb_batched_pending(mm);
1340 arch_enter_lazy_mmu_mode();
1343 if (pte_none(ptent))
1346 if (pte_present(ptent)) {
1349 page = _vm_normal_page(vma, addr, ptent, true);
1350 if (unlikely(details) && page) {
1352 * unmap_shared_mapping_pages() wants to
1353 * invalidate cache without truncating:
1354 * unmap shared but keep private pages.
1356 if (details->check_mapping &&
1357 details->check_mapping != page_rmapping(page))
1360 ptent = ptep_get_and_clear_full(mm, addr, pte,
1362 tlb_remove_tlb_entry(tlb, pte, addr);
1363 if (unlikely(!page))
1366 if (!PageAnon(page)) {
1367 if (pte_dirty(ptent)) {
1369 set_page_dirty(page);
1371 if (pte_young(ptent) &&
1372 likely(!(vma->vm_flags & VM_SEQ_READ)))
1373 mark_page_accessed(page);
1375 rss[mm_counter(page)]--;
1376 page_remove_rmap(page, false);
1377 if (unlikely(page_mapcount(page) < 0))
1378 print_bad_pte(vma, addr, ptent, page);
1379 if (unlikely(__tlb_remove_page(tlb, page))) {
1387 entry = pte_to_swp_entry(ptent);
1388 if (non_swap_entry(entry) && is_device_private_entry(entry)) {
1389 struct page *page = device_private_entry_to_page(entry);
1391 if (unlikely(details && details->check_mapping)) {
1393 * unmap_shared_mapping_pages() wants to
1394 * invalidate cache without truncating:
1395 * unmap shared but keep private pages.
1397 if (details->check_mapping !=
1398 page_rmapping(page))
1402 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1403 rss[mm_counter(page)]--;
1404 page_remove_rmap(page, false);
1409 entry = pte_to_swp_entry(ptent);
1410 if (!non_swap_entry(entry)) {
1411 /* Genuine swap entry, hence a private anon page */
1412 if (!should_zap_cows(details))
1415 } else if (is_migration_entry(entry)) {
1418 page = migration_entry_to_page(entry);
1419 if (details && details->check_mapping &&
1420 details->check_mapping != page_rmapping(page))
1422 rss[mm_counter(page)]--;
1424 if (unlikely(!free_swap_and_cache(entry)))
1425 print_bad_pte(vma, addr, ptent, NULL);
1426 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1427 } while (pte++, addr += PAGE_SIZE, addr != end);
1429 add_mm_rss_vec(mm, rss);
1430 arch_leave_lazy_mmu_mode();
1432 /* Do the actual TLB flush before dropping ptl */
1434 tlb_flush_mmu_tlbonly(tlb);
1435 pte_unmap_unlock(start_pte, ptl);
1438 * If we forced a TLB flush (either due to running out of
1439 * batch buffers or because we needed to flush dirty TLB
1440 * entries before releasing the ptl), free the batched
1441 * memory too. Restart if we didn't do everything.
1445 tlb_flush_mmu_free(tlb);
1453 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1454 struct vm_area_struct *vma, pud_t *pud,
1455 unsigned long addr, unsigned long end,
1456 struct zap_details *details)
1461 pmd = pmd_offset(pud, addr);
1463 next = pmd_addr_end(addr, end);
1464 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1465 if (next - addr != HPAGE_PMD_SIZE)
1466 __split_huge_pmd(vma, pmd, addr, false, NULL);
1467 else if (zap_huge_pmd(tlb, vma, pmd, addr))
1470 } else if (details && details->single_page &&
1471 PageTransCompound(details->single_page) &&
1472 next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) {
1473 spinlock_t *ptl = pmd_lock(tlb->mm, pmd);
1475 * Take and drop THP pmd lock so that we cannot return
1476 * prematurely, while zap_huge_pmd() has cleared *pmd,
1477 * but not yet decremented compound_mapcount().
1483 * Here there can be other concurrent MADV_DONTNEED or
1484 * trans huge page faults running, and if the pmd is
1485 * none or trans huge it can change under us. This is
1486 * because MADV_DONTNEED holds the mmap_sem in read
1489 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1491 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1494 } while (pmd++, addr = next, addr != end);
1499 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1500 struct vm_area_struct *vma, p4d_t *p4d,
1501 unsigned long addr, unsigned long end,
1502 struct zap_details *details)
1507 pud = pud_offset(p4d, addr);
1509 next = pud_addr_end(addr, end);
1510 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1511 if (next - addr != HPAGE_PUD_SIZE) {
1512 VM_BUG_ON_VMA(!rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1513 split_huge_pud(vma, pud, addr);
1514 } else if (zap_huge_pud(tlb, vma, pud, addr))
1518 if (pud_none_or_clear_bad(pud))
1520 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1523 } while (pud++, addr = next, addr != end);
1528 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1529 struct vm_area_struct *vma, pgd_t *pgd,
1530 unsigned long addr, unsigned long end,
1531 struct zap_details *details)
1536 p4d = p4d_offset(pgd, addr);
1538 next = p4d_addr_end(addr, end);
1539 if (p4d_none_or_clear_bad(p4d))
1541 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1542 } while (p4d++, addr = next, addr != end);
1547 void unmap_page_range(struct mmu_gather *tlb,
1548 struct vm_area_struct *vma,
1549 unsigned long addr, unsigned long end,
1550 struct zap_details *details)
1555 BUG_ON(addr >= end);
1556 tlb_start_vma(tlb, vma);
1557 pgd = pgd_offset(vma->vm_mm, addr);
1559 next = pgd_addr_end(addr, end);
1560 if (pgd_none_or_clear_bad(pgd))
1562 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1563 } while (pgd++, addr = next, addr != end);
1564 tlb_end_vma(tlb, vma);
1568 static void unmap_single_vma(struct mmu_gather *tlb,
1569 struct vm_area_struct *vma, unsigned long start_addr,
1570 unsigned long end_addr,
1571 struct zap_details *details)
1573 unsigned long start = max(vma->vm_start, start_addr);
1576 if (start >= vma->vm_end)
1578 end = min(vma->vm_end, end_addr);
1579 if (end <= vma->vm_start)
1583 uprobe_munmap(vma, start, end);
1585 if (unlikely(vma->vm_flags & VM_PFNMAP))
1586 untrack_pfn(vma, 0, 0);
1589 if (unlikely(is_vm_hugetlb_page(vma))) {
1591 * It is undesirable to test vma->vm_file as it
1592 * should be non-null for valid hugetlb area.
1593 * However, vm_file will be NULL in the error
1594 * cleanup path of mmap_region. When
1595 * hugetlbfs ->mmap method fails,
1596 * mmap_region() nullifies vma->vm_file
1597 * before calling this function to clean up.
1598 * Since no pte has actually been setup, it is
1599 * safe to do nothing in this case.
1602 i_mmap_lock_write(vma->vm_file->f_mapping);
1603 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1604 i_mmap_unlock_write(vma->vm_file->f_mapping);
1607 unmap_page_range(tlb, vma, start, end, details);
1612 * unmap_vmas - unmap a range of memory covered by a list of vma's
1613 * @tlb: address of the caller's struct mmu_gather
1614 * @vma: the starting vma
1615 * @start_addr: virtual address at which to start unmapping
1616 * @end_addr: virtual address at which to end unmapping
1618 * Unmap all pages in the vma list.
1620 * Only addresses between `start' and `end' will be unmapped.
1622 * The VMA list must be sorted in ascending virtual address order.
1624 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1625 * range after unmap_vmas() returns. So the only responsibility here is to
1626 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1627 * drops the lock and schedules.
1629 void unmap_vmas(struct mmu_gather *tlb,
1630 struct vm_area_struct *vma, unsigned long start_addr,
1631 unsigned long end_addr)
1633 struct mm_struct *mm = vma->vm_mm;
1635 mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1636 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1637 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1638 mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
1642 * zap_page_range - remove user pages in a given range
1643 * @vma: vm_area_struct holding the applicable pages
1644 * @start: starting address of pages to zap
1645 * @size: number of bytes to zap
1647 * Caller must protect the VMA list
1649 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1652 struct mm_struct *mm = vma->vm_mm;
1653 struct mmu_gather tlb;
1654 unsigned long end = start + size;
1657 tlb_gather_mmu(&tlb, mm, start, end);
1658 update_hiwater_rss(mm);
1659 mmu_notifier_invalidate_range_start(mm, start, end);
1660 for ( ; vma && vma->vm_start < end; vma = vma->vm_next)
1661 unmap_single_vma(&tlb, vma, start, end, NULL);
1662 mmu_notifier_invalidate_range_end(mm, start, end);
1663 tlb_finish_mmu(&tlb, start, end);
1667 * zap_page_range_single - remove user pages in a given range
1668 * @vma: vm_area_struct holding the applicable pages
1669 * @address: starting address of pages to zap
1670 * @size: number of bytes to zap
1671 * @details: details of shared cache invalidation
1673 * The range must fit into one VMA.
1675 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1676 unsigned long size, struct zap_details *details)
1678 struct mm_struct *mm = vma->vm_mm;
1679 struct mmu_gather tlb;
1680 unsigned long end = address + size;
1683 tlb_gather_mmu(&tlb, mm, address, end);
1684 update_hiwater_rss(mm);
1685 mmu_notifier_invalidate_range_start(mm, address, end);
1686 unmap_single_vma(&tlb, vma, address, end, details);
1687 mmu_notifier_invalidate_range_end(mm, address, end);
1688 tlb_finish_mmu(&tlb, address, end);
1692 * zap_vma_ptes - remove ptes mapping the vma
1693 * @vma: vm_area_struct holding ptes to be zapped
1694 * @address: starting address of pages to zap
1695 * @size: number of bytes to zap
1697 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1699 * The entire address range must be fully contained within the vma.
1702 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1705 if (address < vma->vm_start || address + size > vma->vm_end ||
1706 !(vma->vm_flags & VM_PFNMAP))
1709 zap_page_range_single(vma, address, size, NULL);
1711 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1713 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1721 pgd = pgd_offset(mm, addr);
1722 p4d = p4d_alloc(mm, pgd, addr);
1725 pud = pud_alloc(mm, p4d, addr);
1728 pmd = pmd_alloc(mm, pud, addr);
1732 VM_BUG_ON(pmd_trans_huge(*pmd));
1733 return pte_alloc_map_lock(mm, pmd, addr, ptl);
1737 * This is the old fallback for page remapping.
1739 * For historical reasons, it only allows reserved pages. Only
1740 * old drivers should use this, and they needed to mark their
1741 * pages reserved for the old functions anyway.
1743 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1744 struct page *page, pgprot_t prot)
1746 struct mm_struct *mm = vma->vm_mm;
1755 flush_dcache_page(page);
1756 pte = get_locked_pte(mm, addr, &ptl);
1760 if (!pte_none(*pte))
1763 /* Ok, finally just insert the thing.. */
1765 inc_mm_counter_fast(mm, mm_counter_file(page));
1766 page_add_file_rmap(page, false);
1767 set_pte_at(mm, addr, pte, mk_pte(page, prot));
1770 pte_unmap_unlock(pte, ptl);
1773 pte_unmap_unlock(pte, ptl);
1779 * vm_insert_page - insert single page into user vma
1780 * @vma: user vma to map to
1781 * @addr: target user address of this page
1782 * @page: source kernel page
1784 * This allows drivers to insert individual pages they've allocated
1787 * The page has to be a nice clean _individual_ kernel allocation.
1788 * If you allocate a compound page, you need to have marked it as
1789 * such (__GFP_COMP), or manually just split the page up yourself
1790 * (see split_page()).
1792 * NOTE! Traditionally this was done with "remap_pfn_range()" which
1793 * took an arbitrary page protection parameter. This doesn't allow
1794 * that. Your vma protection will have to be set up correctly, which
1795 * means that if you want a shared writable mapping, you'd better
1796 * ask for a shared writable mapping!
1798 * The page does not need to be reserved.
1800 * Usually this function is called from f_op->mmap() handler
1801 * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
1802 * Caller must set VM_MIXEDMAP on vma if it wants to call this
1803 * function from other places, for example from page-fault handler.
1805 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1808 if (addr < vma->vm_start || addr >= vma->vm_end)
1810 if (!page_count(page))
1812 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1813 BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
1814 BUG_ON(vma->vm_flags & VM_PFNMAP);
1815 vma->vm_flags |= VM_MIXEDMAP;
1817 return insert_page(vma, addr, page, vma->vm_page_prot);
1819 EXPORT_SYMBOL(vm_insert_page);
1821 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1822 pfn_t pfn, pgprot_t prot, bool mkwrite)
1824 struct mm_struct *mm = vma->vm_mm;
1830 pte = get_locked_pte(mm, addr, &ptl);
1834 if (!pte_none(*pte)) {
1837 * For read faults on private mappings the PFN passed
1838 * in may not match the PFN we have mapped if the
1839 * mapped PFN is a writeable COW page. In the mkwrite
1840 * case we are creating a writable PTE for a shared
1841 * mapping and we expect the PFNs to match. If they
1842 * don't match, we are likely racing with block
1843 * allocation and mapping invalidation so just skip the
1846 if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
1847 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
1850 entry = pte_mkyoung(*pte);
1851 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1852 if (ptep_set_access_flags(vma, addr, pte, entry, 1))
1853 update_mmu_cache(vma, addr, pte);
1858 /* Ok, finally just insert the thing.. */
1859 if (pfn_t_devmap(pfn))
1860 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
1862 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1865 entry = pte_mkyoung(entry);
1866 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
1869 set_pte_at(mm, addr, pte, entry);
1870 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1874 pte_unmap_unlock(pte, ptl);
1880 * vm_insert_pfn - insert single pfn into user vma
1881 * @vma: user vma to map to
1882 * @addr: target user address of this page
1883 * @pfn: source kernel pfn
1885 * Similar to vm_insert_page, this allows drivers to insert individual pages
1886 * they've allocated into a user vma. Same comments apply.
1888 * This function should only be called from a vm_ops->fault handler, and
1889 * in that case the handler should return NULL.
1891 * vma cannot be a COW mapping.
1893 * As this is called only for pages that do not currently exist, we
1894 * do not need to flush old virtual caches or the TLB.
1896 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1899 return vm_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
1901 EXPORT_SYMBOL(vm_insert_pfn);
1904 * vm_insert_pfn_prot - insert single pfn into user vma with specified pgprot
1905 * @vma: user vma to map to
1906 * @addr: target user address of this page
1907 * @pfn: source kernel pfn
1908 * @pgprot: pgprot flags for the inserted page
1910 * This is exactly like vm_insert_pfn, except that it allows drivers to
1911 * to override pgprot on a per-page basis.
1913 * This only makes sense for IO mappings, and it makes no sense for
1914 * cow mappings. In general, using multiple vmas is preferable;
1915 * vm_insert_pfn_prot should only be used if using multiple VMAs is
1918 int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
1919 unsigned long pfn, pgprot_t pgprot)
1923 * Technically, architectures with pte_special can avoid all these
1924 * restrictions (same for remap_pfn_range). However we would like
1925 * consistency in testing and feature parity among all, so we should
1926 * try to keep these invariants in place for everybody.
1928 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1929 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1930 (VM_PFNMAP|VM_MIXEDMAP));
1931 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1932 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1934 if (addr < vma->vm_start || addr >= vma->vm_end)
1937 if (!pfn_modify_allowed(pfn, pgprot))
1940 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
1942 ret = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
1947 EXPORT_SYMBOL(vm_insert_pfn_prot);
1949 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn)
1951 /* these checks mirror the abort conditions in vm_normal_page */
1952 if (vma->vm_flags & VM_MIXEDMAP)
1954 if (pfn_t_devmap(pfn))
1956 if (pfn_t_special(pfn))
1958 if (is_zero_pfn(pfn_t_to_pfn(pfn)))
1963 static int __vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1964 pfn_t pfn, bool mkwrite)
1966 pgprot_t pgprot = vma->vm_page_prot;
1968 BUG_ON(!vm_mixed_ok(vma, pfn));
1970 if (addr < vma->vm_start || addr >= vma->vm_end)
1973 track_pfn_insert(vma, &pgprot, pfn);
1975 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
1979 * If we don't have pte special, then we have to use the pfn_valid()
1980 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1981 * refcount the page if pfn_valid is true (hence insert_page rather
1982 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
1983 * without pte special, it would there be refcounted as a normal page.
1985 if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
1986 !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1990 * At this point we are committed to insert_page()
1991 * regardless of whether the caller specified flags that
1992 * result in pfn_t_has_page() == false.
1994 page = pfn_to_page(pfn_t_to_pfn(pfn));
1995 return insert_page(vma, addr, page, pgprot);
1997 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2000 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2003 return __vm_insert_mixed(vma, addr, pfn, false);
2006 EXPORT_SYMBOL(vm_insert_mixed);
2009 * If the insertion of PTE failed because someone else already added a
2010 * different entry in the mean time, we treat that as success as we assume
2011 * the same entry was actually inserted.
2014 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2015 unsigned long addr, pfn_t pfn)
2019 err = __vm_insert_mixed(vma, addr, pfn, true);
2021 return VM_FAULT_OOM;
2022 if (err < 0 && err != -EBUSY)
2023 return VM_FAULT_SIGBUS;
2024 return VM_FAULT_NOPAGE;
2026 EXPORT_SYMBOL(vmf_insert_mixed_mkwrite);
2029 * maps a range of physical memory into the requested pages. the old
2030 * mappings are removed. any references to nonexistent pages results
2031 * in null mappings (currently treated as "copy-on-access")
2033 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2034 unsigned long addr, unsigned long end,
2035 unsigned long pfn, pgprot_t prot)
2037 pte_t *pte, *mapped_pte;
2041 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2044 arch_enter_lazy_mmu_mode();
2046 BUG_ON(!pte_none(*pte));
2047 if (!pfn_modify_allowed(pfn, prot)) {
2051 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2053 } while (pte++, addr += PAGE_SIZE, addr != end);
2054 arch_leave_lazy_mmu_mode();
2055 pte_unmap_unlock(mapped_pte, ptl);
2059 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2060 unsigned long addr, unsigned long end,
2061 unsigned long pfn, pgprot_t prot)
2067 pfn -= addr >> PAGE_SHIFT;
2068 pmd = pmd_alloc(mm, pud, addr);
2071 VM_BUG_ON(pmd_trans_huge(*pmd));
2073 next = pmd_addr_end(addr, end);
2074 err = remap_pte_range(mm, pmd, addr, next,
2075 pfn + (addr >> PAGE_SHIFT), prot);
2078 } while (pmd++, addr = next, addr != end);
2082 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2083 unsigned long addr, unsigned long end,
2084 unsigned long pfn, pgprot_t prot)
2090 pfn -= addr >> PAGE_SHIFT;
2091 pud = pud_alloc(mm, p4d, addr);
2095 next = pud_addr_end(addr, end);
2096 err = remap_pmd_range(mm, pud, addr, next,
2097 pfn + (addr >> PAGE_SHIFT), prot);
2100 } while (pud++, addr = next, addr != end);
2104 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2105 unsigned long addr, unsigned long end,
2106 unsigned long pfn, pgprot_t prot)
2112 pfn -= addr >> PAGE_SHIFT;
2113 p4d = p4d_alloc(mm, pgd, addr);
2117 next = p4d_addr_end(addr, end);
2118 err = remap_pud_range(mm, p4d, addr, next,
2119 pfn + (addr >> PAGE_SHIFT), prot);
2122 } while (p4d++, addr = next, addr != end);
2127 * remap_pfn_range - remap kernel memory to userspace
2128 * @vma: user vma to map to
2129 * @addr: target user address to start at
2130 * @pfn: physical address of kernel memory
2131 * @size: size of map area
2132 * @prot: page protection flags for this mapping
2134 * Note: this is only safe if the mm semaphore is held when called.
2136 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2137 unsigned long pfn, unsigned long size, pgprot_t prot)
2141 unsigned long end = addr + PAGE_ALIGN(size);
2142 struct mm_struct *mm = vma->vm_mm;
2143 unsigned long remap_pfn = pfn;
2147 * Physically remapped pages are special. Tell the
2148 * rest of the world about it:
2149 * VM_IO tells people not to look at these pages
2150 * (accesses can have side effects).
2151 * VM_PFNMAP tells the core MM that the base pages are just
2152 * raw PFN mappings, and do not have a "struct page" associated
2155 * Disable vma merging and expanding with mremap().
2157 * Omit vma from core dump, even when VM_IO turned off.
2159 * There's a horrible special case to handle copy-on-write
2160 * behaviour that some programs depend on. We mark the "original"
2161 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2162 * See vm_normal_page() for details.
2164 if (is_cow_mapping(vma->vm_flags)) {
2165 if (addr != vma->vm_start || end != vma->vm_end)
2167 vma->vm_pgoff = pfn;
2170 err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
2174 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2176 BUG_ON(addr >= end);
2177 pfn -= addr >> PAGE_SHIFT;
2178 pgd = pgd_offset(mm, addr);
2179 flush_cache_range(vma, addr, end);
2181 next = pgd_addr_end(addr, end);
2182 err = remap_p4d_range(mm, pgd, addr, next,
2183 pfn + (addr >> PAGE_SHIFT), prot);
2186 } while (pgd++, addr = next, addr != end);
2189 untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
2193 EXPORT_SYMBOL(remap_pfn_range);
2196 * vm_iomap_memory - remap memory to userspace
2197 * @vma: user vma to map to
2198 * @start: start of area
2199 * @len: size of area
2201 * This is a simplified io_remap_pfn_range() for common driver use. The
2202 * driver just needs to give us the physical memory range to be mapped,
2203 * we'll figure out the rest from the vma information.
2205 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2206 * whatever write-combining details or similar.
2208 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2210 unsigned long vm_len, pfn, pages;
2212 /* Check that the physical memory area passed in looks valid */
2213 if (start + len < start)
2216 * You *really* shouldn't map things that aren't page-aligned,
2217 * but we've historically allowed it because IO memory might
2218 * just have smaller alignment.
2220 len += start & ~PAGE_MASK;
2221 pfn = start >> PAGE_SHIFT;
2222 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2223 if (pfn + pages < pfn)
2226 /* We start the mapping 'vm_pgoff' pages into the area */
2227 if (vma->vm_pgoff > pages)
2229 pfn += vma->vm_pgoff;
2230 pages -= vma->vm_pgoff;
2232 /* Can we fit all of the mapping? */
2233 vm_len = vma->vm_end - vma->vm_start;
2234 if (vm_len >> PAGE_SHIFT > pages)
2237 /* Ok, let it rip */
2238 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2240 EXPORT_SYMBOL(vm_iomap_memory);
2242 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2243 unsigned long addr, unsigned long end,
2244 pte_fn_t fn, void *data)
2249 spinlock_t *uninitialized_var(ptl);
2251 pte = (mm == &init_mm) ?
2252 pte_alloc_kernel(pmd, addr) :
2253 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2257 BUG_ON(pmd_huge(*pmd));
2259 arch_enter_lazy_mmu_mode();
2261 token = pmd_pgtable(*pmd);
2264 err = fn(pte++, token, addr, data);
2267 } while (addr += PAGE_SIZE, addr != end);
2269 arch_leave_lazy_mmu_mode();
2272 pte_unmap_unlock(pte-1, ptl);
2276 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2277 unsigned long addr, unsigned long end,
2278 pte_fn_t fn, void *data)
2284 BUG_ON(pud_huge(*pud));
2286 pmd = pmd_alloc(mm, pud, addr);
2290 next = pmd_addr_end(addr, end);
2291 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
2294 } while (pmd++, addr = next, addr != end);
2298 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2299 unsigned long addr, unsigned long end,
2300 pte_fn_t fn, void *data)
2306 pud = pud_alloc(mm, p4d, addr);
2310 next = pud_addr_end(addr, end);
2311 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
2314 } while (pud++, addr = next, addr != end);
2318 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2319 unsigned long addr, unsigned long end,
2320 pte_fn_t fn, void *data)
2326 p4d = p4d_alloc(mm, pgd, addr);
2330 next = p4d_addr_end(addr, end);
2331 err = apply_to_pud_range(mm, p4d, addr, next, fn, data);
2334 } while (p4d++, addr = next, addr != end);
2339 * Scan a region of virtual memory, filling in page tables as necessary
2340 * and calling a provided function on each leaf page table.
2342 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2343 unsigned long size, pte_fn_t fn, void *data)
2347 unsigned long end = addr + size;
2350 if (WARN_ON(addr >= end))
2353 pgd = pgd_offset(mm, addr);
2355 next = pgd_addr_end(addr, end);
2356 err = apply_to_p4d_range(mm, pgd, addr, next, fn, data);
2359 } while (pgd++, addr = next, addr != end);
2363 EXPORT_SYMBOL_GPL(apply_to_page_range);
2366 * handle_pte_fault chooses page fault handler according to an entry which was
2367 * read non-atomically. Before making any commitment, on those architectures
2368 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2369 * parts, do_swap_page must check under lock before unmapping the pte and
2370 * proceeding (but do_wp_page is only called after already making such a check;
2371 * and do_anonymous_page can safely check later on).
2373 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2374 pte_t *page_table, pte_t orig_pte)
2377 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
2378 if (sizeof(pte_t) > sizeof(unsigned long)) {
2379 spinlock_t *ptl = pte_lockptr(mm, pmd);
2381 same = pte_same(*page_table, orig_pte);
2385 pte_unmap(page_table);
2389 static inline bool cow_user_page(struct page *dst, struct page *src,
2390 struct vm_fault *vmf)
2395 bool locked = false;
2396 struct vm_area_struct *vma = vmf->vma;
2397 struct mm_struct *mm = vma->vm_mm;
2398 unsigned long addr = vmf->address;
2400 debug_dma_assert_idle(src);
2403 copy_user_highpage(dst, src, addr, vma);
2408 * If the source page was a PFN mapping, we don't have
2409 * a "struct page" for it. We do a best-effort copy by
2410 * just copying from the original user address. If that
2411 * fails, we just zero-fill it. Live with it.
2413 kaddr = kmap_atomic(dst);
2414 uaddr = (void __user *)(addr & PAGE_MASK);
2417 * On architectures with software "accessed" bits, we would
2418 * take a double page fault, so mark it accessed here.
2420 if (arch_faults_on_old_pte() && !pte_young(vmf->orig_pte)) {
2423 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2425 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2427 * Other thread has already handled the fault
2428 * and we don't need to do anything. If it's
2429 * not the case, the fault will be triggered
2430 * again on the same address.
2436 entry = pte_mkyoung(vmf->orig_pte);
2437 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2438 update_mmu_cache(vma, addr, vmf->pte);
2442 * This really shouldn't fail, because the page is there
2443 * in the page tables. But it might just be unreadable,
2444 * in which case we just give up and fill the result with
2447 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2451 /* Re-validate under PTL if the page is still mapped */
2452 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2454 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2455 /* The PTE changed under us. Retry page fault. */
2461 * The same page can be mapped back since last copy attampt.
2462 * Try to copy again under PTL.
2464 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2466 * Give a warn in case there can be some obscure
2479 pte_unmap_unlock(vmf->pte, vmf->ptl);
2480 kunmap_atomic(kaddr);
2481 flush_dcache_page(dst);
2486 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2488 struct file *vm_file = vma->vm_file;
2491 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2494 * Special mappings (e.g. VDSO) do not have any file so fake
2495 * a default GFP_KERNEL for them.
2501 * Notify the address space that the page is about to become writable so that
2502 * it can prohibit this or wait for the page to get into an appropriate state.
2504 * We do this without the lock held, so that it can sleep if it needs to.
2506 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf)
2509 struct page *page = vmf->page;
2510 unsigned int old_flags = vmf->flags;
2512 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2514 ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2515 /* Restore original flags so that caller is not surprised */
2516 vmf->flags = old_flags;
2517 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2519 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2521 if (!page->mapping) {
2523 return 0; /* retry */
2525 ret |= VM_FAULT_LOCKED;
2527 VM_BUG_ON_PAGE(!PageLocked(page), page);
2532 * Handle dirtying of a page in shared file mapping on a write fault.
2534 * The function expects the page to be locked and unlocks it.
2536 static void fault_dirty_shared_page(struct vm_area_struct *vma,
2539 struct address_space *mapping;
2541 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2543 dirtied = set_page_dirty(page);
2544 VM_BUG_ON_PAGE(PageAnon(page), page);
2546 * Take a local copy of the address_space - page.mapping may be zeroed
2547 * by truncate after unlock_page(). The address_space itself remains
2548 * pinned by vma->vm_file's reference. We rely on unlock_page()'s
2549 * release semantics to prevent the compiler from undoing this copying.
2551 mapping = page_rmapping(page);
2554 if ((dirtied || page_mkwrite) && mapping) {
2556 * Some device drivers do not set page.mapping
2557 * but still dirty their pages
2559 balance_dirty_pages_ratelimited(mapping);
2563 file_update_time(vma->vm_file);
2567 * Handle write page faults for pages that can be reused in the current vma
2569 * This can happen either due to the mapping being with the VM_SHARED flag,
2570 * or due to us being the last reference standing to the page. In either
2571 * case, all we need to do here is to mark the page as writable and update
2572 * any related book-keeping.
2574 static inline void wp_page_reuse(struct vm_fault *vmf)
2575 __releases(vmf->ptl)
2577 struct vm_area_struct *vma = vmf->vma;
2578 struct page *page = vmf->page;
2581 * Clear the pages cpupid information as the existing
2582 * information potentially belongs to a now completely
2583 * unrelated process.
2586 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2588 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2589 entry = pte_mkyoung(vmf->orig_pte);
2590 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2591 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
2592 update_mmu_cache(vma, vmf->address, vmf->pte);
2593 pte_unmap_unlock(vmf->pte, vmf->ptl);
2597 * Handle the case of a page which we actually need to copy to a new page.
2599 * Called with mmap_sem locked and the old page referenced, but
2600 * without the ptl held.
2602 * High level logic flow:
2604 * - Allocate a page, copy the content of the old page to the new one.
2605 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2606 * - Take the PTL. If the pte changed, bail out and release the allocated page
2607 * - If the pte is still the way we remember it, update the page table and all
2608 * relevant references. This includes dropping the reference the page-table
2609 * held to the old page, as well as updating the rmap.
2610 * - In any case, unlock the PTL and drop the reference we took to the old page.
2612 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
2614 struct vm_area_struct *vma = vmf->vma;
2615 struct mm_struct *mm = vma->vm_mm;
2616 struct page *old_page = vmf->page;
2617 struct page *new_page = NULL;
2619 int page_copied = 0;
2620 const unsigned long mmun_start = vmf->address & PAGE_MASK;
2621 const unsigned long mmun_end = mmun_start + PAGE_SIZE;
2622 struct mem_cgroup *memcg;
2624 if (unlikely(anon_vma_prepare(vma)))
2627 if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
2628 new_page = alloc_zeroed_user_highpage_movable(vma,
2633 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2638 if (!cow_user_page(new_page, old_page, vmf)) {
2640 * COW failed, if the fault was solved by other,
2641 * it's fine. If not, userspace would re-fault on
2642 * the same address and we will handle the fault
2643 * from the second attempt.
2652 if (mem_cgroup_try_charge_delay(new_page, mm, GFP_KERNEL, &memcg, false))
2655 __SetPageUptodate(new_page);
2657 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2660 * Re-check the pte - we dropped the lock
2662 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
2663 if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2665 if (!PageAnon(old_page)) {
2666 dec_mm_counter_fast(mm,
2667 mm_counter_file(old_page));
2668 inc_mm_counter_fast(mm, MM_ANONPAGES);
2671 inc_mm_counter_fast(mm, MM_ANONPAGES);
2673 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2674 entry = mk_pte(new_page, vma->vm_page_prot);
2675 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2677 * Clear the pte entry and flush it first, before updating the
2678 * pte with the new entry. This will avoid a race condition
2679 * seen in the presence of one thread doing SMC and another
2682 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
2683 page_add_new_anon_rmap(new_page, vma, vmf->address, false);
2684 mem_cgroup_commit_charge(new_page, memcg, false, false);
2685 lru_cache_add_active_or_unevictable(new_page, vma);
2687 * We call the notify macro here because, when using secondary
2688 * mmu page tables (such as kvm shadow page tables), we want the
2689 * new page to be mapped directly into the secondary page table.
2691 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
2692 update_mmu_cache(vma, vmf->address, vmf->pte);
2695 * Only after switching the pte to the new page may
2696 * we remove the mapcount here. Otherwise another
2697 * process may come and find the rmap count decremented
2698 * before the pte is switched to the new page, and
2699 * "reuse" the old page writing into it while our pte
2700 * here still points into it and can be read by other
2703 * The critical issue is to order this
2704 * page_remove_rmap with the ptp_clear_flush above.
2705 * Those stores are ordered by (if nothing else,)
2706 * the barrier present in the atomic_add_negative
2707 * in page_remove_rmap.
2709 * Then the TLB flush in ptep_clear_flush ensures that
2710 * no process can access the old page before the
2711 * decremented mapcount is visible. And the old page
2712 * cannot be reused until after the decremented
2713 * mapcount is visible. So transitively, TLBs to
2714 * old page will be flushed before it can be reused.
2716 page_remove_rmap(old_page, false);
2719 /* Free the old page.. */
2720 new_page = old_page;
2723 mem_cgroup_cancel_charge(new_page, memcg, false);
2729 pte_unmap_unlock(vmf->pte, vmf->ptl);
2731 * No need to double call mmu_notifier->invalidate_range() callback as
2732 * the above ptep_clear_flush_notify() did already call it.
2734 mmu_notifier_invalidate_range_only_end(mm, mmun_start, mmun_end);
2737 * Don't let another task, with possibly unlocked vma,
2738 * keep the mlocked page.
2740 if (page_copied && (vma->vm_flags & VM_LOCKED)) {
2741 lock_page(old_page); /* LRU manipulation */
2742 if (PageMlocked(old_page))
2743 munlock_vma_page(old_page);
2744 unlock_page(old_page);
2748 return page_copied ? VM_FAULT_WRITE : 0;
2754 return VM_FAULT_OOM;
2758 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
2759 * writeable once the page is prepared
2761 * @vmf: structure describing the fault
2763 * This function handles all that is needed to finish a write page fault in a
2764 * shared mapping due to PTE being read-only once the mapped page is prepared.
2765 * It handles locking of PTE and modifying it. The function returns
2766 * VM_FAULT_WRITE on success, 0 when PTE got changed before we acquired PTE
2769 * The function expects the page to be locked or other protection against
2770 * concurrent faults / writeback (such as DAX radix tree locks).
2772 vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf)
2774 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
2775 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
2778 * We might have raced with another page fault while we released the
2779 * pte_offset_map_lock.
2781 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2782 pte_unmap_unlock(vmf->pte, vmf->ptl);
2783 return VM_FAULT_NOPAGE;
2790 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2793 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
2795 struct vm_area_struct *vma = vmf->vma;
2797 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2800 pte_unmap_unlock(vmf->pte, vmf->ptl);
2801 vmf->flags |= FAULT_FLAG_MKWRITE;
2802 ret = vma->vm_ops->pfn_mkwrite(vmf);
2803 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
2805 return finish_mkwrite_fault(vmf);
2808 return VM_FAULT_WRITE;
2811 static vm_fault_t wp_page_shared(struct vm_fault *vmf)
2812 __releases(vmf->ptl)
2814 struct vm_area_struct *vma = vmf->vma;
2816 get_page(vmf->page);
2818 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2821 pte_unmap_unlock(vmf->pte, vmf->ptl);
2822 tmp = do_page_mkwrite(vmf);
2823 if (unlikely(!tmp || (tmp &
2824 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
2825 put_page(vmf->page);
2828 tmp = finish_mkwrite_fault(vmf);
2829 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
2830 unlock_page(vmf->page);
2831 put_page(vmf->page);
2836 lock_page(vmf->page);
2838 fault_dirty_shared_page(vma, vmf->page);
2839 put_page(vmf->page);
2841 return VM_FAULT_WRITE;
2845 * This routine handles present pages, when users try to write
2846 * to a shared page. It is done by copying the page to a new address
2847 * and decrementing the shared-page counter for the old page.
2849 * Note that this routine assumes that the protection checks have been
2850 * done by the caller (the low-level page fault routine in most cases).
2851 * Thus we can safely just mark it writable once we've done any necessary
2854 * We also mark the page dirty at this point even though the page will
2855 * change only once the write actually happens. This avoids a few races,
2856 * and potentially makes it more efficient.
2858 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2859 * but allow concurrent faults), with pte both mapped and locked.
2860 * We return with mmap_sem still held, but pte unmapped and unlocked.
2862 static vm_fault_t do_wp_page(struct vm_fault *vmf)
2863 __releases(vmf->ptl)
2865 struct vm_area_struct *vma = vmf->vma;
2867 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
2870 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
2873 * We should not cow pages in a shared writeable mapping.
2874 * Just mark the pages writable and/or call ops->pfn_mkwrite.
2876 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2877 (VM_WRITE|VM_SHARED))
2878 return wp_pfn_shared(vmf);
2880 pte_unmap_unlock(vmf->pte, vmf->ptl);
2881 return wp_page_copy(vmf);
2885 * Take out anonymous pages first, anonymous shared vmas are
2886 * not dirty accountable.
2888 if (PageAnon(vmf->page) && !PageKsm(vmf->page)) {
2889 int total_map_swapcount;
2890 if (!trylock_page(vmf->page)) {
2891 get_page(vmf->page);
2892 pte_unmap_unlock(vmf->pte, vmf->ptl);
2893 lock_page(vmf->page);
2894 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
2895 vmf->address, &vmf->ptl);
2896 if (!pte_same(*vmf->pte, vmf->orig_pte)) {
2897 unlock_page(vmf->page);
2898 pte_unmap_unlock(vmf->pte, vmf->ptl);
2899 put_page(vmf->page);
2902 put_page(vmf->page);
2904 if (reuse_swap_page(vmf->page, &total_map_swapcount)) {
2905 if (total_map_swapcount == 1) {
2907 * The page is all ours. Move it to
2908 * our anon_vma so the rmap code will
2909 * not search our parent or siblings.
2910 * Protected against the rmap code by
2913 page_move_anon_rmap(vmf->page, vma);
2915 unlock_page(vmf->page);
2917 return VM_FAULT_WRITE;
2919 unlock_page(vmf->page);
2920 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2921 (VM_WRITE|VM_SHARED))) {
2922 return wp_page_shared(vmf);
2926 * Ok, we need to copy. Oh, well..
2928 get_page(vmf->page);
2930 pte_unmap_unlock(vmf->pte, vmf->ptl);
2931 return wp_page_copy(vmf);
2934 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2935 unsigned long start_addr, unsigned long end_addr,
2936 struct zap_details *details)
2938 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2941 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
2942 struct zap_details *details)
2944 struct vm_area_struct *vma;
2945 pgoff_t vba, vea, zba, zea;
2947 vma_interval_tree_foreach(vma, root,
2948 details->first_index, details->last_index) {
2950 vba = vma->vm_pgoff;
2951 vea = vba + vma_pages(vma) - 1;
2952 zba = details->first_index;
2955 zea = details->last_index;
2959 unmap_mapping_range_vma(vma,
2960 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2961 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2967 * unmap_mapping_page() - Unmap single page from processes.
2968 * @page: The locked page to be unmapped.
2970 * Unmap this page from any userspace process which still has it mmaped.
2971 * Typically, for efficiency, the range of nearby pages has already been
2972 * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once
2973 * truncation or invalidation holds the lock on a page, it may find that
2974 * the page has been remapped again: and then uses unmap_mapping_page()
2975 * to unmap it finally.
2977 void unmap_mapping_page(struct page *page)
2979 struct address_space *mapping = page->mapping;
2980 struct zap_details details = { };
2982 VM_BUG_ON(!PageLocked(page));
2983 VM_BUG_ON(PageTail(page));
2985 details.check_mapping = mapping;
2986 details.first_index = page->index;
2987 details.last_index = page->index + hpage_nr_pages(page) - 1;
2988 details.single_page = page;
2990 i_mmap_lock_write(mapping);
2991 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
2992 unmap_mapping_range_tree(&mapping->i_mmap, &details);
2993 i_mmap_unlock_write(mapping);
2997 * unmap_mapping_pages() - Unmap pages from processes.
2998 * @mapping: The address space containing pages to be unmapped.
2999 * @start: Index of first page to be unmapped.
3000 * @nr: Number of pages to be unmapped. 0 to unmap to end of file.
3001 * @even_cows: Whether to unmap even private COWed pages.
3003 * Unmap the pages in this address space from any userspace process which
3004 * has them mmaped. Generally, you want to remove COWed pages as well when
3005 * a file is being truncated, but not when invalidating pages from the page
3008 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
3009 pgoff_t nr, bool even_cows)
3011 struct zap_details details = { };
3013 details.check_mapping = even_cows ? NULL : mapping;
3014 details.first_index = start;
3015 details.last_index = start + nr - 1;
3016 if (details.last_index < details.first_index)
3017 details.last_index = ULONG_MAX;
3019 i_mmap_lock_write(mapping);
3020 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3021 unmap_mapping_range_tree(&mapping->i_mmap, &details);
3022 i_mmap_unlock_write(mapping);
3026 * unmap_mapping_range - unmap the portion of all mmaps in the specified
3027 * address_space corresponding to the specified byte range in the underlying
3030 * @mapping: the address space containing mmaps to be unmapped.
3031 * @holebegin: byte in first page to unmap, relative to the start of
3032 * the underlying file. This will be rounded down to a PAGE_SIZE
3033 * boundary. Note that this is different from truncate_pagecache(), which
3034 * must keep the partial page. In contrast, we must get rid of
3036 * @holelen: size of prospective hole in bytes. This will be rounded
3037 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
3039 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3040 * but 0 when invalidating pagecache, don't throw away private data.
3042 void unmap_mapping_range(struct address_space *mapping,
3043 loff_t const holebegin, loff_t const holelen, int even_cows)
3045 pgoff_t hba = (pgoff_t)(holebegin) >> PAGE_SHIFT;
3046 pgoff_t hlen = ((pgoff_t)(holelen) + PAGE_SIZE - 1) >> PAGE_SHIFT;
3048 /* Check for overflow. */
3049 if (sizeof(holelen) > sizeof(hlen)) {
3051 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3052 if (holeend & ~(long long)ULONG_MAX)
3053 hlen = ULONG_MAX - hba + 1;
3056 unmap_mapping_pages(mapping, hba, hlen, even_cows);
3058 EXPORT_SYMBOL(unmap_mapping_range);
3061 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3062 * but allow concurrent faults), and pte mapped but not yet locked.
3063 * We return with pte unmapped and unlocked.
3065 * We return with the mmap_sem locked or unlocked in the same cases
3066 * as does filemap_fault().
3068 vm_fault_t do_swap_page(struct vm_fault *vmf)
3070 struct vm_area_struct *vma = vmf->vma;
3071 struct page *page = NULL, *swapcache;
3072 struct mem_cgroup *memcg;
3079 if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte))
3082 entry = pte_to_swp_entry(vmf->orig_pte);
3083 if (unlikely(non_swap_entry(entry))) {
3084 if (is_migration_entry(entry)) {
3085 migration_entry_wait(vma->vm_mm, vmf->pmd,
3087 } else if (is_device_private_entry(entry)) {
3089 * For un-addressable device memory we call the pgmap
3090 * fault handler callback. The callback must migrate
3091 * the page back to some CPU accessible page.
3093 ret = device_private_entry_fault(vma, vmf->address, entry,
3094 vmf->flags, vmf->pmd);
3095 } else if (is_hwpoison_entry(entry)) {
3096 ret = VM_FAULT_HWPOISON;
3098 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3099 ret = VM_FAULT_SIGBUS;
3105 delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3106 page = lookup_swap_cache(entry, vma, vmf->address);
3110 struct swap_info_struct *si = swp_swap_info(entry);
3112 if (si->flags & SWP_SYNCHRONOUS_IO &&
3113 __swap_count(si, entry) == 1) {
3114 /* skip swapcache */
3115 page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3118 __SetPageLocked(page);
3119 __SetPageSwapBacked(page);
3120 set_page_private(page, entry.val);
3121 lru_cache_add_anon(page);
3122 swap_readpage(page, true);
3125 page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3132 * Back out if somebody else faulted in this pte
3133 * while we released the pte lock.
3135 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3136 vmf->address, &vmf->ptl);
3137 if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3139 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3143 /* Had to read the page from swap area: Major fault */
3144 ret = VM_FAULT_MAJOR;
3145 count_vm_event(PGMAJFAULT);
3146 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3147 } else if (PageHWPoison(page)) {
3149 * hwpoisoned dirty swapcache pages are kept for killing
3150 * owner processes (which may be unknown at hwpoison time)
3152 ret = VM_FAULT_HWPOISON;
3153 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3157 locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3159 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3161 ret |= VM_FAULT_RETRY;
3166 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3167 * release the swapcache from under us. The page pin, and pte_same
3168 * test below, are not enough to exclude that. Even if it is still
3169 * swapcache, we need to check that the page's swap has not changed.
3171 if (unlikely((!PageSwapCache(page) ||
3172 page_private(page) != entry.val)) && swapcache)
3175 page = ksm_might_need_to_copy(page, vma, vmf->address);
3176 if (unlikely(!page)) {
3182 if (mem_cgroup_try_charge_delay(page, vma->vm_mm, GFP_KERNEL,
3189 * Back out if somebody else already faulted in this pte.
3191 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3193 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3196 if (unlikely(!PageUptodate(page))) {
3197 ret = VM_FAULT_SIGBUS;
3202 * The page isn't present yet, go ahead with the fault.
3204 * Be careful about the sequence of operations here.
3205 * To get its accounting right, reuse_swap_page() must be called
3206 * while the page is counted on swap but not yet in mapcount i.e.
3207 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3208 * must be called after the swap_free(), or it will never succeed.
3211 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3212 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3213 pte = mk_pte(page, vma->vm_page_prot);
3214 if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3215 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3216 vmf->flags &= ~FAULT_FLAG_WRITE;
3217 ret |= VM_FAULT_WRITE;
3218 exclusive = RMAP_EXCLUSIVE;
3220 flush_icache_page(vma, page);
3221 if (pte_swp_soft_dirty(vmf->orig_pte))
3222 pte = pte_mksoft_dirty(pte);
3223 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3224 arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
3225 vmf->orig_pte = pte;
3227 /* ksm created a completely new copy */
3228 if (unlikely(page != swapcache && swapcache)) {
3229 page_add_new_anon_rmap(page, vma, vmf->address, false);
3230 mem_cgroup_commit_charge(page, memcg, false, false);
3231 lru_cache_add_active_or_unevictable(page, vma);
3233 do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3234 mem_cgroup_commit_charge(page, memcg, true, false);
3235 activate_page(page);
3239 if (mem_cgroup_swap_full(page) ||
3240 (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3241 try_to_free_swap(page);
3243 if (page != swapcache && swapcache) {
3245 * Hold the lock to avoid the swap entry to be reused
3246 * until we take the PT lock for the pte_same() check
3247 * (to avoid false positives from pte_same). For
3248 * further safety release the lock after the swap_free
3249 * so that the swap count won't change under a
3250 * parallel locked swapcache.
3252 unlock_page(swapcache);
3253 put_page(swapcache);
3256 if (vmf->flags & FAULT_FLAG_WRITE) {
3257 ret |= do_wp_page(vmf);
3258 if (ret & VM_FAULT_ERROR)
3259 ret &= VM_FAULT_ERROR;
3263 /* No need to invalidate - it was non-present before */
3264 update_mmu_cache(vma, vmf->address, vmf->pte);
3266 pte_unmap_unlock(vmf->pte, vmf->ptl);
3270 mem_cgroup_cancel_charge(page, memcg, false);
3271 pte_unmap_unlock(vmf->pte, vmf->ptl);
3276 if (page != swapcache && swapcache) {
3277 unlock_page(swapcache);
3278 put_page(swapcache);
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 vm_fault_t do_anonymous_page(struct vm_fault *vmf)
3290 struct vm_area_struct *vma = vmf->vma;
3291 struct mem_cgroup *memcg;
3296 /* File mapping without ->vm_ops ? */
3297 if (vma->vm_flags & VM_SHARED)
3298 return VM_FAULT_SIGBUS;
3301 * Use pte_alloc() instead of pte_alloc_map(). We can't run
3302 * pte_offset_map() on pmds where a huge pmd might be created
3303 * from a different thread.
3305 * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
3306 * parallel threads are excluded by other means.
3308 * Here we only have down_read(mmap_sem).
3310 if (pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))
3311 return VM_FAULT_OOM;
3313 /* See the comment in pte_alloc_one_map() */
3314 if (unlikely(pmd_trans_unstable(vmf->pmd)))
3317 /* Use the zero-page for reads */
3318 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3319 !mm_forbids_zeropage(vma->vm_mm)) {
3320 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3321 vma->vm_page_prot));
3322 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3323 vmf->address, &vmf->ptl);
3324 if (!pte_none(*vmf->pte))
3326 ret = check_stable_address_space(vma->vm_mm);
3329 /* Deliver the page fault to userland, check inside PT lock */
3330 if (userfaultfd_missing(vma)) {
3331 pte_unmap_unlock(vmf->pte, vmf->ptl);
3332 return handle_userfault(vmf, VM_UFFD_MISSING);
3337 /* Allocate our own private page. */
3338 if (unlikely(anon_vma_prepare(vma)))
3340 page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3344 if (mem_cgroup_try_charge_delay(page, vma->vm_mm, GFP_KERNEL, &memcg,
3349 * The memory barrier inside __SetPageUptodate makes sure that
3350 * preceeding stores to the page contents become visible before
3351 * the set_pte_at() write.
3353 __SetPageUptodate(page);
3355 entry = mk_pte(page, vma->vm_page_prot);
3356 if (vma->vm_flags & VM_WRITE)
3357 entry = pte_mkwrite(pte_mkdirty(entry));
3359 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3361 if (!pte_none(*vmf->pte))
3364 ret = check_stable_address_space(vma->vm_mm);
3368 /* Deliver the page fault to userland, check inside PT lock */
3369 if (userfaultfd_missing(vma)) {
3370 pte_unmap_unlock(vmf->pte, vmf->ptl);
3371 mem_cgroup_cancel_charge(page, memcg, false);
3373 return handle_userfault(vmf, VM_UFFD_MISSING);
3376 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3377 page_add_new_anon_rmap(page, vma, vmf->address, false);
3378 mem_cgroup_commit_charge(page, memcg, false, false);
3379 lru_cache_add_active_or_unevictable(page, vma);
3381 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3383 /* No need to invalidate - it was non-present before */
3384 update_mmu_cache(vma, vmf->address, vmf->pte);
3386 pte_unmap_unlock(vmf->pte, vmf->ptl);
3389 mem_cgroup_cancel_charge(page, memcg, false);
3395 return VM_FAULT_OOM;
3399 * The mmap_sem must have been held on entry, and may have been
3400 * released depending on flags and vma->vm_ops->fault() return value.
3401 * See filemap_fault() and __lock_page_retry().
3403 static vm_fault_t __do_fault(struct vm_fault *vmf)
3405 struct vm_area_struct *vma = vmf->vma;
3409 * Preallocate pte before we take page_lock because this might lead to
3410 * deadlocks for memcg reclaim which waits for pages under writeback:
3412 * SetPageWriteback(A)
3418 * wait_on_page_writeback(A)
3419 * SetPageWriteback(B)
3421 * # flush A, B to clear the writeback
3423 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3424 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
3426 if (!vmf->prealloc_pte)
3427 return VM_FAULT_OOM;
3428 smp_wmb(); /* See comment in __pte_alloc() */
3431 ret = vma->vm_ops->fault(vmf);
3432 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3433 VM_FAULT_DONE_COW)))
3436 if (unlikely(PageHWPoison(vmf->page))) {
3437 struct page *page = vmf->page;
3438 vm_fault_t poisonret = VM_FAULT_HWPOISON;
3439 if (ret & VM_FAULT_LOCKED) {
3440 if (page_mapped(page))
3441 unmap_mapping_pages(page_mapping(page),
3442 page->index, 1, false);
3443 /* Retry if a clean page was removed from the cache. */
3444 if (invalidate_inode_page(page))
3445 poisonret = VM_FAULT_NOPAGE;
3453 if (unlikely(!(ret & VM_FAULT_LOCKED)))
3454 lock_page(vmf->page);
3456 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3462 * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3463 * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3464 * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3465 * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3467 static int pmd_devmap_trans_unstable(pmd_t *pmd)
3469 return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3472 static vm_fault_t pte_alloc_one_map(struct vm_fault *vmf)
3474 struct vm_area_struct *vma = vmf->vma;
3476 if (!pmd_none(*vmf->pmd))
3478 if (vmf->prealloc_pte) {
3479 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3480 if (unlikely(!pmd_none(*vmf->pmd))) {
3481 spin_unlock(vmf->ptl);
3485 mm_inc_nr_ptes(vma->vm_mm);
3486 pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3487 spin_unlock(vmf->ptl);
3488 vmf->prealloc_pte = NULL;
3489 } else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd, vmf->address))) {
3490 return VM_FAULT_OOM;
3494 * If a huge pmd materialized under us just retry later. Use
3495 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3496 * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3497 * under us and then back to pmd_none, as a result of MADV_DONTNEED
3498 * running immediately after a huge pmd fault in a different thread of
3499 * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3500 * All we have to ensure is that it is a regular pmd that we can walk
3501 * with pte_offset_map() and we can do that through an atomic read in
3502 * C, which is what pmd_trans_unstable() provides.
3504 if (pmd_devmap_trans_unstable(vmf->pmd))
3505 return VM_FAULT_NOPAGE;
3508 * At this point we know that our vmf->pmd points to a page of ptes
3509 * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3510 * for the duration of the fault. If a racing MADV_DONTNEED runs and
3511 * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3512 * be valid and we will re-check to make sure the vmf->pte isn't
3513 * pte_none() under vmf->ptl protection when we return to
3516 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3521 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
3523 #define HPAGE_CACHE_INDEX_MASK (HPAGE_PMD_NR - 1)
3524 static inline bool transhuge_vma_suitable(struct vm_area_struct *vma,
3525 unsigned long haddr)
3527 if (((vma->vm_start >> PAGE_SHIFT) & HPAGE_CACHE_INDEX_MASK) !=
3528 (vma->vm_pgoff & HPAGE_CACHE_INDEX_MASK))
3530 if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
3535 static void deposit_prealloc_pte(struct vm_fault *vmf)
3537 struct vm_area_struct *vma = vmf->vma;
3539 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3541 * We are going to consume the prealloc table,
3542 * count that as nr_ptes.
3544 mm_inc_nr_ptes(vma->vm_mm);
3545 vmf->prealloc_pte = NULL;
3548 static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3550 struct vm_area_struct *vma = vmf->vma;
3551 bool write = vmf->flags & FAULT_FLAG_WRITE;
3552 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3557 if (!transhuge_vma_suitable(vma, haddr))
3558 return VM_FAULT_FALLBACK;
3560 ret = VM_FAULT_FALLBACK;
3561 page = compound_head(page);
3564 * Archs like ppc64 need additonal space to store information
3565 * related to pte entry. Use the preallocated table for that.
3567 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3568 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm, vmf->address);
3569 if (!vmf->prealloc_pte)
3570 return VM_FAULT_OOM;
3571 smp_wmb(); /* See comment in __pte_alloc() */
3574 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3575 if (unlikely(!pmd_none(*vmf->pmd)))
3578 for (i = 0; i < HPAGE_PMD_NR; i++)
3579 flush_icache_page(vma, page + i);
3581 entry = mk_huge_pmd(page, vma->vm_page_prot);
3583 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3585 add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
3586 page_add_file_rmap(page, true);
3588 * deposit and withdraw with pmd lock held
3590 if (arch_needs_pgtable_deposit())
3591 deposit_prealloc_pte(vmf);
3593 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3595 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3597 /* fault is handled */
3599 count_vm_event(THP_FILE_MAPPED);
3601 spin_unlock(vmf->ptl);
3605 static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3613 * alloc_set_pte - setup new PTE entry for given page and add reverse page
3614 * mapping. If needed, the fucntion allocates page table or use pre-allocated.
3616 * @vmf: fault environment
3617 * @memcg: memcg to charge page (only for private mappings)
3618 * @page: page to map
3620 * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
3623 * Target users are page handler itself and implementations of
3624 * vm_ops->map_pages.
3626 vm_fault_t alloc_set_pte(struct vm_fault *vmf, struct mem_cgroup *memcg,
3629 struct vm_area_struct *vma = vmf->vma;
3630 bool write = vmf->flags & FAULT_FLAG_WRITE;
3634 if (pmd_none(*vmf->pmd) && PageTransCompound(page) &&
3635 IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
3637 VM_BUG_ON_PAGE(memcg, page);
3639 ret = do_set_pmd(vmf, page);
3640 if (ret != VM_FAULT_FALLBACK)
3645 ret = pte_alloc_one_map(vmf);
3650 /* Re-check under ptl */
3651 if (unlikely(!pte_none(*vmf->pte)))
3652 return VM_FAULT_NOPAGE;
3654 flush_icache_page(vma, page);
3655 entry = mk_pte(page, vma->vm_page_prot);
3657 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3658 /* copy-on-write page */
3659 if (write && !(vma->vm_flags & VM_SHARED)) {
3660 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3661 page_add_new_anon_rmap(page, vma, vmf->address, false);
3662 mem_cgroup_commit_charge(page, memcg, false, false);
3663 lru_cache_add_active_or_unevictable(page, vma);
3665 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3666 page_add_file_rmap(page, false);
3668 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3670 /* no need to invalidate: a not-present page won't be cached */
3671 update_mmu_cache(vma, vmf->address, vmf->pte);
3678 * finish_fault - finish page fault once we have prepared the page to fault
3680 * @vmf: structure describing the fault
3682 * This function handles all that is needed to finish a page fault once the
3683 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
3684 * given page, adds reverse page mapping, handles memcg charges and LRU
3685 * addition. The function returns 0 on success, VM_FAULT_ code in case of
3688 * The function expects the page to be locked and on success it consumes a
3689 * reference of a page being mapped (for the PTE which maps it).
3691 vm_fault_t finish_fault(struct vm_fault *vmf)
3696 /* Did we COW the page? */
3697 if ((vmf->flags & FAULT_FLAG_WRITE) &&
3698 !(vmf->vma->vm_flags & VM_SHARED))
3699 page = vmf->cow_page;
3704 * check even for read faults because we might have lost our CoWed
3707 if (!(vmf->vma->vm_flags & VM_SHARED))
3708 ret = check_stable_address_space(vmf->vma->vm_mm);
3710 ret = alloc_set_pte(vmf, vmf->memcg, page);
3712 pte_unmap_unlock(vmf->pte, vmf->ptl);
3716 static unsigned long fault_around_bytes __read_mostly =
3717 rounddown_pow_of_two(65536);
3719 #ifdef CONFIG_DEBUG_FS
3720 static int fault_around_bytes_get(void *data, u64 *val)
3722 *val = fault_around_bytes;
3727 * fault_around_bytes must be rounded down to the nearest page order as it's
3728 * what do_fault_around() expects to see.
3730 static int fault_around_bytes_set(void *data, u64 val)
3732 if (val / PAGE_SIZE > PTRS_PER_PTE)
3734 if (val > PAGE_SIZE)
3735 fault_around_bytes = rounddown_pow_of_two(val);
3737 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
3740 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
3741 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
3743 static int __init fault_around_debugfs(void)
3747 ret = debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
3748 &fault_around_bytes_fops);
3750 pr_warn("Failed to create fault_around_bytes in debugfs");
3753 late_initcall(fault_around_debugfs);
3757 * do_fault_around() tries to map few pages around the fault address. The hope
3758 * is that the pages will be needed soon and this will lower the number of
3761 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
3762 * not ready to be mapped: not up-to-date, locked, etc.
3764 * This function is called with the page table lock taken. In the split ptlock
3765 * case the page table lock only protects only those entries which belong to
3766 * the page table corresponding to the fault address.
3768 * This function doesn't cross the VMA boundaries, in order to call map_pages()
3771 * fault_around_bytes defines how many bytes we'll try to map.
3772 * do_fault_around() expects it to be set to a power of two less than or equal
3775 * The virtual address of the area that we map is naturally aligned to
3776 * fault_around_bytes rounded down to the machine page size
3777 * (and therefore to page order). This way it's easier to guarantee
3778 * that we don't cross page table boundaries.
3780 static vm_fault_t do_fault_around(struct vm_fault *vmf)
3782 unsigned long address = vmf->address, nr_pages, mask;
3783 pgoff_t start_pgoff = vmf->pgoff;
3788 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3789 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3791 vmf->address = max(address & mask, vmf->vma->vm_start);
3792 off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3796 * end_pgoff is either the end of the page table, the end of
3797 * the vma or nr_pages from start_pgoff, depending what is nearest.
3799 end_pgoff = start_pgoff -
3800 ((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
3802 end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
3803 start_pgoff + nr_pages - 1);
3805 if (pmd_none(*vmf->pmd)) {
3806 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm,
3808 if (!vmf->prealloc_pte)
3810 smp_wmb(); /* See comment in __pte_alloc() */
3813 vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
3815 /* Huge page is mapped? Page fault is solved */
3816 if (pmd_trans_huge(*vmf->pmd)) {
3817 ret = VM_FAULT_NOPAGE;
3821 /* ->map_pages() haven't done anything useful. Cold page cache? */
3825 /* check if the page fault is solved */
3826 vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
3827 if (!pte_none(*vmf->pte))
3828 ret = VM_FAULT_NOPAGE;
3829 pte_unmap_unlock(vmf->pte, vmf->ptl);
3831 vmf->address = address;
3836 static vm_fault_t do_read_fault(struct vm_fault *vmf)
3838 struct vm_area_struct *vma = vmf->vma;
3842 * Let's call ->map_pages() first and use ->fault() as fallback
3843 * if page by the offset is not ready to be mapped (cold cache or
3846 if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
3847 ret = do_fault_around(vmf);
3852 ret = __do_fault(vmf);
3853 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3856 ret |= finish_fault(vmf);
3857 unlock_page(vmf->page);
3858 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3859 put_page(vmf->page);
3863 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
3865 struct vm_area_struct *vma = vmf->vma;
3868 if (unlikely(anon_vma_prepare(vma)))
3869 return VM_FAULT_OOM;
3871 vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
3873 return VM_FAULT_OOM;
3875 if (mem_cgroup_try_charge_delay(vmf->cow_page, vma->vm_mm, GFP_KERNEL,
3876 &vmf->memcg, false)) {
3877 put_page(vmf->cow_page);
3878 return VM_FAULT_OOM;
3881 ret = __do_fault(vmf);
3882 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3884 if (ret & VM_FAULT_DONE_COW)
3887 copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
3888 __SetPageUptodate(vmf->cow_page);
3890 ret |= finish_fault(vmf);
3891 unlock_page(vmf->page);
3892 put_page(vmf->page);
3893 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3897 mem_cgroup_cancel_charge(vmf->cow_page, vmf->memcg, false);
3898 put_page(vmf->cow_page);
3902 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
3904 struct vm_area_struct *vma = vmf->vma;
3905 vm_fault_t ret, tmp;
3907 ret = __do_fault(vmf);
3908 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3912 * Check if the backing address space wants to know that the page is
3913 * about to become writable
3915 if (vma->vm_ops->page_mkwrite) {
3916 unlock_page(vmf->page);
3917 tmp = do_page_mkwrite(vmf);
3918 if (unlikely(!tmp ||
3919 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3920 put_page(vmf->page);
3925 ret |= finish_fault(vmf);
3926 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3928 unlock_page(vmf->page);
3929 put_page(vmf->page);
3933 fault_dirty_shared_page(vma, vmf->page);
3938 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3939 * but allow concurrent faults).
3940 * The mmap_sem may have been released depending on flags and our
3941 * return value. See filemap_fault() and __lock_page_or_retry().
3942 * If mmap_sem is released, vma may become invalid (for example
3943 * by other thread calling munmap()).
3945 static vm_fault_t do_fault(struct vm_fault *vmf)
3947 struct vm_area_struct *vma = vmf->vma;
3948 struct mm_struct *vm_mm = vma->vm_mm;
3952 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
3954 if (!vma->vm_ops->fault) {
3956 * If we find a migration pmd entry or a none pmd entry, which
3957 * should never happen, return SIGBUS
3959 if (unlikely(!pmd_present(*vmf->pmd)))
3960 ret = VM_FAULT_SIGBUS;
3962 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
3967 * Make sure this is not a temporary clearing of pte
3968 * by holding ptl and checking again. A R/M/W update
3969 * of pte involves: take ptl, clearing the pte so that
3970 * we don't have concurrent modification by hardware
3971 * followed by an update.
3973 if (unlikely(pte_none(*vmf->pte)))
3974 ret = VM_FAULT_SIGBUS;
3976 ret = VM_FAULT_NOPAGE;
3978 pte_unmap_unlock(vmf->pte, vmf->ptl);
3980 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
3981 ret = do_read_fault(vmf);
3982 else if (!(vma->vm_flags & VM_SHARED))
3983 ret = do_cow_fault(vmf);
3985 ret = do_shared_fault(vmf);
3987 /* preallocated pagetable is unused: free it */
3988 if (vmf->prealloc_pte) {
3989 pte_free(vm_mm, vmf->prealloc_pte);
3990 vmf->prealloc_pte = NULL;
3995 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3996 unsigned long addr, int page_nid,
4001 count_vm_numa_event(NUMA_HINT_FAULTS);
4002 if (page_nid == numa_node_id()) {
4003 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
4004 *flags |= TNF_FAULT_LOCAL;
4007 return mpol_misplaced(page, vma, addr);
4010 static vm_fault_t do_numa_page(struct vm_fault *vmf)
4012 struct vm_area_struct *vma = vmf->vma;
4013 struct page *page = NULL;
4017 bool migrated = false;
4019 bool was_writable = pte_savedwrite(vmf->orig_pte);
4023 * The "pte" at this point cannot be used safely without
4024 * validation through pte_unmap_same(). It's of NUMA type but
4025 * the pfn may be screwed if the read is non atomic.
4027 vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
4028 spin_lock(vmf->ptl);
4029 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4030 pte_unmap_unlock(vmf->pte, vmf->ptl);
4035 * Make it present again, Depending on how arch implementes non
4036 * accessible ptes, some can allow access by kernel mode.
4038 pte = ptep_modify_prot_start(vma->vm_mm, vmf->address, vmf->pte);
4039 pte = pte_modify(pte, vma->vm_page_prot);
4040 pte = pte_mkyoung(pte);
4042 pte = pte_mkwrite(pte);
4043 ptep_modify_prot_commit(vma->vm_mm, vmf->address, vmf->pte, pte);
4044 update_mmu_cache(vma, vmf->address, vmf->pte);
4046 page = vm_normal_page(vma, vmf->address, pte);
4048 pte_unmap_unlock(vmf->pte, vmf->ptl);
4052 /* TODO: handle PTE-mapped THP */
4053 if (PageCompound(page)) {
4054 pte_unmap_unlock(vmf->pte, vmf->ptl);
4059 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
4060 * much anyway since they can be in shared cache state. This misses
4061 * the case where a mapping is writable but the process never writes
4062 * to it but pte_write gets cleared during protection updates and
4063 * pte_dirty has unpredictable behaviour between PTE scan updates,
4064 * background writeback, dirty balancing and application behaviour.
4066 if (!pte_write(pte))
4067 flags |= TNF_NO_GROUP;
4070 * Flag if the page is shared between multiple address spaces. This
4071 * is later used when determining whether to group tasks together
4073 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
4074 flags |= TNF_SHARED;
4076 last_cpupid = page_cpupid_last(page);
4077 page_nid = page_to_nid(page);
4078 target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
4080 pte_unmap_unlock(vmf->pte, vmf->ptl);
4081 if (target_nid == -1) {
4086 /* Migrate to the requested node */
4087 migrated = migrate_misplaced_page(page, vma, target_nid);
4089 page_nid = target_nid;
4090 flags |= TNF_MIGRATED;
4092 flags |= TNF_MIGRATE_FAIL;
4096 task_numa_fault(last_cpupid, page_nid, 1, flags);
4100 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4102 if (vma_is_anonymous(vmf->vma))
4103 return do_huge_pmd_anonymous_page(vmf);
4104 if (vmf->vma->vm_ops->huge_fault)
4105 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4106 return VM_FAULT_FALLBACK;
4109 /* `inline' is required to avoid gcc 4.1.2 build error */
4110 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
4112 if (vma_is_anonymous(vmf->vma))
4113 return do_huge_pmd_wp_page(vmf, orig_pmd);
4114 if (vmf->vma->vm_ops->huge_fault)
4115 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4117 /* COW handled on pte level: split pmd */
4118 VM_BUG_ON_VMA(vmf->vma->vm_flags & VM_SHARED, vmf->vma);
4119 __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4121 return VM_FAULT_FALLBACK;
4124 static inline bool vma_is_accessible(struct vm_area_struct *vma)
4126 return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
4129 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4131 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4132 /* No support for anonymous transparent PUD pages yet */
4133 if (vma_is_anonymous(vmf->vma))
4134 return VM_FAULT_FALLBACK;
4135 if (vmf->vma->vm_ops->huge_fault)
4136 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4137 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4138 return VM_FAULT_FALLBACK;
4141 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4143 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4144 /* No support for anonymous transparent PUD pages yet */
4145 if (vma_is_anonymous(vmf->vma))
4146 return VM_FAULT_FALLBACK;
4147 if (vmf->vma->vm_ops->huge_fault)
4148 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4149 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4150 return VM_FAULT_FALLBACK;
4154 * These routines also need to handle stuff like marking pages dirty
4155 * and/or accessed for architectures that don't do it in hardware (most
4156 * RISC architectures). The early dirtying is also good on the i386.
4158 * There is also a hook called "update_mmu_cache()" that architectures
4159 * with external mmu caches can use to update those (ie the Sparc or
4160 * PowerPC hashed page tables that act as extended TLBs).
4162 * We enter with non-exclusive mmap_sem (to exclude vma changes, but allow
4163 * concurrent faults).
4165 * The mmap_sem may have been released depending on flags and our return value.
4166 * See filemap_fault() and __lock_page_or_retry().
4168 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4172 if (unlikely(pmd_none(*vmf->pmd))) {
4174 * Leave __pte_alloc() until later: because vm_ops->fault may
4175 * want to allocate huge page, and if we expose page table
4176 * for an instant, it will be difficult to retract from
4177 * concurrent faults and from rmap lookups.
4181 /* See comment in pte_alloc_one_map() */
4182 if (pmd_devmap_trans_unstable(vmf->pmd))
4185 * A regular pmd is established and it can't morph into a huge
4186 * pmd from under us anymore at this point because we hold the
4187 * mmap_sem read mode and khugepaged takes it in write mode.
4188 * So now it's safe to run pte_offset_map().
4190 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4191 vmf->orig_pte = *vmf->pte;
4194 * some architectures can have larger ptes than wordsize,
4195 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4196 * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4197 * accesses. The code below just needs a consistent view
4198 * for the ifs and we later double check anyway with the
4199 * ptl lock held. So here a barrier will do.
4202 if (pte_none(vmf->orig_pte)) {
4203 pte_unmap(vmf->pte);
4209 if (vma_is_anonymous(vmf->vma))
4210 return do_anonymous_page(vmf);
4212 return do_fault(vmf);
4215 if (!pte_present(vmf->orig_pte))
4216 return do_swap_page(vmf);
4218 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4219 return do_numa_page(vmf);
4221 vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4222 spin_lock(vmf->ptl);
4223 entry = vmf->orig_pte;
4224 if (unlikely(!pte_same(*vmf->pte, entry)))
4226 if (vmf->flags & FAULT_FLAG_WRITE) {
4227 if (!pte_write(entry))
4228 return do_wp_page(vmf);
4229 entry = pte_mkdirty(entry);
4231 entry = pte_mkyoung(entry);
4232 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4233 vmf->flags & FAULT_FLAG_WRITE)) {
4234 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4237 * This is needed only for protection faults but the arch code
4238 * is not yet telling us if this is a protection fault or not.
4239 * This still avoids useless tlb flushes for .text page faults
4242 if (vmf->flags & FAULT_FLAG_WRITE)
4243 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4246 pte_unmap_unlock(vmf->pte, vmf->ptl);
4251 * By the time we get here, we already hold the mm semaphore
4253 * The mmap_sem may have been released depending on flags and our
4254 * return value. See filemap_fault() and __lock_page_or_retry().
4256 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
4257 unsigned long address, unsigned int flags)
4259 struct vm_fault vmf = {
4261 .address = address & PAGE_MASK,
4263 .pgoff = linear_page_index(vma, address),
4264 .gfp_mask = __get_fault_gfp_mask(vma),
4266 unsigned int dirty = flags & FAULT_FLAG_WRITE;
4267 struct mm_struct *mm = vma->vm_mm;
4272 pgd = pgd_offset(mm, address);
4273 p4d = p4d_alloc(mm, pgd, address);
4275 return VM_FAULT_OOM;
4277 vmf.pud = pud_alloc(mm, p4d, address);
4279 return VM_FAULT_OOM;
4280 if (pud_none(*vmf.pud) && __transparent_hugepage_enabled(vma)) {
4281 ret = create_huge_pud(&vmf);
4282 if (!(ret & VM_FAULT_FALLBACK))
4285 pud_t orig_pud = *vmf.pud;
4288 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4290 /* NUMA case for anonymous PUDs would go here */
4292 if (dirty && !pud_write(orig_pud)) {
4293 ret = wp_huge_pud(&vmf, orig_pud);
4294 if (!(ret & VM_FAULT_FALLBACK))
4297 huge_pud_set_accessed(&vmf, orig_pud);
4303 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4305 return VM_FAULT_OOM;
4306 if (pmd_none(*vmf.pmd) && __transparent_hugepage_enabled(vma)) {
4307 ret = create_huge_pmd(&vmf);
4308 if (!(ret & VM_FAULT_FALLBACK))
4311 pmd_t orig_pmd = *vmf.pmd;
4314 if (unlikely(is_swap_pmd(orig_pmd))) {
4315 VM_BUG_ON(thp_migration_supported() &&
4316 !is_pmd_migration_entry(orig_pmd));
4317 if (is_pmd_migration_entry(orig_pmd))
4318 pmd_migration_entry_wait(mm, vmf.pmd);
4321 if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
4322 if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
4323 return do_huge_pmd_numa_page(&vmf, orig_pmd);
4325 if (dirty && !pmd_write(orig_pmd)) {
4326 ret = wp_huge_pmd(&vmf, orig_pmd);
4327 if (!(ret & VM_FAULT_FALLBACK))
4330 huge_pmd_set_accessed(&vmf, orig_pmd);
4336 return handle_pte_fault(&vmf);
4340 * By the time we get here, we already hold the mm semaphore
4342 * The mmap_sem may have been released depending on flags and our
4343 * return value. See filemap_fault() and __lock_page_or_retry().
4345 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4350 __set_current_state(TASK_RUNNING);
4352 count_vm_event(PGFAULT);
4353 count_memcg_event_mm(vma->vm_mm, PGFAULT);
4355 /* do counter updates before entering really critical section. */
4356 check_sync_rss_stat(current);
4358 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4359 flags & FAULT_FLAG_INSTRUCTION,
4360 flags & FAULT_FLAG_REMOTE))
4361 return VM_FAULT_SIGSEGV;
4364 * Enable the memcg OOM handling for faults triggered in user
4365 * space. Kernel faults are handled more gracefully.
4367 if (flags & FAULT_FLAG_USER)
4368 mem_cgroup_enter_user_fault();
4370 if (unlikely(is_vm_hugetlb_page(vma)))
4371 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4373 ret = __handle_mm_fault(vma, address, flags);
4375 if (flags & FAULT_FLAG_USER) {
4376 mem_cgroup_exit_user_fault();
4378 * The task may have entered a memcg OOM situation but
4379 * if the allocation error was handled gracefully (no
4380 * VM_FAULT_OOM), there is no need to kill anything.
4381 * Just clean up the OOM state peacefully.
4383 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4384 mem_cgroup_oom_synchronize(false);
4389 EXPORT_SYMBOL_GPL(handle_mm_fault);
4391 #ifndef __PAGETABLE_P4D_FOLDED
4393 * Allocate p4d page table.
4394 * We've already handled the fast-path in-line.
4396 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4398 p4d_t *new = p4d_alloc_one(mm, address);
4402 smp_wmb(); /* See comment in __pte_alloc */
4404 spin_lock(&mm->page_table_lock);
4405 if (pgd_present(*pgd)) /* Another has populated it */
4408 pgd_populate(mm, pgd, new);
4409 spin_unlock(&mm->page_table_lock);
4412 #endif /* __PAGETABLE_P4D_FOLDED */
4414 #ifndef __PAGETABLE_PUD_FOLDED
4416 * Allocate page upper directory.
4417 * We've already handled the fast-path in-line.
4419 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4421 pud_t *new = pud_alloc_one(mm, address);
4425 smp_wmb(); /* See comment in __pte_alloc */
4427 spin_lock(&mm->page_table_lock);
4428 #ifndef __ARCH_HAS_5LEVEL_HACK
4429 if (!p4d_present(*p4d)) {
4431 p4d_populate(mm, p4d, new);
4432 } else /* Another has populated it */
4435 if (!pgd_present(*p4d)) {
4437 pgd_populate(mm, p4d, new);
4438 } else /* Another has populated it */
4440 #endif /* __ARCH_HAS_5LEVEL_HACK */
4441 spin_unlock(&mm->page_table_lock);
4444 #endif /* __PAGETABLE_PUD_FOLDED */
4446 #ifndef __PAGETABLE_PMD_FOLDED
4448 * Allocate page middle directory.
4449 * We've already handled the fast-path in-line.
4451 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4454 pmd_t *new = pmd_alloc_one(mm, address);
4458 smp_wmb(); /* See comment in __pte_alloc */
4460 ptl = pud_lock(mm, pud);
4461 #ifndef __ARCH_HAS_4LEVEL_HACK
4462 if (!pud_present(*pud)) {
4464 pud_populate(mm, pud, new);
4465 } else /* Another has populated it */
4468 if (!pgd_present(*pud)) {
4470 pgd_populate(mm, pud, new);
4471 } else /* Another has populated it */
4473 #endif /* __ARCH_HAS_4LEVEL_HACK */
4477 #endif /* __PAGETABLE_PMD_FOLDED */
4479 static int __follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4480 unsigned long *start, unsigned long *end,
4481 pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4489 pgd = pgd_offset(mm, address);
4490 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4493 p4d = p4d_offset(pgd, address);
4494 if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4497 pud = pud_offset(p4d, address);
4498 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4501 pmd = pmd_offset(pud, address);
4502 VM_BUG_ON(pmd_trans_huge(*pmd));
4504 if (pmd_huge(*pmd)) {
4509 *start = address & PMD_MASK;
4510 *end = *start + PMD_SIZE;
4511 mmu_notifier_invalidate_range_start(mm, *start, *end);
4513 *ptlp = pmd_lock(mm, pmd);
4514 if (pmd_huge(*pmd)) {
4520 mmu_notifier_invalidate_range_end(mm, *start, *end);
4523 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4527 *start = address & PAGE_MASK;
4528 *end = *start + PAGE_SIZE;
4529 mmu_notifier_invalidate_range_start(mm, *start, *end);
4531 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4532 if (!pte_present(*ptep))
4537 pte_unmap_unlock(ptep, *ptlp);
4539 mmu_notifier_invalidate_range_end(mm, *start, *end);
4544 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
4545 pte_t **ptepp, spinlock_t **ptlp)
4549 /* (void) is needed to make gcc happy */
4550 (void) __cond_lock(*ptlp,
4551 !(res = __follow_pte_pmd(mm, address, NULL, NULL,
4552 ptepp, NULL, ptlp)));
4556 int follow_pte_pmd(struct mm_struct *mm, unsigned long address,
4557 unsigned long *start, unsigned long *end,
4558 pte_t **ptepp, pmd_t **pmdpp, spinlock_t **ptlp)
4562 /* (void) is needed to make gcc happy */
4563 (void) __cond_lock(*ptlp,
4564 !(res = __follow_pte_pmd(mm, address, start, end,
4565 ptepp, pmdpp, ptlp)));
4568 EXPORT_SYMBOL(follow_pte_pmd);
4571 * follow_pfn - look up PFN at a user virtual address
4572 * @vma: memory mapping
4573 * @address: user virtual address
4574 * @pfn: location to store found PFN
4576 * Only IO mappings and raw PFN mappings are allowed.
4578 * Returns zero and the pfn at @pfn on success, -ve otherwise.
4580 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
4587 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4590 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
4593 *pfn = pte_pfn(*ptep);
4594 pte_unmap_unlock(ptep, ptl);
4597 EXPORT_SYMBOL(follow_pfn);
4599 #ifdef CONFIG_HAVE_IOREMAP_PROT
4600 int follow_phys(struct vm_area_struct *vma,
4601 unsigned long address, unsigned int flags,
4602 unsigned long *prot, resource_size_t *phys)
4608 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
4611 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
4615 /* Never return PFNs of anon folios in COW mappings. */
4616 if (vm_normal_page(vma, address, pte))
4619 if ((flags & FOLL_WRITE) && !pte_write(pte))
4622 *prot = pgprot_val(pte_pgprot(pte));
4623 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
4627 pte_unmap_unlock(ptep, ptl);
4632 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
4633 void *buf, int len, int write)
4635 resource_size_t phys_addr;
4636 unsigned long prot = 0;
4637 void __iomem *maddr;
4638 int offset = addr & (PAGE_SIZE-1);
4640 if (follow_phys(vma, addr, write, &prot, &phys_addr))
4643 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
4648 memcpy_toio(maddr + offset, buf, len);
4650 memcpy_fromio(buf, maddr + offset, len);
4655 EXPORT_SYMBOL_GPL(generic_access_phys);
4659 * Access another process' address space as given in mm. If non-NULL, use the
4660 * given task for page fault accounting.
4662 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
4663 unsigned long addr, void *buf, int len, unsigned int gup_flags)
4665 struct vm_area_struct *vma;
4666 void *old_buf = buf;
4667 int write = gup_flags & FOLL_WRITE;
4669 if (down_read_killable(&mm->mmap_sem))
4672 /* ignore errors, just check how much was successfully transferred */
4674 int bytes, ret, offset;
4676 struct page *page = NULL;
4678 ret = get_user_pages_remote(tsk, mm, addr, 1,
4679 gup_flags, &page, &vma, NULL);
4681 #ifndef CONFIG_HAVE_IOREMAP_PROT
4685 * Check if this is a VM_IO | VM_PFNMAP VMA, which
4686 * we can access using slightly different code.
4688 vma = find_vma(mm, addr);
4689 if (!vma || vma->vm_start > addr)
4691 if (vma->vm_ops && vma->vm_ops->access)
4692 ret = vma->vm_ops->access(vma, addr, buf,
4700 offset = addr & (PAGE_SIZE-1);
4701 if (bytes > PAGE_SIZE-offset)
4702 bytes = PAGE_SIZE-offset;
4706 copy_to_user_page(vma, page, addr,
4707 maddr + offset, buf, bytes);
4708 set_page_dirty_lock(page);
4710 copy_from_user_page(vma, page, addr,
4711 buf, maddr + offset, bytes);
4720 up_read(&mm->mmap_sem);
4722 return buf - old_buf;
4726 * access_remote_vm - access another process' address space
4727 * @mm: the mm_struct of the target address space
4728 * @addr: start address to access
4729 * @buf: source or destination buffer
4730 * @len: number of bytes to transfer
4731 * @gup_flags: flags modifying lookup behaviour
4733 * The caller must hold a reference on @mm.
4735 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
4736 void *buf, int len, unsigned int gup_flags)
4738 return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
4742 * Access another process' address space.
4743 * Source/target buffer must be kernel space,
4744 * Do not walk the page table directly, use get_user_pages
4746 int access_process_vm(struct task_struct *tsk, unsigned long addr,
4747 void *buf, int len, unsigned int gup_flags)
4749 struct mm_struct *mm;
4752 mm = get_task_mm(tsk);
4756 ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
4762 EXPORT_SYMBOL_GPL(access_process_vm);
4765 * Print the name of a VMA.
4767 void print_vma_addr(char *prefix, unsigned long ip)
4769 struct mm_struct *mm = current->mm;
4770 struct vm_area_struct *vma;
4773 * we might be running from an atomic context so we cannot sleep
4775 if (!down_read_trylock(&mm->mmap_sem))
4778 vma = find_vma(mm, ip);
4779 if (vma && vma->vm_file) {
4780 struct file *f = vma->vm_file;
4781 char *buf = (char *)__get_free_page(GFP_NOWAIT);
4785 p = file_path(f, buf, PAGE_SIZE);
4788 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
4790 vma->vm_end - vma->vm_start);
4791 free_page((unsigned long)buf);
4794 up_read(&mm->mmap_sem);
4797 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4798 void __might_fault(const char *file, int line)
4801 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4802 * holding the mmap_sem, this is safe because kernel memory doesn't
4803 * get paged out, therefore we'll never actually fault, and the
4804 * below annotations will generate false positives.
4806 if (uaccess_kernel())
4808 if (pagefault_disabled())
4810 __might_sleep(file, line, 0);
4811 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4813 might_lock_read(¤t->mm->mmap_sem);
4816 EXPORT_SYMBOL(__might_fault);
4819 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4821 * Process all subpages of the specified huge page with the specified
4822 * operation. The target subpage will be processed last to keep its
4825 static inline void process_huge_page(
4826 unsigned long addr_hint, unsigned int pages_per_huge_page,
4827 void (*process_subpage)(unsigned long addr, int idx, void *arg),
4831 unsigned long addr = addr_hint &
4832 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4834 /* Process target subpage last to keep its cache lines hot */
4836 n = (addr_hint - addr) / PAGE_SIZE;
4837 if (2 * n <= pages_per_huge_page) {
4838 /* If target subpage in first half of huge page */
4841 /* Process subpages at the end of huge page */
4842 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
4844 process_subpage(addr + i * PAGE_SIZE, i, arg);
4847 /* If target subpage in second half of huge page */
4848 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
4849 l = pages_per_huge_page - n;
4850 /* Process subpages at the begin of huge page */
4851 for (i = 0; i < base; i++) {
4853 process_subpage(addr + i * PAGE_SIZE, i, arg);
4857 * Process remaining subpages in left-right-left-right pattern
4858 * towards the target subpage
4860 for (i = 0; i < l; i++) {
4861 int left_idx = base + i;
4862 int right_idx = base + 2 * l - 1 - i;
4865 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
4867 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
4871 static void clear_gigantic_page(struct page *page,
4873 unsigned int pages_per_huge_page)
4876 struct page *p = page;
4879 for (i = 0; i < pages_per_huge_page;
4880 i++, p = mem_map_next(p, page, i)) {
4882 clear_user_highpage(p, addr + i * PAGE_SIZE);
4886 static void clear_subpage(unsigned long addr, int idx, void *arg)
4888 struct page *page = arg;
4890 clear_user_highpage(page + idx, addr);
4893 void clear_huge_page(struct page *page,
4894 unsigned long addr_hint, unsigned int pages_per_huge_page)
4896 unsigned long addr = addr_hint &
4897 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4899 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4900 clear_gigantic_page(page, addr, pages_per_huge_page);
4904 process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
4907 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4909 struct vm_area_struct *vma,
4910 unsigned int pages_per_huge_page)
4913 struct page *dst_base = dst;
4914 struct page *src_base = src;
4916 for (i = 0; i < pages_per_huge_page; ) {
4918 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4921 dst = mem_map_next(dst, dst_base, i);
4922 src = mem_map_next(src, src_base, i);
4926 struct copy_subpage_arg {
4929 struct vm_area_struct *vma;
4932 static void copy_subpage(unsigned long addr, int idx, void *arg)
4934 struct copy_subpage_arg *copy_arg = arg;
4936 copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
4937 addr, copy_arg->vma);
4940 void copy_user_huge_page(struct page *dst, struct page *src,
4941 unsigned long addr_hint, struct vm_area_struct *vma,
4942 unsigned int pages_per_huge_page)
4944 unsigned long addr = addr_hint &
4945 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
4946 struct copy_subpage_arg arg = {
4952 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4953 copy_user_gigantic_page(dst, src, addr, vma,
4954 pages_per_huge_page);
4958 process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
4961 long copy_huge_page_from_user(struct page *dst_page,
4962 const void __user *usr_src,
4963 unsigned int pages_per_huge_page,
4964 bool allow_pagefault)
4966 void *src = (void *)usr_src;
4968 unsigned long i, rc = 0;
4969 unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
4970 struct page *subpage = dst_page;
4972 for (i = 0; i < pages_per_huge_page;
4973 i++, subpage = mem_map_next(subpage, dst_page, i)) {
4974 if (allow_pagefault)
4975 page_kaddr = kmap(subpage);
4977 page_kaddr = kmap_atomic(subpage);
4978 rc = copy_from_user(page_kaddr,
4979 (const void __user *)(src + i * PAGE_SIZE),
4981 if (allow_pagefault)
4984 kunmap_atomic(page_kaddr);
4986 ret_val -= (PAGE_SIZE - rc);
4990 flush_dcache_page(subpage);
4996 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
4998 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
5000 static struct kmem_cache *page_ptl_cachep;
5002 void __init ptlock_cache_init(void)
5004 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
5008 bool ptlock_alloc(struct page *page)
5012 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
5019 void ptlock_free(struct page *page)
5021 kmem_cache_free(page_ptl_cachep, page->ptl);