drm/vc4: Fix scaling of uni-planar formats
[linux/fpc-iii.git] / mm / memory.c
blobd2db2c4eb0a4d317f92736a3880efa99228cb1c0
1 /*
2 * linux/mm/memory.c
4 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
5 */
7 /*
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
18 * far as I could see.
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>
42 #include <linux/mm.h>
43 #include <linux/hugetlb.h>
44 #include <linux/mman.h>
45 #include <linux/swap.h>
46 #include <linux/highmem.h>
47 #include <linux/pagemap.h>
48 #include <linux/ksm.h>
49 #include <linux/rmap.h>
50 #include <linux/export.h>
51 #include <linux/delayacct.h>
52 #include <linux/init.h>
53 #include <linux/pfn_t.h>
54 #include <linux/writeback.h>
55 #include <linux/memcontrol.h>
56 #include <linux/mmu_notifier.h>
57 #include <linux/kallsyms.h>
58 #include <linux/swapops.h>
59 #include <linux/elf.h>
60 #include <linux/gfp.h>
61 #include <linux/migrate.h>
62 #include <linux/string.h>
63 #include <linux/dma-debug.h>
64 #include <linux/debugfs.h>
65 #include <linux/userfaultfd_k.h>
66 #include <linux/dax.h>
68 #include <asm/io.h>
69 #include <asm/mmu_context.h>
70 #include <asm/pgalloc.h>
71 #include <asm/uaccess.h>
72 #include <asm/tlb.h>
73 #include <asm/tlbflush.h>
74 #include <asm/pgtable.h>
76 #include "internal.h"
78 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
79 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
80 #endif
82 #ifndef CONFIG_NEED_MULTIPLE_NODES
83 /* use the per-pgdat data instead for discontigmem - mbligh */
84 unsigned long max_mapnr;
85 struct page *mem_map;
87 EXPORT_SYMBOL(max_mapnr);
88 EXPORT_SYMBOL(mem_map);
89 #endif
92 * A number of key systems in x86 including ioremap() rely on the assumption
93 * that high_memory defines the upper bound on direct map memory, then end
94 * of ZONE_NORMAL. Under CONFIG_DISCONTIG this means that max_low_pfn and
95 * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
96 * and ZONE_HIGHMEM.
98 void * high_memory;
100 EXPORT_SYMBOL(high_memory);
103 * Randomize the address space (stacks, mmaps, brk, etc.).
105 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
106 * as ancient (libc5 based) binaries can segfault. )
108 int randomize_va_space __read_mostly =
109 #ifdef CONFIG_COMPAT_BRK
111 #else
113 #endif
115 static int __init disable_randmaps(char *s)
117 randomize_va_space = 0;
118 return 1;
120 __setup("norandmaps", disable_randmaps);
122 unsigned long zero_pfn __read_mostly;
123 unsigned long highest_memmap_pfn __read_mostly;
125 EXPORT_SYMBOL(zero_pfn);
128 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
130 static int __init init_zero_pfn(void)
132 zero_pfn = page_to_pfn(ZERO_PAGE(0));
133 return 0;
135 core_initcall(init_zero_pfn);
138 #if defined(SPLIT_RSS_COUNTING)
140 void sync_mm_rss(struct mm_struct *mm)
142 int i;
144 for (i = 0; i < NR_MM_COUNTERS; i++) {
145 if (current->rss_stat.count[i]) {
146 add_mm_counter(mm, i, current->rss_stat.count[i]);
147 current->rss_stat.count[i] = 0;
150 current->rss_stat.events = 0;
153 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
155 struct task_struct *task = current;
157 if (likely(task->mm == mm))
158 task->rss_stat.count[member] += val;
159 else
160 add_mm_counter(mm, member, val);
162 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
163 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
165 /* sync counter once per 64 page faults */
166 #define TASK_RSS_EVENTS_THRESH (64)
167 static void check_sync_rss_stat(struct task_struct *task)
169 if (unlikely(task != current))
170 return;
171 if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
172 sync_mm_rss(task->mm);
174 #else /* SPLIT_RSS_COUNTING */
176 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
177 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
179 static void check_sync_rss_stat(struct task_struct *task)
183 #endif /* SPLIT_RSS_COUNTING */
185 #ifdef HAVE_GENERIC_MMU_GATHER
187 static bool tlb_next_batch(struct mmu_gather *tlb)
189 struct mmu_gather_batch *batch;
191 batch = tlb->active;
192 if (batch->next) {
193 tlb->active = batch->next;
194 return true;
197 if (tlb->batch_count == MAX_GATHER_BATCH_COUNT)
198 return false;
200 batch = (void *)__get_free_pages(GFP_NOWAIT | __GFP_NOWARN, 0);
201 if (!batch)
202 return false;
204 tlb->batch_count++;
205 batch->next = NULL;
206 batch->nr = 0;
207 batch->max = MAX_GATHER_BATCH;
209 tlb->active->next = batch;
210 tlb->active = batch;
212 return true;
215 /* tlb_gather_mmu
216 * Called to initialize an (on-stack) mmu_gather structure for page-table
217 * tear-down from @mm. The @fullmm argument is used when @mm is without
218 * users and we're going to destroy the full address space (exit/execve).
220 void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm, unsigned long start, unsigned long end)
222 tlb->mm = mm;
224 /* Is it from 0 to ~0? */
225 tlb->fullmm = !(start | (end+1));
226 tlb->need_flush_all = 0;
227 tlb->local.next = NULL;
228 tlb->local.nr = 0;
229 tlb->local.max = ARRAY_SIZE(tlb->__pages);
230 tlb->active = &tlb->local;
231 tlb->batch_count = 0;
233 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
234 tlb->batch = NULL;
235 #endif
236 tlb->page_size = 0;
238 __tlb_reset_range(tlb);
241 static void tlb_flush_mmu_tlbonly(struct mmu_gather *tlb)
243 if (!tlb->end)
244 return;
246 tlb_flush(tlb);
247 mmu_notifier_invalidate_range(tlb->mm, tlb->start, tlb->end);
248 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
249 tlb_table_flush(tlb);
250 #endif
251 __tlb_reset_range(tlb);
254 static void tlb_flush_mmu_free(struct mmu_gather *tlb)
256 struct mmu_gather_batch *batch;
258 for (batch = &tlb->local; batch && batch->nr; batch = batch->next) {
259 free_pages_and_swap_cache(batch->pages, batch->nr);
260 batch->nr = 0;
262 tlb->active = &tlb->local;
265 void tlb_flush_mmu(struct mmu_gather *tlb)
267 tlb_flush_mmu_tlbonly(tlb);
268 tlb_flush_mmu_free(tlb);
271 /* tlb_finish_mmu
272 * Called at the end of the shootdown operation to free up any resources
273 * that were required.
275 void tlb_finish_mmu(struct mmu_gather *tlb, unsigned long start, unsigned long end)
277 struct mmu_gather_batch *batch, *next;
279 tlb_flush_mmu(tlb);
281 /* keep the page table cache within bounds */
282 check_pgt_cache();
284 for (batch = tlb->local.next; batch; batch = next) {
285 next = batch->next;
286 free_pages((unsigned long)batch, 0);
288 tlb->local.next = NULL;
291 /* __tlb_remove_page
292 * Must perform the equivalent to __free_pte(pte_get_and_clear(ptep)), while
293 * handling the additional races in SMP caused by other CPUs caching valid
294 * mappings in their TLBs. Returns the number of free page slots left.
295 * When out of page slots we must call tlb_flush_mmu().
296 *returns true if the caller should flush.
298 bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, int page_size)
300 struct mmu_gather_batch *batch;
302 VM_BUG_ON(!tlb->end);
304 if (!tlb->page_size)
305 tlb->page_size = page_size;
306 else {
307 if (page_size != tlb->page_size)
308 return true;
311 batch = tlb->active;
312 if (batch->nr == batch->max) {
313 if (!tlb_next_batch(tlb))
314 return true;
315 batch = tlb->active;
317 VM_BUG_ON_PAGE(batch->nr > batch->max, page);
319 batch->pages[batch->nr++] = page;
320 return false;
323 #endif /* HAVE_GENERIC_MMU_GATHER */
325 #ifdef CONFIG_HAVE_RCU_TABLE_FREE
328 * See the comment near struct mmu_table_batch.
331 static void tlb_remove_table_smp_sync(void *arg)
333 /* Simply deliver the interrupt */
336 static void tlb_remove_table_one(void *table)
339 * This isn't an RCU grace period and hence the page-tables cannot be
340 * assumed to be actually RCU-freed.
342 * It is however sufficient for software page-table walkers that rely on
343 * IRQ disabling. See the comment near struct mmu_table_batch.
345 smp_call_function(tlb_remove_table_smp_sync, NULL, 1);
346 __tlb_remove_table(table);
349 static void tlb_remove_table_rcu(struct rcu_head *head)
351 struct mmu_table_batch *batch;
352 int i;
354 batch = container_of(head, struct mmu_table_batch, rcu);
356 for (i = 0; i < batch->nr; i++)
357 __tlb_remove_table(batch->tables[i]);
359 free_page((unsigned long)batch);
362 void tlb_table_flush(struct mmu_gather *tlb)
364 struct mmu_table_batch **batch = &tlb->batch;
366 if (*batch) {
367 call_rcu_sched(&(*batch)->rcu, tlb_remove_table_rcu);
368 *batch = NULL;
372 void tlb_remove_table(struct mmu_gather *tlb, void *table)
374 struct mmu_table_batch **batch = &tlb->batch;
377 * When there's less then two users of this mm there cannot be a
378 * concurrent page-table walk.
380 if (atomic_read(&tlb->mm->mm_users) < 2) {
381 __tlb_remove_table(table);
382 return;
385 if (*batch == NULL) {
386 *batch = (struct mmu_table_batch *)__get_free_page(GFP_NOWAIT | __GFP_NOWARN);
387 if (*batch == NULL) {
388 tlb_remove_table_one(table);
389 return;
391 (*batch)->nr = 0;
393 (*batch)->tables[(*batch)->nr++] = table;
394 if ((*batch)->nr == MAX_TABLE_BATCH)
395 tlb_table_flush(tlb);
398 #endif /* CONFIG_HAVE_RCU_TABLE_FREE */
401 * Note: this doesn't free the actual pages themselves. That
402 * has been handled earlier when unmapping all the memory regions.
404 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
405 unsigned long addr)
407 pgtable_t token = pmd_pgtable(*pmd);
408 pmd_clear(pmd);
409 pte_free_tlb(tlb, token, addr);
410 atomic_long_dec(&tlb->mm->nr_ptes);
413 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
414 unsigned long addr, unsigned long end,
415 unsigned long floor, unsigned long ceiling)
417 pmd_t *pmd;
418 unsigned long next;
419 unsigned long start;
421 start = addr;
422 pmd = pmd_offset(pud, addr);
423 do {
424 next = pmd_addr_end(addr, end);
425 if (pmd_none_or_clear_bad(pmd))
426 continue;
427 free_pte_range(tlb, pmd, addr);
428 } while (pmd++, addr = next, addr != end);
430 start &= PUD_MASK;
431 if (start < floor)
432 return;
433 if (ceiling) {
434 ceiling &= PUD_MASK;
435 if (!ceiling)
436 return;
438 if (end - 1 > ceiling - 1)
439 return;
441 pmd = pmd_offset(pud, start);
442 pud_clear(pud);
443 pmd_free_tlb(tlb, pmd, start);
444 mm_dec_nr_pmds(tlb->mm);
447 static inline void free_pud_range(struct mmu_gather *tlb, pgd_t *pgd,
448 unsigned long addr, unsigned long end,
449 unsigned long floor, unsigned long ceiling)
451 pud_t *pud;
452 unsigned long next;
453 unsigned long start;
455 start = addr;
456 pud = pud_offset(pgd, addr);
457 do {
458 next = pud_addr_end(addr, end);
459 if (pud_none_or_clear_bad(pud))
460 continue;
461 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
462 } while (pud++, addr = next, addr != end);
464 start &= PGDIR_MASK;
465 if (start < floor)
466 return;
467 if (ceiling) {
468 ceiling &= PGDIR_MASK;
469 if (!ceiling)
470 return;
472 if (end - 1 > ceiling - 1)
473 return;
475 pud = pud_offset(pgd, start);
476 pgd_clear(pgd);
477 pud_free_tlb(tlb, pud, start);
481 * This function frees user-level page tables of a process.
483 void free_pgd_range(struct mmu_gather *tlb,
484 unsigned long addr, unsigned long end,
485 unsigned long floor, unsigned long ceiling)
487 pgd_t *pgd;
488 unsigned long next;
491 * The next few lines have given us lots of grief...
493 * Why are we testing PMD* at this top level? Because often
494 * there will be no work to do at all, and we'd prefer not to
495 * go all the way down to the bottom just to discover that.
497 * Why all these "- 1"s? Because 0 represents both the bottom
498 * of the address space and the top of it (using -1 for the
499 * top wouldn't help much: the masks would do the wrong thing).
500 * The rule is that addr 0 and floor 0 refer to the bottom of
501 * the address space, but end 0 and ceiling 0 refer to the top
502 * Comparisons need to use "end - 1" and "ceiling - 1" (though
503 * that end 0 case should be mythical).
505 * Wherever addr is brought up or ceiling brought down, we must
506 * be careful to reject "the opposite 0" before it confuses the
507 * subsequent tests. But what about where end is brought down
508 * by PMD_SIZE below? no, end can't go down to 0 there.
510 * Whereas we round start (addr) and ceiling down, by different
511 * masks at different levels, in order to test whether a table
512 * now has no other vmas using it, so can be freed, we don't
513 * bother to round floor or end up - the tests don't need that.
516 addr &= PMD_MASK;
517 if (addr < floor) {
518 addr += PMD_SIZE;
519 if (!addr)
520 return;
522 if (ceiling) {
523 ceiling &= PMD_MASK;
524 if (!ceiling)
525 return;
527 if (end - 1 > ceiling - 1)
528 end -= PMD_SIZE;
529 if (addr > end - 1)
530 return;
532 pgd = pgd_offset(tlb->mm, addr);
533 do {
534 next = pgd_addr_end(addr, end);
535 if (pgd_none_or_clear_bad(pgd))
536 continue;
537 free_pud_range(tlb, pgd, addr, next, floor, ceiling);
538 } while (pgd++, addr = next, addr != end);
541 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
542 unsigned long floor, unsigned long ceiling)
544 while (vma) {
545 struct vm_area_struct *next = vma->vm_next;
546 unsigned long addr = vma->vm_start;
549 * Hide vma from rmap and truncate_pagecache before freeing
550 * pgtables
552 unlink_anon_vmas(vma);
553 unlink_file_vma(vma);
555 if (is_vm_hugetlb_page(vma)) {
556 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
557 floor, next? next->vm_start: ceiling);
558 } else {
560 * Optimization: gather nearby vmas into one call down
562 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
563 && !is_vm_hugetlb_page(next)) {
564 vma = next;
565 next = vma->vm_next;
566 unlink_anon_vmas(vma);
567 unlink_file_vma(vma);
569 free_pgd_range(tlb, addr, vma->vm_end,
570 floor, next? next->vm_start: ceiling);
572 vma = next;
576 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd, unsigned long address)
578 spinlock_t *ptl;
579 pgtable_t new = pte_alloc_one(mm, address);
580 if (!new)
581 return -ENOMEM;
584 * Ensure all pte setup (eg. pte page lock and page clearing) are
585 * visible before the pte is made visible to other CPUs by being
586 * put into page tables.
588 * The other side of the story is the pointer chasing in the page
589 * table walking code (when walking the page table without locking;
590 * ie. most of the time). Fortunately, these data accesses consist
591 * of a chain of data-dependent loads, meaning most CPUs (alpha
592 * being the notable exception) will already guarantee loads are
593 * seen in-order. See the alpha page table accessors for the
594 * smp_read_barrier_depends() barriers in page table walking code.
596 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
598 ptl = pmd_lock(mm, pmd);
599 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
600 atomic_long_inc(&mm->nr_ptes);
601 pmd_populate(mm, pmd, new);
602 new = NULL;
604 spin_unlock(ptl);
605 if (new)
606 pte_free(mm, new);
607 return 0;
610 int __pte_alloc_kernel(pmd_t *pmd, unsigned long address)
612 pte_t *new = pte_alloc_one_kernel(&init_mm, address);
613 if (!new)
614 return -ENOMEM;
616 smp_wmb(); /* See comment in __pte_alloc */
618 spin_lock(&init_mm.page_table_lock);
619 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
620 pmd_populate_kernel(&init_mm, pmd, new);
621 new = NULL;
623 spin_unlock(&init_mm.page_table_lock);
624 if (new)
625 pte_free_kernel(&init_mm, new);
626 return 0;
629 static inline void init_rss_vec(int *rss)
631 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
634 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
636 int i;
638 if (current->mm == mm)
639 sync_mm_rss(mm);
640 for (i = 0; i < NR_MM_COUNTERS; i++)
641 if (rss[i])
642 add_mm_counter(mm, i, rss[i]);
646 * This function is called to print an error when a bad pte
647 * is found. For example, we might have a PFN-mapped pte in
648 * a region that doesn't allow it.
650 * The calling function must still handle the error.
652 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
653 pte_t pte, struct page *page)
655 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
656 pud_t *pud = pud_offset(pgd, addr);
657 pmd_t *pmd = pmd_offset(pud, addr);
658 struct address_space *mapping;
659 pgoff_t index;
660 static unsigned long resume;
661 static unsigned long nr_shown;
662 static unsigned long nr_unshown;
665 * Allow a burst of 60 reports, then keep quiet for that minute;
666 * or allow a steady drip of one report per second.
668 if (nr_shown == 60) {
669 if (time_before(jiffies, resume)) {
670 nr_unshown++;
671 return;
673 if (nr_unshown) {
674 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
675 nr_unshown);
676 nr_unshown = 0;
678 nr_shown = 0;
680 if (nr_shown++ == 0)
681 resume = jiffies + 60 * HZ;
683 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
684 index = linear_page_index(vma, addr);
686 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
687 current->comm,
688 (long long)pte_val(pte), (long long)pmd_val(*pmd));
689 if (page)
690 dump_page(page, "bad pte");
691 pr_alert("addr:%p vm_flags:%08lx anon_vma:%p mapping:%p index:%lx\n",
692 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
694 * Choose text because data symbols depend on CONFIG_KALLSYMS_ALL=y
696 pr_alert("file:%pD fault:%pf mmap:%pf readpage:%pf\n",
697 vma->vm_file,
698 vma->vm_ops ? vma->vm_ops->fault : NULL,
699 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
700 mapping ? mapping->a_ops->readpage : NULL);
701 dump_stack();
702 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
706 * vm_normal_page -- This function gets the "struct page" associated with a pte.
708 * "Special" mappings do not wish to be associated with a "struct page" (either
709 * it doesn't exist, or it exists but they don't want to touch it). In this
710 * case, NULL is returned here. "Normal" mappings do have a struct page.
712 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
713 * pte bit, in which case this function is trivial. Secondly, an architecture
714 * may not have a spare pte bit, which requires a more complicated scheme,
715 * described below.
717 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
718 * special mapping (even if there are underlying and valid "struct pages").
719 * COWed pages of a VM_PFNMAP are always normal.
721 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
722 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
723 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
724 * mapping will always honor the rule
726 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
728 * And for normal mappings this is false.
730 * This restricts such mappings to be a linear translation from virtual address
731 * to pfn. To get around this restriction, we allow arbitrary mappings so long
732 * as the vma is not a COW mapping; in that case, we know that all ptes are
733 * special (because none can have been COWed).
736 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
738 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
739 * page" backing, however the difference is that _all_ pages with a struct
740 * page (that is, those where pfn_valid is true) are refcounted and considered
741 * normal pages by the VM. The disadvantage is that pages are refcounted
742 * (which can be slower and simply not an option for some PFNMAP users). The
743 * advantage is that we don't have to follow the strict linearity rule of
744 * PFNMAP mappings in order to support COWable mappings.
747 #ifdef __HAVE_ARCH_PTE_SPECIAL
748 # define HAVE_PTE_SPECIAL 1
749 #else
750 # define HAVE_PTE_SPECIAL 0
751 #endif
752 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
753 pte_t pte)
755 unsigned long pfn = pte_pfn(pte);
757 if (HAVE_PTE_SPECIAL) {
758 if (likely(!pte_special(pte)))
759 goto check_pfn;
760 if (vma->vm_ops && vma->vm_ops->find_special_page)
761 return vma->vm_ops->find_special_page(vma, addr);
762 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
763 return NULL;
764 if (!is_zero_pfn(pfn))
765 print_bad_pte(vma, addr, pte, NULL);
766 return NULL;
769 /* !HAVE_PTE_SPECIAL case follows: */
771 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
772 if (vma->vm_flags & VM_MIXEDMAP) {
773 if (!pfn_valid(pfn))
774 return NULL;
775 goto out;
776 } else {
777 unsigned long off;
778 off = (addr - vma->vm_start) >> PAGE_SHIFT;
779 if (pfn == vma->vm_pgoff + off)
780 return NULL;
781 if (!is_cow_mapping(vma->vm_flags))
782 return NULL;
786 if (is_zero_pfn(pfn))
787 return NULL;
788 check_pfn:
789 if (unlikely(pfn > highest_memmap_pfn)) {
790 print_bad_pte(vma, addr, pte, NULL);
791 return NULL;
795 * NOTE! We still have PageReserved() pages in the page tables.
796 * eg. VDSO mappings can cause them to exist.
798 out:
799 return pfn_to_page(pfn);
802 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
803 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
804 pmd_t pmd)
806 unsigned long pfn = pmd_pfn(pmd);
809 * There is no pmd_special() but there may be special pmds, e.g.
810 * in a direct-access (dax) mapping, so let's just replicate the
811 * !HAVE_PTE_SPECIAL case from vm_normal_page() here.
813 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
814 if (vma->vm_flags & VM_MIXEDMAP) {
815 if (!pfn_valid(pfn))
816 return NULL;
817 goto out;
818 } else {
819 unsigned long off;
820 off = (addr - vma->vm_start) >> PAGE_SHIFT;
821 if (pfn == vma->vm_pgoff + off)
822 return NULL;
823 if (!is_cow_mapping(vma->vm_flags))
824 return NULL;
828 if (is_zero_pfn(pfn))
829 return NULL;
830 if (unlikely(pfn > highest_memmap_pfn))
831 return NULL;
834 * NOTE! We still have PageReserved() pages in the page tables.
835 * eg. VDSO mappings can cause them to exist.
837 out:
838 return pfn_to_page(pfn);
840 #endif
843 * copy one vm_area from one task to the other. Assumes the page tables
844 * already present in the new task to be cleared in the whole range
845 * covered by this vma.
848 static inline unsigned long
849 copy_one_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
850 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
851 unsigned long addr, int *rss)
853 unsigned long vm_flags = vma->vm_flags;
854 pte_t pte = *src_pte;
855 struct page *page;
857 /* pte contains position in swap or file, so copy. */
858 if (unlikely(!pte_present(pte))) {
859 swp_entry_t entry = pte_to_swp_entry(pte);
861 if (likely(!non_swap_entry(entry))) {
862 if (swap_duplicate(entry) < 0)
863 return entry.val;
865 /* make sure dst_mm is on swapoff's mmlist. */
866 if (unlikely(list_empty(&dst_mm->mmlist))) {
867 spin_lock(&mmlist_lock);
868 if (list_empty(&dst_mm->mmlist))
869 list_add(&dst_mm->mmlist,
870 &src_mm->mmlist);
871 spin_unlock(&mmlist_lock);
873 rss[MM_SWAPENTS]++;
874 } else if (is_migration_entry(entry)) {
875 page = migration_entry_to_page(entry);
877 rss[mm_counter(page)]++;
879 if (is_write_migration_entry(entry) &&
880 is_cow_mapping(vm_flags)) {
882 * COW mappings require pages in both
883 * parent and child to be set to read.
885 make_migration_entry_read(&entry);
886 pte = swp_entry_to_pte(entry);
887 if (pte_swp_soft_dirty(*src_pte))
888 pte = pte_swp_mksoft_dirty(pte);
889 set_pte_at(src_mm, addr, src_pte, pte);
892 goto out_set_pte;
896 * If it's a COW mapping, write protect it both
897 * in the parent and the child
899 if (is_cow_mapping(vm_flags)) {
900 ptep_set_wrprotect(src_mm, addr, src_pte);
901 pte = pte_wrprotect(pte);
905 * If it's a shared mapping, mark it clean in
906 * the child
908 if (vm_flags & VM_SHARED)
909 pte = pte_mkclean(pte);
910 pte = pte_mkold(pte);
912 page = vm_normal_page(vma, addr, pte);
913 if (page) {
914 get_page(page);
915 page_dup_rmap(page, false);
916 rss[mm_counter(page)]++;
919 out_set_pte:
920 set_pte_at(dst_mm, addr, dst_pte, pte);
921 return 0;
924 static int copy_pte_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
925 pmd_t *dst_pmd, pmd_t *src_pmd, struct vm_area_struct *vma,
926 unsigned long addr, unsigned long end)
928 pte_t *orig_src_pte, *orig_dst_pte;
929 pte_t *src_pte, *dst_pte;
930 spinlock_t *src_ptl, *dst_ptl;
931 int progress = 0;
932 int rss[NR_MM_COUNTERS];
933 swp_entry_t entry = (swp_entry_t){0};
935 again:
936 init_rss_vec(rss);
938 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
939 if (!dst_pte)
940 return -ENOMEM;
941 src_pte = pte_offset_map(src_pmd, addr);
942 src_ptl = pte_lockptr(src_mm, src_pmd);
943 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
944 orig_src_pte = src_pte;
945 orig_dst_pte = dst_pte;
946 arch_enter_lazy_mmu_mode();
948 do {
950 * We are holding two locks at this point - either of them
951 * could generate latencies in another task on another CPU.
953 if (progress >= 32) {
954 progress = 0;
955 if (need_resched() ||
956 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
957 break;
959 if (pte_none(*src_pte)) {
960 progress++;
961 continue;
963 entry.val = copy_one_pte(dst_mm, src_mm, dst_pte, src_pte,
964 vma, addr, rss);
965 if (entry.val)
966 break;
967 progress += 8;
968 } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
970 arch_leave_lazy_mmu_mode();
971 spin_unlock(src_ptl);
972 pte_unmap(orig_src_pte);
973 add_mm_rss_vec(dst_mm, rss);
974 pte_unmap_unlock(orig_dst_pte, dst_ptl);
975 cond_resched();
977 if (entry.val) {
978 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0)
979 return -ENOMEM;
980 progress = 0;
982 if (addr != end)
983 goto again;
984 return 0;
987 static inline int copy_pmd_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
988 pud_t *dst_pud, pud_t *src_pud, struct vm_area_struct *vma,
989 unsigned long addr, unsigned long end)
991 pmd_t *src_pmd, *dst_pmd;
992 unsigned long next;
994 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
995 if (!dst_pmd)
996 return -ENOMEM;
997 src_pmd = pmd_offset(src_pud, addr);
998 do {
999 next = pmd_addr_end(addr, end);
1000 if (pmd_trans_huge(*src_pmd) || pmd_devmap(*src_pmd)) {
1001 int err;
1002 VM_BUG_ON(next-addr != HPAGE_PMD_SIZE);
1003 err = copy_huge_pmd(dst_mm, src_mm,
1004 dst_pmd, src_pmd, addr, vma);
1005 if (err == -ENOMEM)
1006 return -ENOMEM;
1007 if (!err)
1008 continue;
1009 /* fall through */
1011 if (pmd_none_or_clear_bad(src_pmd))
1012 continue;
1013 if (copy_pte_range(dst_mm, src_mm, dst_pmd, src_pmd,
1014 vma, addr, next))
1015 return -ENOMEM;
1016 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1017 return 0;
1020 static inline int copy_pud_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1021 pgd_t *dst_pgd, pgd_t *src_pgd, struct vm_area_struct *vma,
1022 unsigned long addr, unsigned long end)
1024 pud_t *src_pud, *dst_pud;
1025 unsigned long next;
1027 dst_pud = pud_alloc(dst_mm, dst_pgd, addr);
1028 if (!dst_pud)
1029 return -ENOMEM;
1030 src_pud = pud_offset(src_pgd, addr);
1031 do {
1032 next = pud_addr_end(addr, end);
1033 if (pud_none_or_clear_bad(src_pud))
1034 continue;
1035 if (copy_pmd_range(dst_mm, src_mm, dst_pud, src_pud,
1036 vma, addr, next))
1037 return -ENOMEM;
1038 } while (dst_pud++, src_pud++, addr = next, addr != end);
1039 return 0;
1042 int copy_page_range(struct mm_struct *dst_mm, struct mm_struct *src_mm,
1043 struct vm_area_struct *vma)
1045 pgd_t *src_pgd, *dst_pgd;
1046 unsigned long next;
1047 unsigned long addr = vma->vm_start;
1048 unsigned long end = vma->vm_end;
1049 unsigned long mmun_start; /* For mmu_notifiers */
1050 unsigned long mmun_end; /* For mmu_notifiers */
1051 bool is_cow;
1052 int ret;
1055 * Don't copy ptes where a page fault will fill them correctly.
1056 * Fork becomes much lighter when there are big shared or private
1057 * readonly mappings. The tradeoff is that copy_page_range is more
1058 * efficient than faulting.
1060 if (!(vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1061 !vma->anon_vma)
1062 return 0;
1064 if (is_vm_hugetlb_page(vma))
1065 return copy_hugetlb_page_range(dst_mm, src_mm, vma);
1067 if (unlikely(vma->vm_flags & VM_PFNMAP)) {
1069 * We do not free on error cases below as remove_vma
1070 * gets called on error from higher level routine
1072 ret = track_pfn_copy(vma);
1073 if (ret)
1074 return ret;
1078 * We need to invalidate the secondary MMU mappings only when
1079 * there could be a permission downgrade on the ptes of the
1080 * parent mm. And a permission downgrade will only happen if
1081 * is_cow_mapping() returns true.
1083 is_cow = is_cow_mapping(vma->vm_flags);
1084 mmun_start = addr;
1085 mmun_end = end;
1086 if (is_cow)
1087 mmu_notifier_invalidate_range_start(src_mm, mmun_start,
1088 mmun_end);
1090 ret = 0;
1091 dst_pgd = pgd_offset(dst_mm, addr);
1092 src_pgd = pgd_offset(src_mm, addr);
1093 do {
1094 next = pgd_addr_end(addr, end);
1095 if (pgd_none_or_clear_bad(src_pgd))
1096 continue;
1097 if (unlikely(copy_pud_range(dst_mm, src_mm, dst_pgd, src_pgd,
1098 vma, addr, next))) {
1099 ret = -ENOMEM;
1100 break;
1102 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1104 if (is_cow)
1105 mmu_notifier_invalidate_range_end(src_mm, mmun_start, mmun_end);
1106 return ret;
1109 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1110 struct vm_area_struct *vma, pmd_t *pmd,
1111 unsigned long addr, unsigned long end,
1112 struct zap_details *details)
1114 struct mm_struct *mm = tlb->mm;
1115 int force_flush = 0;
1116 int rss[NR_MM_COUNTERS];
1117 spinlock_t *ptl;
1118 pte_t *start_pte;
1119 pte_t *pte;
1120 swp_entry_t entry;
1121 struct page *pending_page = NULL;
1123 again:
1124 init_rss_vec(rss);
1125 start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1126 pte = start_pte;
1127 flush_tlb_batched_pending(mm);
1128 arch_enter_lazy_mmu_mode();
1129 do {
1130 pte_t ptent = *pte;
1131 if (pte_none(ptent)) {
1132 continue;
1135 if (pte_present(ptent)) {
1136 struct page *page;
1138 page = vm_normal_page(vma, addr, ptent);
1139 if (unlikely(details) && page) {
1141 * unmap_shared_mapping_pages() wants to
1142 * invalidate cache without truncating:
1143 * unmap shared but keep private pages.
1145 if (details->check_mapping &&
1146 details->check_mapping != page_rmapping(page))
1147 continue;
1149 ptent = ptep_get_and_clear_full(mm, addr, pte,
1150 tlb->fullmm);
1151 tlb_remove_tlb_entry(tlb, pte, addr);
1152 if (unlikely(!page))
1153 continue;
1155 if (!PageAnon(page)) {
1156 if (pte_dirty(ptent)) {
1158 * oom_reaper cannot tear down dirty
1159 * pages
1161 if (unlikely(details && details->ignore_dirty))
1162 continue;
1163 force_flush = 1;
1164 set_page_dirty(page);
1166 if (pte_young(ptent) &&
1167 likely(!(vma->vm_flags & VM_SEQ_READ)))
1168 mark_page_accessed(page);
1170 rss[mm_counter(page)]--;
1171 page_remove_rmap(page, false);
1172 if (unlikely(page_mapcount(page) < 0))
1173 print_bad_pte(vma, addr, ptent, page);
1174 if (unlikely(__tlb_remove_page(tlb, page))) {
1175 force_flush = 1;
1176 pending_page = page;
1177 addr += PAGE_SIZE;
1178 break;
1180 continue;
1182 /* only check swap_entries if explicitly asked for in details */
1183 if (unlikely(details && !details->check_swap_entries))
1184 continue;
1186 entry = pte_to_swp_entry(ptent);
1187 if (!non_swap_entry(entry))
1188 rss[MM_SWAPENTS]--;
1189 else if (is_migration_entry(entry)) {
1190 struct page *page;
1192 page = migration_entry_to_page(entry);
1193 rss[mm_counter(page)]--;
1195 if (unlikely(!free_swap_and_cache(entry)))
1196 print_bad_pte(vma, addr, ptent, NULL);
1197 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1198 } while (pte++, addr += PAGE_SIZE, addr != end);
1200 add_mm_rss_vec(mm, rss);
1201 arch_leave_lazy_mmu_mode();
1203 /* Do the actual TLB flush before dropping ptl */
1204 if (force_flush)
1205 tlb_flush_mmu_tlbonly(tlb);
1206 pte_unmap_unlock(start_pte, ptl);
1209 * If we forced a TLB flush (either due to running out of
1210 * batch buffers or because we needed to flush dirty TLB
1211 * entries before releasing the ptl), free the batched
1212 * memory too. Restart if we didn't do everything.
1214 if (force_flush) {
1215 force_flush = 0;
1216 tlb_flush_mmu_free(tlb);
1217 if (pending_page) {
1218 /* remove the page with new size */
1219 __tlb_remove_pte_page(tlb, pending_page);
1220 pending_page = NULL;
1222 if (addr != end)
1223 goto again;
1226 return addr;
1229 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1230 struct vm_area_struct *vma, pud_t *pud,
1231 unsigned long addr, unsigned long end,
1232 struct zap_details *details)
1234 pmd_t *pmd;
1235 unsigned long next;
1237 pmd = pmd_offset(pud, addr);
1238 do {
1239 next = pmd_addr_end(addr, end);
1240 if (pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1241 if (next - addr != HPAGE_PMD_SIZE) {
1242 VM_BUG_ON_VMA(vma_is_anonymous(vma) &&
1243 !rwsem_is_locked(&tlb->mm->mmap_sem), vma);
1244 split_huge_pmd(vma, pmd, addr);
1245 } else if (zap_huge_pmd(tlb, vma, pmd, addr))
1246 goto next;
1247 /* fall through */
1250 * Here there can be other concurrent MADV_DONTNEED or
1251 * trans huge page faults running, and if the pmd is
1252 * none or trans huge it can change under us. This is
1253 * because MADV_DONTNEED holds the mmap_sem in read
1254 * mode.
1256 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1257 goto next;
1258 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1259 next:
1260 cond_resched();
1261 } while (pmd++, addr = next, addr != end);
1263 return addr;
1266 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1267 struct vm_area_struct *vma, pgd_t *pgd,
1268 unsigned long addr, unsigned long end,
1269 struct zap_details *details)
1271 pud_t *pud;
1272 unsigned long next;
1274 pud = pud_offset(pgd, addr);
1275 do {
1276 next = pud_addr_end(addr, end);
1277 if (pud_none_or_clear_bad(pud))
1278 continue;
1279 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1280 } while (pud++, addr = next, addr != end);
1282 return addr;
1285 void unmap_page_range(struct mmu_gather *tlb,
1286 struct vm_area_struct *vma,
1287 unsigned long addr, unsigned long end,
1288 struct zap_details *details)
1290 pgd_t *pgd;
1291 unsigned long next;
1293 BUG_ON(addr >= end);
1294 tlb_start_vma(tlb, vma);
1295 pgd = pgd_offset(vma->vm_mm, addr);
1296 do {
1297 next = pgd_addr_end(addr, end);
1298 if (pgd_none_or_clear_bad(pgd))
1299 continue;
1300 next = zap_pud_range(tlb, vma, pgd, addr, next, details);
1301 } while (pgd++, addr = next, addr != end);
1302 tlb_end_vma(tlb, vma);
1306 static void unmap_single_vma(struct mmu_gather *tlb,
1307 struct vm_area_struct *vma, unsigned long start_addr,
1308 unsigned long end_addr,
1309 struct zap_details *details)
1311 unsigned long start = max(vma->vm_start, start_addr);
1312 unsigned long end;
1314 if (start >= vma->vm_end)
1315 return;
1316 end = min(vma->vm_end, end_addr);
1317 if (end <= vma->vm_start)
1318 return;
1320 if (vma->vm_file)
1321 uprobe_munmap(vma, start, end);
1323 if (unlikely(vma->vm_flags & VM_PFNMAP))
1324 untrack_pfn(vma, 0, 0);
1326 if (start != end) {
1327 if (unlikely(is_vm_hugetlb_page(vma))) {
1329 * It is undesirable to test vma->vm_file as it
1330 * should be non-null for valid hugetlb area.
1331 * However, vm_file will be NULL in the error
1332 * cleanup path of mmap_region. When
1333 * hugetlbfs ->mmap method fails,
1334 * mmap_region() nullifies vma->vm_file
1335 * before calling this function to clean up.
1336 * Since no pte has actually been setup, it is
1337 * safe to do nothing in this case.
1339 if (vma->vm_file) {
1340 i_mmap_lock_write(vma->vm_file->f_mapping);
1341 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1342 i_mmap_unlock_write(vma->vm_file->f_mapping);
1344 } else
1345 unmap_page_range(tlb, vma, start, end, details);
1350 * unmap_vmas - unmap a range of memory covered by a list of vma's
1351 * @tlb: address of the caller's struct mmu_gather
1352 * @vma: the starting vma
1353 * @start_addr: virtual address at which to start unmapping
1354 * @end_addr: virtual address at which to end unmapping
1356 * Unmap all pages in the vma list.
1358 * Only addresses between `start' and `end' will be unmapped.
1360 * The VMA list must be sorted in ascending virtual address order.
1362 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1363 * range after unmap_vmas() returns. So the only responsibility here is to
1364 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1365 * drops the lock and schedules.
1367 void unmap_vmas(struct mmu_gather *tlb,
1368 struct vm_area_struct *vma, unsigned long start_addr,
1369 unsigned long end_addr)
1371 struct mm_struct *mm = vma->vm_mm;
1373 mmu_notifier_invalidate_range_start(mm, start_addr, end_addr);
1374 for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1375 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1376 mmu_notifier_invalidate_range_end(mm, start_addr, end_addr);
1380 * zap_page_range - remove user pages in a given range
1381 * @vma: vm_area_struct holding the applicable pages
1382 * @start: starting address of pages to zap
1383 * @size: number of bytes to zap
1384 * @details: details of shared cache invalidation
1386 * Caller must protect the VMA list
1388 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1389 unsigned long size, struct zap_details *details)
1391 struct mm_struct *mm = vma->vm_mm;
1392 struct mmu_gather tlb;
1393 unsigned long end = start + size;
1395 lru_add_drain();
1396 tlb_gather_mmu(&tlb, mm, start, end);
1397 update_hiwater_rss(mm);
1398 mmu_notifier_invalidate_range_start(mm, start, end);
1399 for ( ; vma && vma->vm_start < end; vma = vma->vm_next)
1400 unmap_single_vma(&tlb, vma, start, end, details);
1401 mmu_notifier_invalidate_range_end(mm, start, end);
1402 tlb_finish_mmu(&tlb, start, end);
1406 * zap_page_range_single - remove user pages in a given range
1407 * @vma: vm_area_struct holding the applicable pages
1408 * @address: starting address of pages to zap
1409 * @size: number of bytes to zap
1410 * @details: details of shared cache invalidation
1412 * The range must fit into one VMA.
1414 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1415 unsigned long size, struct zap_details *details)
1417 struct mm_struct *mm = vma->vm_mm;
1418 struct mmu_gather tlb;
1419 unsigned long end = address + size;
1421 lru_add_drain();
1422 tlb_gather_mmu(&tlb, mm, address, end);
1423 update_hiwater_rss(mm);
1424 mmu_notifier_invalidate_range_start(mm, address, end);
1425 unmap_single_vma(&tlb, vma, address, end, details);
1426 mmu_notifier_invalidate_range_end(mm, address, end);
1427 tlb_finish_mmu(&tlb, address, end);
1431 * zap_vma_ptes - remove ptes mapping the vma
1432 * @vma: vm_area_struct holding ptes to be zapped
1433 * @address: starting address of pages to zap
1434 * @size: number of bytes to zap
1436 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1438 * The entire address range must be fully contained within the vma.
1440 * Returns 0 if successful.
1442 int zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1443 unsigned long size)
1445 if (address < vma->vm_start || address + size > vma->vm_end ||
1446 !(vma->vm_flags & VM_PFNMAP))
1447 return -1;
1448 zap_page_range_single(vma, address, size, NULL);
1449 return 0;
1451 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1453 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1454 spinlock_t **ptl)
1456 pgd_t * pgd = pgd_offset(mm, addr);
1457 pud_t * pud = pud_alloc(mm, pgd, addr);
1458 if (pud) {
1459 pmd_t * pmd = pmd_alloc(mm, pud, addr);
1460 if (pmd) {
1461 VM_BUG_ON(pmd_trans_huge(*pmd));
1462 return pte_alloc_map_lock(mm, pmd, addr, ptl);
1465 return NULL;
1469 * This is the old fallback for page remapping.
1471 * For historical reasons, it only allows reserved pages. Only
1472 * old drivers should use this, and they needed to mark their
1473 * pages reserved for the old functions anyway.
1475 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1476 struct page *page, pgprot_t prot)
1478 struct mm_struct *mm = vma->vm_mm;
1479 int retval;
1480 pte_t *pte;
1481 spinlock_t *ptl;
1483 retval = -EINVAL;
1484 if (PageAnon(page))
1485 goto out;
1486 retval = -ENOMEM;
1487 flush_dcache_page(page);
1488 pte = get_locked_pte(mm, addr, &ptl);
1489 if (!pte)
1490 goto out;
1491 retval = -EBUSY;
1492 if (!pte_none(*pte))
1493 goto out_unlock;
1495 /* Ok, finally just insert the thing.. */
1496 get_page(page);
1497 inc_mm_counter_fast(mm, mm_counter_file(page));
1498 page_add_file_rmap(page, false);
1499 set_pte_at(mm, addr, pte, mk_pte(page, prot));
1501 retval = 0;
1502 pte_unmap_unlock(pte, ptl);
1503 return retval;
1504 out_unlock:
1505 pte_unmap_unlock(pte, ptl);
1506 out:
1507 return retval;
1511 * vm_insert_page - insert single page into user vma
1512 * @vma: user vma to map to
1513 * @addr: target user address of this page
1514 * @page: source kernel page
1516 * This allows drivers to insert individual pages they've allocated
1517 * into a user vma.
1519 * The page has to be a nice clean _individual_ kernel allocation.
1520 * If you allocate a compound page, you need to have marked it as
1521 * such (__GFP_COMP), or manually just split the page up yourself
1522 * (see split_page()).
1524 * NOTE! Traditionally this was done with "remap_pfn_range()" which
1525 * took an arbitrary page protection parameter. This doesn't allow
1526 * that. Your vma protection will have to be set up correctly, which
1527 * means that if you want a shared writable mapping, you'd better
1528 * ask for a shared writable mapping!
1530 * The page does not need to be reserved.
1532 * Usually this function is called from f_op->mmap() handler
1533 * under mm->mmap_sem write-lock, so it can change vma->vm_flags.
1534 * Caller must set VM_MIXEDMAP on vma if it wants to call this
1535 * function from other places, for example from page-fault handler.
1537 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1538 struct page *page)
1540 if (addr < vma->vm_start || addr >= vma->vm_end)
1541 return -EFAULT;
1542 if (!page_count(page))
1543 return -EINVAL;
1544 if (!(vma->vm_flags & VM_MIXEDMAP)) {
1545 BUG_ON(down_read_trylock(&vma->vm_mm->mmap_sem));
1546 BUG_ON(vma->vm_flags & VM_PFNMAP);
1547 vma->vm_flags |= VM_MIXEDMAP;
1549 return insert_page(vma, addr, page, vma->vm_page_prot);
1551 EXPORT_SYMBOL(vm_insert_page);
1553 static int insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1554 pfn_t pfn, pgprot_t prot)
1556 struct mm_struct *mm = vma->vm_mm;
1557 int retval;
1558 pte_t *pte, entry;
1559 spinlock_t *ptl;
1561 retval = -ENOMEM;
1562 pte = get_locked_pte(mm, addr, &ptl);
1563 if (!pte)
1564 goto out;
1565 retval = -EBUSY;
1566 if (!pte_none(*pte))
1567 goto out_unlock;
1569 /* Ok, finally just insert the thing.. */
1570 if (pfn_t_devmap(pfn))
1571 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
1572 else
1573 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
1574 set_pte_at(mm, addr, pte, entry);
1575 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
1577 retval = 0;
1578 out_unlock:
1579 pte_unmap_unlock(pte, ptl);
1580 out:
1581 return retval;
1585 * vm_insert_pfn - insert single pfn into user vma
1586 * @vma: user vma to map to
1587 * @addr: target user address of this page
1588 * @pfn: source kernel pfn
1590 * Similar to vm_insert_page, this allows drivers to insert individual pages
1591 * they've allocated into a user vma. Same comments apply.
1593 * This function should only be called from a vm_ops->fault handler, and
1594 * in that case the handler should return NULL.
1596 * vma cannot be a COW mapping.
1598 * As this is called only for pages that do not currently exist, we
1599 * do not need to flush old virtual caches or the TLB.
1601 int vm_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1602 unsigned long pfn)
1604 return vm_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
1606 EXPORT_SYMBOL(vm_insert_pfn);
1609 * vm_insert_pfn_prot - insert single pfn into user vma with specified pgprot
1610 * @vma: user vma to map to
1611 * @addr: target user address of this page
1612 * @pfn: source kernel pfn
1613 * @pgprot: pgprot flags for the inserted page
1615 * This is exactly like vm_insert_pfn, except that it allows drivers to
1616 * to override pgprot on a per-page basis.
1618 * This only makes sense for IO mappings, and it makes no sense for
1619 * cow mappings. In general, using multiple vmas is preferable;
1620 * vm_insert_pfn_prot should only be used if using multiple VMAs is
1621 * impractical.
1623 int vm_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
1624 unsigned long pfn, pgprot_t pgprot)
1626 int ret;
1628 * Technically, architectures with pte_special can avoid all these
1629 * restrictions (same for remap_pfn_range). However we would like
1630 * consistency in testing and feature parity among all, so we should
1631 * try to keep these invariants in place for everybody.
1633 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
1634 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
1635 (VM_PFNMAP|VM_MIXEDMAP));
1636 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
1637 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
1639 if (addr < vma->vm_start || addr >= vma->vm_end)
1640 return -EFAULT;
1641 if (track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV)))
1642 return -EINVAL;
1644 ret = insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot);
1646 return ret;
1648 EXPORT_SYMBOL(vm_insert_pfn_prot);
1650 int vm_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
1651 pfn_t pfn)
1653 pgprot_t pgprot = vma->vm_page_prot;
1655 BUG_ON(!(vma->vm_flags & VM_MIXEDMAP));
1657 if (addr < vma->vm_start || addr >= vma->vm_end)
1658 return -EFAULT;
1659 if (track_pfn_insert(vma, &pgprot, pfn))
1660 return -EINVAL;
1663 * If we don't have pte special, then we have to use the pfn_valid()
1664 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
1665 * refcount the page if pfn_valid is true (hence insert_page rather
1666 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
1667 * without pte special, it would there be refcounted as a normal page.
1669 if (!HAVE_PTE_SPECIAL && !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
1670 struct page *page;
1673 * At this point we are committed to insert_page()
1674 * regardless of whether the caller specified flags that
1675 * result in pfn_t_has_page() == false.
1677 page = pfn_to_page(pfn_t_to_pfn(pfn));
1678 return insert_page(vma, addr, page, pgprot);
1680 return insert_pfn(vma, addr, pfn, pgprot);
1682 EXPORT_SYMBOL(vm_insert_mixed);
1685 * maps a range of physical memory into the requested pages. the old
1686 * mappings are removed. any references to nonexistent pages results
1687 * in null mappings (currently treated as "copy-on-access")
1689 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
1690 unsigned long addr, unsigned long end,
1691 unsigned long pfn, pgprot_t prot)
1693 pte_t *pte;
1694 spinlock_t *ptl;
1696 pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
1697 if (!pte)
1698 return -ENOMEM;
1699 arch_enter_lazy_mmu_mode();
1700 do {
1701 BUG_ON(!pte_none(*pte));
1702 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
1703 pfn++;
1704 } while (pte++, addr += PAGE_SIZE, addr != end);
1705 arch_leave_lazy_mmu_mode();
1706 pte_unmap_unlock(pte - 1, ptl);
1707 return 0;
1710 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
1711 unsigned long addr, unsigned long end,
1712 unsigned long pfn, pgprot_t prot)
1714 pmd_t *pmd;
1715 unsigned long next;
1717 pfn -= addr >> PAGE_SHIFT;
1718 pmd = pmd_alloc(mm, pud, addr);
1719 if (!pmd)
1720 return -ENOMEM;
1721 VM_BUG_ON(pmd_trans_huge(*pmd));
1722 do {
1723 next = pmd_addr_end(addr, end);
1724 if (remap_pte_range(mm, pmd, addr, next,
1725 pfn + (addr >> PAGE_SHIFT), prot))
1726 return -ENOMEM;
1727 } while (pmd++, addr = next, addr != end);
1728 return 0;
1731 static inline int remap_pud_range(struct mm_struct *mm, pgd_t *pgd,
1732 unsigned long addr, unsigned long end,
1733 unsigned long pfn, pgprot_t prot)
1735 pud_t *pud;
1736 unsigned long next;
1738 pfn -= addr >> PAGE_SHIFT;
1739 pud = pud_alloc(mm, pgd, addr);
1740 if (!pud)
1741 return -ENOMEM;
1742 do {
1743 next = pud_addr_end(addr, end);
1744 if (remap_pmd_range(mm, pud, addr, next,
1745 pfn + (addr >> PAGE_SHIFT), prot))
1746 return -ENOMEM;
1747 } while (pud++, addr = next, addr != end);
1748 return 0;
1752 * remap_pfn_range - remap kernel memory to userspace
1753 * @vma: user vma to map to
1754 * @addr: target user address to start at
1755 * @pfn: physical address of kernel memory
1756 * @size: size of map area
1757 * @prot: page protection flags for this mapping
1759 * Note: this is only safe if the mm semaphore is held when called.
1761 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
1762 unsigned long pfn, unsigned long size, pgprot_t prot)
1764 pgd_t *pgd;
1765 unsigned long next;
1766 unsigned long end = addr + PAGE_ALIGN(size);
1767 struct mm_struct *mm = vma->vm_mm;
1768 unsigned long remap_pfn = pfn;
1769 int err;
1772 * Physically remapped pages are special. Tell the
1773 * rest of the world about it:
1774 * VM_IO tells people not to look at these pages
1775 * (accesses can have side effects).
1776 * VM_PFNMAP tells the core MM that the base pages are just
1777 * raw PFN mappings, and do not have a "struct page" associated
1778 * with them.
1779 * VM_DONTEXPAND
1780 * Disable vma merging and expanding with mremap().
1781 * VM_DONTDUMP
1782 * Omit vma from core dump, even when VM_IO turned off.
1784 * There's a horrible special case to handle copy-on-write
1785 * behaviour that some programs depend on. We mark the "original"
1786 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
1787 * See vm_normal_page() for details.
1789 if (is_cow_mapping(vma->vm_flags)) {
1790 if (addr != vma->vm_start || end != vma->vm_end)
1791 return -EINVAL;
1792 vma->vm_pgoff = pfn;
1795 err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
1796 if (err)
1797 return -EINVAL;
1799 vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
1801 BUG_ON(addr >= end);
1802 pfn -= addr >> PAGE_SHIFT;
1803 pgd = pgd_offset(mm, addr);
1804 flush_cache_range(vma, addr, end);
1805 do {
1806 next = pgd_addr_end(addr, end);
1807 err = remap_pud_range(mm, pgd, addr, next,
1808 pfn + (addr >> PAGE_SHIFT), prot);
1809 if (err)
1810 break;
1811 } while (pgd++, addr = next, addr != end);
1813 if (err)
1814 untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
1816 return err;
1818 EXPORT_SYMBOL(remap_pfn_range);
1821 * vm_iomap_memory - remap memory to userspace
1822 * @vma: user vma to map to
1823 * @start: start of area
1824 * @len: size of area
1826 * This is a simplified io_remap_pfn_range() for common driver use. The
1827 * driver just needs to give us the physical memory range to be mapped,
1828 * we'll figure out the rest from the vma information.
1830 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
1831 * whatever write-combining details or similar.
1833 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
1835 unsigned long vm_len, pfn, pages;
1837 /* Check that the physical memory area passed in looks valid */
1838 if (start + len < start)
1839 return -EINVAL;
1841 * You *really* shouldn't map things that aren't page-aligned,
1842 * but we've historically allowed it because IO memory might
1843 * just have smaller alignment.
1845 len += start & ~PAGE_MASK;
1846 pfn = start >> PAGE_SHIFT;
1847 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
1848 if (pfn + pages < pfn)
1849 return -EINVAL;
1851 /* We start the mapping 'vm_pgoff' pages into the area */
1852 if (vma->vm_pgoff > pages)
1853 return -EINVAL;
1854 pfn += vma->vm_pgoff;
1855 pages -= vma->vm_pgoff;
1857 /* Can we fit all of the mapping? */
1858 vm_len = vma->vm_end - vma->vm_start;
1859 if (vm_len >> PAGE_SHIFT > pages)
1860 return -EINVAL;
1862 /* Ok, let it rip */
1863 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
1865 EXPORT_SYMBOL(vm_iomap_memory);
1867 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
1868 unsigned long addr, unsigned long end,
1869 pte_fn_t fn, void *data)
1871 pte_t *pte;
1872 int err;
1873 pgtable_t token;
1874 spinlock_t *uninitialized_var(ptl);
1876 pte = (mm == &init_mm) ?
1877 pte_alloc_kernel(pmd, addr) :
1878 pte_alloc_map_lock(mm, pmd, addr, &ptl);
1879 if (!pte)
1880 return -ENOMEM;
1882 BUG_ON(pmd_huge(*pmd));
1884 arch_enter_lazy_mmu_mode();
1886 token = pmd_pgtable(*pmd);
1888 do {
1889 err = fn(pte++, token, addr, data);
1890 if (err)
1891 break;
1892 } while (addr += PAGE_SIZE, addr != end);
1894 arch_leave_lazy_mmu_mode();
1896 if (mm != &init_mm)
1897 pte_unmap_unlock(pte-1, ptl);
1898 return err;
1901 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
1902 unsigned long addr, unsigned long end,
1903 pte_fn_t fn, void *data)
1905 pmd_t *pmd;
1906 unsigned long next;
1907 int err;
1909 BUG_ON(pud_huge(*pud));
1911 pmd = pmd_alloc(mm, pud, addr);
1912 if (!pmd)
1913 return -ENOMEM;
1914 do {
1915 next = pmd_addr_end(addr, end);
1916 err = apply_to_pte_range(mm, pmd, addr, next, fn, data);
1917 if (err)
1918 break;
1919 } while (pmd++, addr = next, addr != end);
1920 return err;
1923 static int apply_to_pud_range(struct mm_struct *mm, pgd_t *pgd,
1924 unsigned long addr, unsigned long end,
1925 pte_fn_t fn, void *data)
1927 pud_t *pud;
1928 unsigned long next;
1929 int err;
1931 pud = pud_alloc(mm, pgd, addr);
1932 if (!pud)
1933 return -ENOMEM;
1934 do {
1935 next = pud_addr_end(addr, end);
1936 err = apply_to_pmd_range(mm, pud, addr, next, fn, data);
1937 if (err)
1938 break;
1939 } while (pud++, addr = next, addr != end);
1940 return err;
1944 * Scan a region of virtual memory, filling in page tables as necessary
1945 * and calling a provided function on each leaf page table.
1947 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
1948 unsigned long size, pte_fn_t fn, void *data)
1950 pgd_t *pgd;
1951 unsigned long next;
1952 unsigned long end = addr + size;
1953 int err;
1955 if (WARN_ON(addr >= end))
1956 return -EINVAL;
1958 pgd = pgd_offset(mm, addr);
1959 do {
1960 next = pgd_addr_end(addr, end);
1961 err = apply_to_pud_range(mm, pgd, addr, next, fn, data);
1962 if (err)
1963 break;
1964 } while (pgd++, addr = next, addr != end);
1966 return err;
1968 EXPORT_SYMBOL_GPL(apply_to_page_range);
1971 * handle_pte_fault chooses page fault handler according to an entry which was
1972 * read non-atomically. Before making any commitment, on those architectures
1973 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
1974 * parts, do_swap_page must check under lock before unmapping the pte and
1975 * proceeding (but do_wp_page is only called after already making such a check;
1976 * and do_anonymous_page can safely check later on).
1978 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
1979 pte_t *page_table, pte_t orig_pte)
1981 int same = 1;
1982 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT)
1983 if (sizeof(pte_t) > sizeof(unsigned long)) {
1984 spinlock_t *ptl = pte_lockptr(mm, pmd);
1985 spin_lock(ptl);
1986 same = pte_same(*page_table, orig_pte);
1987 spin_unlock(ptl);
1989 #endif
1990 pte_unmap(page_table);
1991 return same;
1994 static inline void cow_user_page(struct page *dst, struct page *src, unsigned long va, struct vm_area_struct *vma)
1996 debug_dma_assert_idle(src);
1999 * If the source page was a PFN mapping, we don't have
2000 * a "struct page" for it. We do a best-effort copy by
2001 * just copying from the original user address. If that
2002 * fails, we just zero-fill it. Live with it.
2004 if (unlikely(!src)) {
2005 void *kaddr = kmap_atomic(dst);
2006 void __user *uaddr = (void __user *)(va & PAGE_MASK);
2009 * This really shouldn't fail, because the page is there
2010 * in the page tables. But it might just be unreadable,
2011 * in which case we just give up and fill the result with
2012 * zeroes.
2014 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE))
2015 clear_page(kaddr);
2016 kunmap_atomic(kaddr);
2017 flush_dcache_page(dst);
2018 } else
2019 copy_user_highpage(dst, src, va, vma);
2022 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2024 struct file *vm_file = vma->vm_file;
2026 if (vm_file)
2027 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2030 * Special mappings (e.g. VDSO) do not have any file so fake
2031 * a default GFP_KERNEL for them.
2033 return GFP_KERNEL;
2037 * Notify the address space that the page is about to become writable so that
2038 * it can prohibit this or wait for the page to get into an appropriate state.
2040 * We do this without the lock held, so that it can sleep if it needs to.
2042 static int do_page_mkwrite(struct vm_area_struct *vma, struct page *page,
2043 unsigned long address)
2045 struct vm_fault vmf;
2046 int ret;
2048 vmf.virtual_address = (void __user *)(address & PAGE_MASK);
2049 vmf.pgoff = page->index;
2050 vmf.flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2051 vmf.gfp_mask = __get_fault_gfp_mask(vma);
2052 vmf.page = page;
2053 vmf.cow_page = NULL;
2055 ret = vma->vm_ops->page_mkwrite(vma, &vmf);
2056 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2057 return ret;
2058 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2059 lock_page(page);
2060 if (!page->mapping) {
2061 unlock_page(page);
2062 return 0; /* retry */
2064 ret |= VM_FAULT_LOCKED;
2065 } else
2066 VM_BUG_ON_PAGE(!PageLocked(page), page);
2067 return ret;
2071 * Handle write page faults for pages that can be reused in the current vma
2073 * This can happen either due to the mapping being with the VM_SHARED flag,
2074 * or due to us being the last reference standing to the page. In either
2075 * case, all we need to do here is to mark the page as writable and update
2076 * any related book-keeping.
2078 static inline int wp_page_reuse(struct fault_env *fe, pte_t orig_pte,
2079 struct page *page, int page_mkwrite, int dirty_shared)
2080 __releases(fe->ptl)
2082 struct vm_area_struct *vma = fe->vma;
2083 pte_t entry;
2085 * Clear the pages cpupid information as the existing
2086 * information potentially belongs to a now completely
2087 * unrelated process.
2089 if (page)
2090 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2092 flush_cache_page(vma, fe->address, pte_pfn(orig_pte));
2093 entry = pte_mkyoung(orig_pte);
2094 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2095 if (ptep_set_access_flags(vma, fe->address, fe->pte, entry, 1))
2096 update_mmu_cache(vma, fe->address, fe->pte);
2097 pte_unmap_unlock(fe->pte, fe->ptl);
2099 if (dirty_shared) {
2100 struct address_space *mapping;
2101 int dirtied;
2103 if (!page_mkwrite)
2104 lock_page(page);
2106 dirtied = set_page_dirty(page);
2107 VM_BUG_ON_PAGE(PageAnon(page), page);
2108 mapping = page->mapping;
2109 unlock_page(page);
2110 put_page(page);
2112 if ((dirtied || page_mkwrite) && mapping) {
2114 * Some device drivers do not set page.mapping
2115 * but still dirty their pages
2117 balance_dirty_pages_ratelimited(mapping);
2120 if (!page_mkwrite)
2121 file_update_time(vma->vm_file);
2124 return VM_FAULT_WRITE;
2128 * Handle the case of a page which we actually need to copy to a new page.
2130 * Called with mmap_sem locked and the old page referenced, but
2131 * without the ptl held.
2133 * High level logic flow:
2135 * - Allocate a page, copy the content of the old page to the new one.
2136 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2137 * - Take the PTL. If the pte changed, bail out and release the allocated page
2138 * - If the pte is still the way we remember it, update the page table and all
2139 * relevant references. This includes dropping the reference the page-table
2140 * held to the old page, as well as updating the rmap.
2141 * - In any case, unlock the PTL and drop the reference we took to the old page.
2143 static int wp_page_copy(struct fault_env *fe, pte_t orig_pte,
2144 struct page *old_page)
2146 struct vm_area_struct *vma = fe->vma;
2147 struct mm_struct *mm = vma->vm_mm;
2148 struct page *new_page = NULL;
2149 pte_t entry;
2150 int page_copied = 0;
2151 const unsigned long mmun_start = fe->address & PAGE_MASK;
2152 const unsigned long mmun_end = mmun_start + PAGE_SIZE;
2153 struct mem_cgroup *memcg;
2155 if (unlikely(anon_vma_prepare(vma)))
2156 goto oom;
2158 if (is_zero_pfn(pte_pfn(orig_pte))) {
2159 new_page = alloc_zeroed_user_highpage_movable(vma, fe->address);
2160 if (!new_page)
2161 goto oom;
2162 } else {
2163 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2164 fe->address);
2165 if (!new_page)
2166 goto oom;
2167 cow_user_page(new_page, old_page, fe->address, vma);
2170 if (mem_cgroup_try_charge(new_page, mm, GFP_KERNEL, &memcg, false))
2171 goto oom_free_new;
2173 __SetPageUptodate(new_page);
2175 mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end);
2178 * Re-check the pte - we dropped the lock
2180 fe->pte = pte_offset_map_lock(mm, fe->pmd, fe->address, &fe->ptl);
2181 if (likely(pte_same(*fe->pte, orig_pte))) {
2182 if (old_page) {
2183 if (!PageAnon(old_page)) {
2184 dec_mm_counter_fast(mm,
2185 mm_counter_file(old_page));
2186 inc_mm_counter_fast(mm, MM_ANONPAGES);
2188 } else {
2189 inc_mm_counter_fast(mm, MM_ANONPAGES);
2191 flush_cache_page(vma, fe->address, pte_pfn(orig_pte));
2192 entry = mk_pte(new_page, vma->vm_page_prot);
2193 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2195 * Clear the pte entry and flush it first, before updating the
2196 * pte with the new entry. This will avoid a race condition
2197 * seen in the presence of one thread doing SMC and another
2198 * thread doing COW.
2200 ptep_clear_flush_notify(vma, fe->address, fe->pte);
2201 page_add_new_anon_rmap(new_page, vma, fe->address, false);
2202 mem_cgroup_commit_charge(new_page, memcg, false, false);
2203 lru_cache_add_active_or_unevictable(new_page, vma);
2205 * We call the notify macro here because, when using secondary
2206 * mmu page tables (such as kvm shadow page tables), we want the
2207 * new page to be mapped directly into the secondary page table.
2209 set_pte_at_notify(mm, fe->address, fe->pte, entry);
2210 update_mmu_cache(vma, fe->address, fe->pte);
2211 if (old_page) {
2213 * Only after switching the pte to the new page may
2214 * we remove the mapcount here. Otherwise another
2215 * process may come and find the rmap count decremented
2216 * before the pte is switched to the new page, and
2217 * "reuse" the old page writing into it while our pte
2218 * here still points into it and can be read by other
2219 * threads.
2221 * The critical issue is to order this
2222 * page_remove_rmap with the ptp_clear_flush above.
2223 * Those stores are ordered by (if nothing else,)
2224 * the barrier present in the atomic_add_negative
2225 * in page_remove_rmap.
2227 * Then the TLB flush in ptep_clear_flush ensures that
2228 * no process can access the old page before the
2229 * decremented mapcount is visible. And the old page
2230 * cannot be reused until after the decremented
2231 * mapcount is visible. So transitively, TLBs to
2232 * old page will be flushed before it can be reused.
2234 page_remove_rmap(old_page, false);
2237 /* Free the old page.. */
2238 new_page = old_page;
2239 page_copied = 1;
2240 } else {
2241 mem_cgroup_cancel_charge(new_page, memcg, false);
2244 if (new_page)
2245 put_page(new_page);
2247 pte_unmap_unlock(fe->pte, fe->ptl);
2248 mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end);
2249 if (old_page) {
2251 * Don't let another task, with possibly unlocked vma,
2252 * keep the mlocked page.
2254 if (page_copied && (vma->vm_flags & VM_LOCKED)) {
2255 lock_page(old_page); /* LRU manipulation */
2256 if (PageMlocked(old_page))
2257 munlock_vma_page(old_page);
2258 unlock_page(old_page);
2260 put_page(old_page);
2262 return page_copied ? VM_FAULT_WRITE : 0;
2263 oom_free_new:
2264 put_page(new_page);
2265 oom:
2266 if (old_page)
2267 put_page(old_page);
2268 return VM_FAULT_OOM;
2272 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
2273 * mapping
2275 static int wp_pfn_shared(struct fault_env *fe, pte_t orig_pte)
2277 struct vm_area_struct *vma = fe->vma;
2279 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
2280 struct vm_fault vmf = {
2281 .page = NULL,
2282 .pgoff = linear_page_index(vma, fe->address),
2283 .virtual_address =
2284 (void __user *)(fe->address & PAGE_MASK),
2285 .flags = FAULT_FLAG_WRITE | FAULT_FLAG_MKWRITE,
2287 int ret;
2289 pte_unmap_unlock(fe->pte, fe->ptl);
2290 ret = vma->vm_ops->pfn_mkwrite(vma, &vmf);
2291 if (ret & VM_FAULT_ERROR)
2292 return ret;
2293 fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2294 &fe->ptl);
2296 * We might have raced with another page fault while we
2297 * released the pte_offset_map_lock.
2299 if (!pte_same(*fe->pte, orig_pte)) {
2300 pte_unmap_unlock(fe->pte, fe->ptl);
2301 return 0;
2304 return wp_page_reuse(fe, orig_pte, NULL, 0, 0);
2307 static int wp_page_shared(struct fault_env *fe, pte_t orig_pte,
2308 struct page *old_page)
2309 __releases(fe->ptl)
2311 struct vm_area_struct *vma = fe->vma;
2312 int page_mkwrite = 0;
2314 get_page(old_page);
2316 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
2317 int tmp;
2319 pte_unmap_unlock(fe->pte, fe->ptl);
2320 tmp = do_page_mkwrite(vma, old_page, fe->address);
2321 if (unlikely(!tmp || (tmp &
2322 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
2323 put_page(old_page);
2324 return tmp;
2327 * Since we dropped the lock we need to revalidate
2328 * the PTE as someone else may have changed it. If
2329 * they did, we just return, as we can count on the
2330 * MMU to tell us if they didn't also make it writable.
2332 fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2333 &fe->ptl);
2334 if (!pte_same(*fe->pte, orig_pte)) {
2335 unlock_page(old_page);
2336 pte_unmap_unlock(fe->pte, fe->ptl);
2337 put_page(old_page);
2338 return 0;
2340 page_mkwrite = 1;
2343 return wp_page_reuse(fe, orig_pte, old_page, page_mkwrite, 1);
2347 * This routine handles present pages, when users try to write
2348 * to a shared page. It is done by copying the page to a new address
2349 * and decrementing the shared-page counter for the old page.
2351 * Note that this routine assumes that the protection checks have been
2352 * done by the caller (the low-level page fault routine in most cases).
2353 * Thus we can safely just mark it writable once we've done any necessary
2354 * COW.
2356 * We also mark the page dirty at this point even though the page will
2357 * change only once the write actually happens. This avoids a few races,
2358 * and potentially makes it more efficient.
2360 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2361 * but allow concurrent faults), with pte both mapped and locked.
2362 * We return with mmap_sem still held, but pte unmapped and unlocked.
2364 static int do_wp_page(struct fault_env *fe, pte_t orig_pte)
2365 __releases(fe->ptl)
2367 struct vm_area_struct *vma = fe->vma;
2368 struct page *old_page;
2370 old_page = vm_normal_page(vma, fe->address, orig_pte);
2371 if (!old_page) {
2373 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
2374 * VM_PFNMAP VMA.
2376 * We should not cow pages in a shared writeable mapping.
2377 * Just mark the pages writable and/or call ops->pfn_mkwrite.
2379 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2380 (VM_WRITE|VM_SHARED))
2381 return wp_pfn_shared(fe, orig_pte);
2383 pte_unmap_unlock(fe->pte, fe->ptl);
2384 return wp_page_copy(fe, orig_pte, old_page);
2388 * Take out anonymous pages first, anonymous shared vmas are
2389 * not dirty accountable.
2391 if (PageAnon(old_page) && !PageKsm(old_page)) {
2392 int total_mapcount;
2393 if (!trylock_page(old_page)) {
2394 get_page(old_page);
2395 pte_unmap_unlock(fe->pte, fe->ptl);
2396 lock_page(old_page);
2397 fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd,
2398 fe->address, &fe->ptl);
2399 if (!pte_same(*fe->pte, orig_pte)) {
2400 unlock_page(old_page);
2401 pte_unmap_unlock(fe->pte, fe->ptl);
2402 put_page(old_page);
2403 return 0;
2405 put_page(old_page);
2407 if (reuse_swap_page(old_page, &total_mapcount)) {
2408 if (total_mapcount == 1) {
2410 * The page is all ours. Move it to
2411 * our anon_vma so the rmap code will
2412 * not search our parent or siblings.
2413 * Protected against the rmap code by
2414 * the page lock.
2416 page_move_anon_rmap(old_page, vma);
2418 unlock_page(old_page);
2419 return wp_page_reuse(fe, orig_pte, old_page, 0, 0);
2421 unlock_page(old_page);
2422 } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
2423 (VM_WRITE|VM_SHARED))) {
2424 return wp_page_shared(fe, orig_pte, old_page);
2428 * Ok, we need to copy. Oh, well..
2430 get_page(old_page);
2432 pte_unmap_unlock(fe->pte, fe->ptl);
2433 return wp_page_copy(fe, orig_pte, old_page);
2436 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
2437 unsigned long start_addr, unsigned long end_addr,
2438 struct zap_details *details)
2440 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
2443 static inline void unmap_mapping_range_tree(struct rb_root *root,
2444 struct zap_details *details)
2446 struct vm_area_struct *vma;
2447 pgoff_t vba, vea, zba, zea;
2449 vma_interval_tree_foreach(vma, root,
2450 details->first_index, details->last_index) {
2452 vba = vma->vm_pgoff;
2453 vea = vba + vma_pages(vma) - 1;
2454 zba = details->first_index;
2455 if (zba < vba)
2456 zba = vba;
2457 zea = details->last_index;
2458 if (zea > vea)
2459 zea = vea;
2461 unmap_mapping_range_vma(vma,
2462 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
2463 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
2464 details);
2469 * unmap_mapping_range - unmap the portion of all mmaps in the specified
2470 * address_space corresponding to the specified page range in the underlying
2471 * file.
2473 * @mapping: the address space containing mmaps to be unmapped.
2474 * @holebegin: byte in first page to unmap, relative to the start of
2475 * the underlying file. This will be rounded down to a PAGE_SIZE
2476 * boundary. Note that this is different from truncate_pagecache(), which
2477 * must keep the partial page. In contrast, we must get rid of
2478 * partial pages.
2479 * @holelen: size of prospective hole in bytes. This will be rounded
2480 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
2481 * end of the file.
2482 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
2483 * but 0 when invalidating pagecache, don't throw away private data.
2485 void unmap_mapping_range(struct address_space *mapping,
2486 loff_t const holebegin, loff_t const holelen, int even_cows)
2488 struct zap_details details = { };
2489 pgoff_t hba = holebegin >> PAGE_SHIFT;
2490 pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2492 /* Check for overflow. */
2493 if (sizeof(holelen) > sizeof(hlen)) {
2494 long long holeend =
2495 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
2496 if (holeend & ~(long long)ULONG_MAX)
2497 hlen = ULONG_MAX - hba + 1;
2500 details.check_mapping = even_cows? NULL: mapping;
2501 details.first_index = hba;
2502 details.last_index = hba + hlen - 1;
2503 if (details.last_index < details.first_index)
2504 details.last_index = ULONG_MAX;
2506 i_mmap_lock_write(mapping);
2507 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap)))
2508 unmap_mapping_range_tree(&mapping->i_mmap, &details);
2509 i_mmap_unlock_write(mapping);
2511 EXPORT_SYMBOL(unmap_mapping_range);
2514 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2515 * but allow concurrent faults), and pte mapped but not yet locked.
2516 * We return with pte unmapped and unlocked.
2518 * We return with the mmap_sem locked or unlocked in the same cases
2519 * as does filemap_fault().
2521 int do_swap_page(struct fault_env *fe, pte_t orig_pte)
2523 struct vm_area_struct *vma = fe->vma;
2524 struct page *page, *swapcache;
2525 struct mem_cgroup *memcg;
2526 swp_entry_t entry;
2527 pte_t pte;
2528 int locked;
2529 int exclusive = 0;
2530 int ret = 0;
2532 if (!pte_unmap_same(vma->vm_mm, fe->pmd, fe->pte, orig_pte))
2533 goto out;
2535 entry = pte_to_swp_entry(orig_pte);
2536 if (unlikely(non_swap_entry(entry))) {
2537 if (is_migration_entry(entry)) {
2538 migration_entry_wait(vma->vm_mm, fe->pmd, fe->address);
2539 } else if (is_hwpoison_entry(entry)) {
2540 ret = VM_FAULT_HWPOISON;
2541 } else {
2542 print_bad_pte(vma, fe->address, orig_pte, NULL);
2543 ret = VM_FAULT_SIGBUS;
2545 goto out;
2547 delayacct_set_flag(DELAYACCT_PF_SWAPIN);
2548 page = lookup_swap_cache(entry);
2549 if (!page) {
2550 page = swapin_readahead(entry,
2551 GFP_HIGHUSER_MOVABLE, vma, fe->address);
2552 if (!page) {
2554 * Back out if somebody else faulted in this pte
2555 * while we released the pte lock.
2557 fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd,
2558 fe->address, &fe->ptl);
2559 if (likely(pte_same(*fe->pte, orig_pte)))
2560 ret = VM_FAULT_OOM;
2561 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2562 goto unlock;
2565 /* Had to read the page from swap area: Major fault */
2566 ret = VM_FAULT_MAJOR;
2567 count_vm_event(PGMAJFAULT);
2568 mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
2569 } else if (PageHWPoison(page)) {
2571 * hwpoisoned dirty swapcache pages are kept for killing
2572 * owner processes (which may be unknown at hwpoison time)
2574 ret = VM_FAULT_HWPOISON;
2575 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2576 swapcache = page;
2577 goto out_release;
2580 swapcache = page;
2581 locked = lock_page_or_retry(page, vma->vm_mm, fe->flags);
2583 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
2584 if (!locked) {
2585 ret |= VM_FAULT_RETRY;
2586 goto out_release;
2590 * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
2591 * release the swapcache from under us. The page pin, and pte_same
2592 * test below, are not enough to exclude that. Even if it is still
2593 * swapcache, we need to check that the page's swap has not changed.
2595 if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val))
2596 goto out_page;
2598 page = ksm_might_need_to_copy(page, vma, fe->address);
2599 if (unlikely(!page)) {
2600 ret = VM_FAULT_OOM;
2601 page = swapcache;
2602 goto out_page;
2605 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL,
2606 &memcg, false)) {
2607 ret = VM_FAULT_OOM;
2608 goto out_page;
2612 * Back out if somebody else already faulted in this pte.
2614 fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2615 &fe->ptl);
2616 if (unlikely(!pte_same(*fe->pte, orig_pte)))
2617 goto out_nomap;
2619 if (unlikely(!PageUptodate(page))) {
2620 ret = VM_FAULT_SIGBUS;
2621 goto out_nomap;
2625 * The page isn't present yet, go ahead with the fault.
2627 * Be careful about the sequence of operations here.
2628 * To get its accounting right, reuse_swap_page() must be called
2629 * while the page is counted on swap but not yet in mapcount i.e.
2630 * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
2631 * must be called after the swap_free(), or it will never succeed.
2634 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
2635 dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
2636 pte = mk_pte(page, vma->vm_page_prot);
2637 if ((fe->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
2638 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
2639 fe->flags &= ~FAULT_FLAG_WRITE;
2640 ret |= VM_FAULT_WRITE;
2641 exclusive = RMAP_EXCLUSIVE;
2643 flush_icache_page(vma, page);
2644 if (pte_swp_soft_dirty(orig_pte))
2645 pte = pte_mksoft_dirty(pte);
2646 set_pte_at(vma->vm_mm, fe->address, fe->pte, pte);
2647 if (page == swapcache) {
2648 do_page_add_anon_rmap(page, vma, fe->address, exclusive);
2649 mem_cgroup_commit_charge(page, memcg, true, false);
2650 activate_page(page);
2651 } else { /* ksm created a completely new copy */
2652 page_add_new_anon_rmap(page, vma, fe->address, false);
2653 mem_cgroup_commit_charge(page, memcg, false, false);
2654 lru_cache_add_active_or_unevictable(page, vma);
2657 swap_free(entry);
2658 if (mem_cgroup_swap_full(page) ||
2659 (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
2660 try_to_free_swap(page);
2661 unlock_page(page);
2662 if (page != swapcache) {
2664 * Hold the lock to avoid the swap entry to be reused
2665 * until we take the PT lock for the pte_same() check
2666 * (to avoid false positives from pte_same). For
2667 * further safety release the lock after the swap_free
2668 * so that the swap count won't change under a
2669 * parallel locked swapcache.
2671 unlock_page(swapcache);
2672 put_page(swapcache);
2675 if (fe->flags & FAULT_FLAG_WRITE) {
2676 ret |= do_wp_page(fe, pte);
2677 if (ret & VM_FAULT_ERROR)
2678 ret &= VM_FAULT_ERROR;
2679 goto out;
2682 /* No need to invalidate - it was non-present before */
2683 update_mmu_cache(vma, fe->address, fe->pte);
2684 unlock:
2685 pte_unmap_unlock(fe->pte, fe->ptl);
2686 out:
2687 return ret;
2688 out_nomap:
2689 mem_cgroup_cancel_charge(page, memcg, false);
2690 pte_unmap_unlock(fe->pte, fe->ptl);
2691 out_page:
2692 unlock_page(page);
2693 out_release:
2694 put_page(page);
2695 if (page != swapcache) {
2696 unlock_page(swapcache);
2697 put_page(swapcache);
2699 return ret;
2703 * We enter with non-exclusive mmap_sem (to exclude vma changes,
2704 * but allow concurrent faults), and pte mapped but not yet locked.
2705 * We return with mmap_sem still held, but pte unmapped and unlocked.
2707 static int do_anonymous_page(struct fault_env *fe)
2709 struct vm_area_struct *vma = fe->vma;
2710 struct mem_cgroup *memcg;
2711 struct page *page;
2712 pte_t entry;
2714 /* File mapping without ->vm_ops ? */
2715 if (vma->vm_flags & VM_SHARED)
2716 return VM_FAULT_SIGBUS;
2719 * Use pte_alloc() instead of pte_alloc_map(). We can't run
2720 * pte_offset_map() on pmds where a huge pmd might be created
2721 * from a different thread.
2723 * pte_alloc_map() is safe to use under down_write(mmap_sem) or when
2724 * parallel threads are excluded by other means.
2726 * Here we only have down_read(mmap_sem).
2728 if (pte_alloc(vma->vm_mm, fe->pmd, fe->address))
2729 return VM_FAULT_OOM;
2731 /* See the comment in pte_alloc_one_map() */
2732 if (unlikely(pmd_trans_unstable(fe->pmd)))
2733 return 0;
2735 /* Use the zero-page for reads */
2736 if (!(fe->flags & FAULT_FLAG_WRITE) &&
2737 !mm_forbids_zeropage(vma->vm_mm)) {
2738 entry = pte_mkspecial(pfn_pte(my_zero_pfn(fe->address),
2739 vma->vm_page_prot));
2740 fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2741 &fe->ptl);
2742 if (!pte_none(*fe->pte))
2743 goto unlock;
2744 /* Deliver the page fault to userland, check inside PT lock */
2745 if (userfaultfd_missing(vma)) {
2746 pte_unmap_unlock(fe->pte, fe->ptl);
2747 return handle_userfault(fe, VM_UFFD_MISSING);
2749 goto setpte;
2752 /* Allocate our own private page. */
2753 if (unlikely(anon_vma_prepare(vma)))
2754 goto oom;
2755 page = alloc_zeroed_user_highpage_movable(vma, fe->address);
2756 if (!page)
2757 goto oom;
2759 if (mem_cgroup_try_charge(page, vma->vm_mm, GFP_KERNEL, &memcg, false))
2760 goto oom_free_page;
2763 * The memory barrier inside __SetPageUptodate makes sure that
2764 * preceeding stores to the page contents become visible before
2765 * the set_pte_at() write.
2767 __SetPageUptodate(page);
2769 entry = mk_pte(page, vma->vm_page_prot);
2770 if (vma->vm_flags & VM_WRITE)
2771 entry = pte_mkwrite(pte_mkdirty(entry));
2773 fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2774 &fe->ptl);
2775 if (!pte_none(*fe->pte))
2776 goto release;
2778 /* Deliver the page fault to userland, check inside PT lock */
2779 if (userfaultfd_missing(vma)) {
2780 pte_unmap_unlock(fe->pte, fe->ptl);
2781 mem_cgroup_cancel_charge(page, memcg, false);
2782 put_page(page);
2783 return handle_userfault(fe, VM_UFFD_MISSING);
2786 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
2787 page_add_new_anon_rmap(page, vma, fe->address, false);
2788 mem_cgroup_commit_charge(page, memcg, false, false);
2789 lru_cache_add_active_or_unevictable(page, vma);
2790 setpte:
2791 set_pte_at(vma->vm_mm, fe->address, fe->pte, entry);
2793 /* No need to invalidate - it was non-present before */
2794 update_mmu_cache(vma, fe->address, fe->pte);
2795 unlock:
2796 pte_unmap_unlock(fe->pte, fe->ptl);
2797 return 0;
2798 release:
2799 mem_cgroup_cancel_charge(page, memcg, false);
2800 put_page(page);
2801 goto unlock;
2802 oom_free_page:
2803 put_page(page);
2804 oom:
2805 return VM_FAULT_OOM;
2809 * The mmap_sem must have been held on entry, and may have been
2810 * released depending on flags and vma->vm_ops->fault() return value.
2811 * See filemap_fault() and __lock_page_retry().
2813 static int __do_fault(struct fault_env *fe, pgoff_t pgoff,
2814 struct page *cow_page, struct page **page, void **entry)
2816 struct vm_area_struct *vma = fe->vma;
2817 struct vm_fault vmf;
2818 int ret;
2820 vmf.virtual_address = (void __user *)(fe->address & PAGE_MASK);
2821 vmf.pgoff = pgoff;
2822 vmf.flags = fe->flags;
2823 vmf.page = NULL;
2824 vmf.gfp_mask = __get_fault_gfp_mask(vma);
2825 vmf.cow_page = cow_page;
2827 ret = vma->vm_ops->fault(vma, &vmf);
2828 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
2829 return ret;
2830 if (ret & VM_FAULT_DAX_LOCKED) {
2831 *entry = vmf.entry;
2832 return ret;
2835 if (unlikely(PageHWPoison(vmf.page))) {
2836 if (ret & VM_FAULT_LOCKED)
2837 unlock_page(vmf.page);
2838 put_page(vmf.page);
2839 return VM_FAULT_HWPOISON;
2842 if (unlikely(!(ret & VM_FAULT_LOCKED)))
2843 lock_page(vmf.page);
2844 else
2845 VM_BUG_ON_PAGE(!PageLocked(vmf.page), vmf.page);
2847 *page = vmf.page;
2848 return ret;
2852 * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
2853 * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
2854 * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
2855 * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
2857 static int pmd_devmap_trans_unstable(pmd_t *pmd)
2859 return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
2862 static int pte_alloc_one_map(struct fault_env *fe)
2864 struct vm_area_struct *vma = fe->vma;
2866 if (!pmd_none(*fe->pmd))
2867 goto map_pte;
2868 if (fe->prealloc_pte) {
2869 fe->ptl = pmd_lock(vma->vm_mm, fe->pmd);
2870 if (unlikely(!pmd_none(*fe->pmd))) {
2871 spin_unlock(fe->ptl);
2872 goto map_pte;
2875 atomic_long_inc(&vma->vm_mm->nr_ptes);
2876 pmd_populate(vma->vm_mm, fe->pmd, fe->prealloc_pte);
2877 spin_unlock(fe->ptl);
2878 fe->prealloc_pte = 0;
2879 } else if (unlikely(pte_alloc(vma->vm_mm, fe->pmd, fe->address))) {
2880 return VM_FAULT_OOM;
2882 map_pte:
2884 * If a huge pmd materialized under us just retry later. Use
2885 * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
2886 * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
2887 * under us and then back to pmd_none, as a result of MADV_DONTNEED
2888 * running immediately after a huge pmd fault in a different thread of
2889 * this mm, in turn leading to a misleading pmd_trans_huge() retval.
2890 * All we have to ensure is that it is a regular pmd that we can walk
2891 * with pte_offset_map() and we can do that through an atomic read in
2892 * C, which is what pmd_trans_unstable() provides.
2894 if (pmd_devmap_trans_unstable(fe->pmd))
2895 return VM_FAULT_NOPAGE;
2898 * At this point we know that our vmf->pmd points to a page of ptes
2899 * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
2900 * for the duration of the fault. If a racing MADV_DONTNEED runs and
2901 * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
2902 * be valid and we will re-check to make sure the vmf->pte isn't
2903 * pte_none() under vmf->ptl protection when we return to
2904 * alloc_set_pte().
2906 fe->pte = pte_offset_map_lock(vma->vm_mm, fe->pmd, fe->address,
2907 &fe->ptl);
2908 return 0;
2911 #ifdef CONFIG_TRANSPARENT_HUGE_PAGECACHE
2913 #define HPAGE_CACHE_INDEX_MASK (HPAGE_PMD_NR - 1)
2914 static inline bool transhuge_vma_suitable(struct vm_area_struct *vma,
2915 unsigned long haddr)
2917 if (((vma->vm_start >> PAGE_SHIFT) & HPAGE_CACHE_INDEX_MASK) !=
2918 (vma->vm_pgoff & HPAGE_CACHE_INDEX_MASK))
2919 return false;
2920 if (haddr < vma->vm_start || haddr + HPAGE_PMD_SIZE > vma->vm_end)
2921 return false;
2922 return true;
2925 static int do_set_pmd(struct fault_env *fe, struct page *page)
2927 struct vm_area_struct *vma = fe->vma;
2928 bool write = fe->flags & FAULT_FLAG_WRITE;
2929 unsigned long haddr = fe->address & HPAGE_PMD_MASK;
2930 pmd_t entry;
2931 int i, ret;
2933 if (!transhuge_vma_suitable(vma, haddr))
2934 return VM_FAULT_FALLBACK;
2936 ret = VM_FAULT_FALLBACK;
2937 page = compound_head(page);
2939 fe->ptl = pmd_lock(vma->vm_mm, fe->pmd);
2940 if (unlikely(!pmd_none(*fe->pmd)))
2941 goto out;
2943 for (i = 0; i < HPAGE_PMD_NR; i++)
2944 flush_icache_page(vma, page + i);
2946 entry = mk_huge_pmd(page, vma->vm_page_prot);
2947 if (write)
2948 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
2950 add_mm_counter(vma->vm_mm, MM_FILEPAGES, HPAGE_PMD_NR);
2951 page_add_file_rmap(page, true);
2953 set_pmd_at(vma->vm_mm, haddr, fe->pmd, entry);
2955 update_mmu_cache_pmd(vma, haddr, fe->pmd);
2957 /* fault is handled */
2958 ret = 0;
2959 count_vm_event(THP_FILE_MAPPED);
2960 out:
2961 spin_unlock(fe->ptl);
2962 return ret;
2964 #else
2965 static int do_set_pmd(struct fault_env *fe, struct page *page)
2967 BUILD_BUG();
2968 return 0;
2970 #endif
2973 * alloc_set_pte - setup new PTE entry for given page and add reverse page
2974 * mapping. If needed, the fucntion allocates page table or use pre-allocated.
2976 * @fe: fault environment
2977 * @memcg: memcg to charge page (only for private mappings)
2978 * @page: page to map
2980 * Caller must take care of unlocking fe->ptl, if fe->pte is non-NULL on return.
2982 * Target users are page handler itself and implementations of
2983 * vm_ops->map_pages.
2985 int alloc_set_pte(struct fault_env *fe, struct mem_cgroup *memcg,
2986 struct page *page)
2988 struct vm_area_struct *vma = fe->vma;
2989 bool write = fe->flags & FAULT_FLAG_WRITE;
2990 pte_t entry;
2991 int ret;
2993 if (pmd_none(*fe->pmd) && PageTransCompound(page) &&
2994 IS_ENABLED(CONFIG_TRANSPARENT_HUGE_PAGECACHE)) {
2995 /* THP on COW? */
2996 VM_BUG_ON_PAGE(memcg, page);
2998 ret = do_set_pmd(fe, page);
2999 if (ret != VM_FAULT_FALLBACK)
3000 return ret;
3003 if (!fe->pte) {
3004 ret = pte_alloc_one_map(fe);
3005 if (ret)
3006 return ret;
3009 /* Re-check under ptl */
3010 if (unlikely(!pte_none(*fe->pte)))
3011 return VM_FAULT_NOPAGE;
3013 flush_icache_page(vma, page);
3014 entry = mk_pte(page, vma->vm_page_prot);
3015 if (write)
3016 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3017 /* copy-on-write page */
3018 if (write && !(vma->vm_flags & VM_SHARED)) {
3019 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3020 page_add_new_anon_rmap(page, vma, fe->address, false);
3021 mem_cgroup_commit_charge(page, memcg, false, false);
3022 lru_cache_add_active_or_unevictable(page, vma);
3023 } else {
3024 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3025 page_add_file_rmap(page, false);
3027 set_pte_at(vma->vm_mm, fe->address, fe->pte, entry);
3029 /* no need to invalidate: a not-present page won't be cached */
3030 update_mmu_cache(vma, fe->address, fe->pte);
3032 return 0;
3035 static unsigned long fault_around_bytes __read_mostly =
3036 rounddown_pow_of_two(65536);
3038 #ifdef CONFIG_DEBUG_FS
3039 static int fault_around_bytes_get(void *data, u64 *val)
3041 *val = fault_around_bytes;
3042 return 0;
3046 * fault_around_pages() and fault_around_mask() expects fault_around_bytes
3047 * rounded down to nearest page order. It's what do_fault_around() expects to
3048 * see.
3050 static int fault_around_bytes_set(void *data, u64 val)
3052 if (val / PAGE_SIZE > PTRS_PER_PTE)
3053 return -EINVAL;
3054 if (val > PAGE_SIZE)
3055 fault_around_bytes = rounddown_pow_of_two(val);
3056 else
3057 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
3058 return 0;
3060 DEFINE_SIMPLE_ATTRIBUTE(fault_around_bytes_fops,
3061 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
3063 static int __init fault_around_debugfs(void)
3065 void *ret;
3067 ret = debugfs_create_file("fault_around_bytes", 0644, NULL, NULL,
3068 &fault_around_bytes_fops);
3069 if (!ret)
3070 pr_warn("Failed to create fault_around_bytes in debugfs");
3071 return 0;
3073 late_initcall(fault_around_debugfs);
3074 #endif
3077 * do_fault_around() tries to map few pages around the fault address. The hope
3078 * is that the pages will be needed soon and this will lower the number of
3079 * faults to handle.
3081 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
3082 * not ready to be mapped: not up-to-date, locked, etc.
3084 * This function is called with the page table lock taken. In the split ptlock
3085 * case the page table lock only protects only those entries which belong to
3086 * the page table corresponding to the fault address.
3088 * This function doesn't cross the VMA boundaries, in order to call map_pages()
3089 * only once.
3091 * fault_around_pages() defines how many pages we'll try to map.
3092 * do_fault_around() expects it to return a power of two less than or equal to
3093 * PTRS_PER_PTE.
3095 * The virtual address of the area that we map is naturally aligned to the
3096 * fault_around_pages() value (and therefore to page order). This way it's
3097 * easier to guarantee that we don't cross page table boundaries.
3099 static int do_fault_around(struct fault_env *fe, pgoff_t start_pgoff)
3101 unsigned long address = fe->address, nr_pages, mask;
3102 pgoff_t end_pgoff;
3103 int off, ret = 0;
3105 nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
3106 mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
3108 fe->address = max(address & mask, fe->vma->vm_start);
3109 off = ((address - fe->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
3110 start_pgoff -= off;
3113 * end_pgoff is either end of page table or end of vma
3114 * or fault_around_pages() from start_pgoff, depending what is nearest.
3116 end_pgoff = start_pgoff -
3117 ((fe->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
3118 PTRS_PER_PTE - 1;
3119 end_pgoff = min3(end_pgoff, vma_pages(fe->vma) + fe->vma->vm_pgoff - 1,
3120 start_pgoff + nr_pages - 1);
3122 if (pmd_none(*fe->pmd)) {
3123 fe->prealloc_pte = pte_alloc_one(fe->vma->vm_mm, fe->address);
3124 if (!fe->prealloc_pte)
3125 goto out;
3126 smp_wmb(); /* See comment in __pte_alloc() */
3129 fe->vma->vm_ops->map_pages(fe, start_pgoff, end_pgoff);
3131 /* preallocated pagetable is unused: free it */
3132 if (fe->prealloc_pte) {
3133 pte_free(fe->vma->vm_mm, fe->prealloc_pte);
3134 fe->prealloc_pte = 0;
3136 /* Huge page is mapped? Page fault is solved */
3137 if (pmd_trans_huge(*fe->pmd)) {
3138 ret = VM_FAULT_NOPAGE;
3139 goto out;
3142 /* ->map_pages() haven't done anything useful. Cold page cache? */
3143 if (!fe->pte)
3144 goto out;
3146 /* check if the page fault is solved */
3147 fe->pte -= (fe->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
3148 if (!pte_none(*fe->pte))
3149 ret = VM_FAULT_NOPAGE;
3150 pte_unmap_unlock(fe->pte, fe->ptl);
3151 out:
3152 fe->address = address;
3153 fe->pte = NULL;
3154 return ret;
3157 static int do_read_fault(struct fault_env *fe, pgoff_t pgoff)
3159 struct vm_area_struct *vma = fe->vma;
3160 struct page *fault_page;
3161 int ret = 0;
3164 * Let's call ->map_pages() first and use ->fault() as fallback
3165 * if page by the offset is not ready to be mapped (cold cache or
3166 * something).
3168 if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
3169 ret = do_fault_around(fe, pgoff);
3170 if (ret)
3171 return ret;
3174 ret = __do_fault(fe, pgoff, NULL, &fault_page, NULL);
3175 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3176 return ret;
3178 ret |= alloc_set_pte(fe, NULL, fault_page);
3179 if (fe->pte)
3180 pte_unmap_unlock(fe->pte, fe->ptl);
3181 unlock_page(fault_page);
3182 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3183 put_page(fault_page);
3184 return ret;
3187 static int do_cow_fault(struct fault_env *fe, pgoff_t pgoff)
3189 struct vm_area_struct *vma = fe->vma;
3190 struct page *fault_page, *new_page;
3191 void *fault_entry;
3192 struct mem_cgroup *memcg;
3193 int ret;
3195 if (unlikely(anon_vma_prepare(vma)))
3196 return VM_FAULT_OOM;
3198 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, fe->address);
3199 if (!new_page)
3200 return VM_FAULT_OOM;
3202 if (mem_cgroup_try_charge(new_page, vma->vm_mm, GFP_KERNEL,
3203 &memcg, false)) {
3204 put_page(new_page);
3205 return VM_FAULT_OOM;
3208 ret = __do_fault(fe, pgoff, new_page, &fault_page, &fault_entry);
3209 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3210 goto uncharge_out;
3212 if (!(ret & VM_FAULT_DAX_LOCKED))
3213 copy_user_highpage(new_page, fault_page, fe->address, vma);
3214 __SetPageUptodate(new_page);
3216 ret |= alloc_set_pte(fe, memcg, new_page);
3217 if (fe->pte)
3218 pte_unmap_unlock(fe->pte, fe->ptl);
3219 if (!(ret & VM_FAULT_DAX_LOCKED)) {
3220 unlock_page(fault_page);
3221 put_page(fault_page);
3222 } else {
3223 dax_unlock_mapping_entry(vma->vm_file->f_mapping, pgoff);
3225 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3226 goto uncharge_out;
3227 return ret;
3228 uncharge_out:
3229 mem_cgroup_cancel_charge(new_page, memcg, false);
3230 put_page(new_page);
3231 return ret;
3234 static int do_shared_fault(struct fault_env *fe, pgoff_t pgoff)
3236 struct vm_area_struct *vma = fe->vma;
3237 struct page *fault_page;
3238 struct address_space *mapping;
3239 int dirtied = 0;
3240 int ret, tmp;
3242 ret = __do_fault(fe, pgoff, NULL, &fault_page, NULL);
3243 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
3244 return ret;
3247 * Check if the backing address space wants to know that the page is
3248 * about to become writable
3250 if (vma->vm_ops->page_mkwrite) {
3251 unlock_page(fault_page);
3252 tmp = do_page_mkwrite(vma, fault_page, fe->address);
3253 if (unlikely(!tmp ||
3254 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3255 put_page(fault_page);
3256 return tmp;
3260 ret |= alloc_set_pte(fe, NULL, fault_page);
3261 if (fe->pte)
3262 pte_unmap_unlock(fe->pte, fe->ptl);
3263 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
3264 VM_FAULT_RETRY))) {
3265 unlock_page(fault_page);
3266 put_page(fault_page);
3267 return ret;
3270 if (set_page_dirty(fault_page))
3271 dirtied = 1;
3273 * Take a local copy of the address_space - page.mapping may be zeroed
3274 * by truncate after unlock_page(). The address_space itself remains
3275 * pinned by vma->vm_file's reference. We rely on unlock_page()'s
3276 * release semantics to prevent the compiler from undoing this copying.
3278 mapping = page_rmapping(fault_page);
3279 unlock_page(fault_page);
3280 if ((dirtied || vma->vm_ops->page_mkwrite) && mapping) {
3282 * Some device drivers do not set page.mapping but still
3283 * dirty their pages
3285 balance_dirty_pages_ratelimited(mapping);
3288 if (!vma->vm_ops->page_mkwrite)
3289 file_update_time(vma->vm_file);
3291 return ret;
3295 * We enter with non-exclusive mmap_sem (to exclude vma changes,
3296 * but allow concurrent faults).
3297 * The mmap_sem may have been released depending on flags and our
3298 * return value. See filemap_fault() and __lock_page_or_retry().
3300 static int do_fault(struct fault_env *fe)
3302 struct vm_area_struct *vma = fe->vma;
3303 pgoff_t pgoff = linear_page_index(vma, fe->address);
3305 /* The VMA was not fully populated on mmap() or missing VM_DONTEXPAND */
3306 if (!vma->vm_ops->fault)
3307 return VM_FAULT_SIGBUS;
3308 if (!(fe->flags & FAULT_FLAG_WRITE))
3309 return do_read_fault(fe, pgoff);
3310 if (!(vma->vm_flags & VM_SHARED))
3311 return do_cow_fault(fe, pgoff);
3312 return do_shared_fault(fe, pgoff);
3315 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
3316 unsigned long addr, int page_nid,
3317 int *flags)
3319 get_page(page);
3321 count_vm_numa_event(NUMA_HINT_FAULTS);
3322 if (page_nid == numa_node_id()) {
3323 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
3324 *flags |= TNF_FAULT_LOCAL;
3327 return mpol_misplaced(page, vma, addr);
3330 static int do_numa_page(struct fault_env *fe, pte_t pte)
3332 struct vm_area_struct *vma = fe->vma;
3333 struct page *page = NULL;
3334 int page_nid = -1;
3335 int last_cpupid;
3336 int target_nid;
3337 bool migrated = false;
3338 bool was_writable = pte_write(pte);
3339 int flags = 0;
3342 * The "pte" at this point cannot be used safely without
3343 * validation through pte_unmap_same(). It's of NUMA type but
3344 * the pfn may be screwed if the read is non atomic.
3346 * We can safely just do a "set_pte_at()", because the old
3347 * page table entry is not accessible, so there would be no
3348 * concurrent hardware modifications to the PTE.
3350 fe->ptl = pte_lockptr(vma->vm_mm, fe->pmd);
3351 spin_lock(fe->ptl);
3352 if (unlikely(!pte_same(*fe->pte, pte))) {
3353 pte_unmap_unlock(fe->pte, fe->ptl);
3354 goto out;
3357 /* Make it present again */
3358 pte = pte_modify(pte, vma->vm_page_prot);
3359 pte = pte_mkyoung(pte);
3360 if (was_writable)
3361 pte = pte_mkwrite(pte);
3362 set_pte_at(vma->vm_mm, fe->address, fe->pte, pte);
3363 update_mmu_cache(vma, fe->address, fe->pte);
3365 page = vm_normal_page(vma, fe->address, pte);
3366 if (!page) {
3367 pte_unmap_unlock(fe->pte, fe->ptl);
3368 return 0;
3371 /* TODO: handle PTE-mapped THP */
3372 if (PageCompound(page)) {
3373 pte_unmap_unlock(fe->pte, fe->ptl);
3374 return 0;
3378 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
3379 * much anyway since they can be in shared cache state. This misses
3380 * the case where a mapping is writable but the process never writes
3381 * to it but pte_write gets cleared during protection updates and
3382 * pte_dirty has unpredictable behaviour between PTE scan updates,
3383 * background writeback, dirty balancing and application behaviour.
3385 if (!pte_write(pte))
3386 flags |= TNF_NO_GROUP;
3389 * Flag if the page is shared between multiple address spaces. This
3390 * is later used when determining whether to group tasks together
3392 if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
3393 flags |= TNF_SHARED;
3395 last_cpupid = page_cpupid_last(page);
3396 page_nid = page_to_nid(page);
3397 target_nid = numa_migrate_prep(page, vma, fe->address, page_nid,
3398 &flags);
3399 pte_unmap_unlock(fe->pte, fe->ptl);
3400 if (target_nid == -1) {
3401 put_page(page);
3402 goto out;
3405 /* Migrate to the requested node */
3406 migrated = migrate_misplaced_page(page, vma, target_nid);
3407 if (migrated) {
3408 page_nid = target_nid;
3409 flags |= TNF_MIGRATED;
3410 } else
3411 flags |= TNF_MIGRATE_FAIL;
3413 out:
3414 if (page_nid != -1)
3415 task_numa_fault(last_cpupid, page_nid, 1, flags);
3416 return 0;
3419 static int create_huge_pmd(struct fault_env *fe)
3421 struct vm_area_struct *vma = fe->vma;
3422 if (vma_is_anonymous(vma))
3423 return do_huge_pmd_anonymous_page(fe);
3424 if (vma->vm_ops->pmd_fault)
3425 return vma->vm_ops->pmd_fault(vma, fe->address, fe->pmd,
3426 fe->flags);
3427 return VM_FAULT_FALLBACK;
3430 static int wp_huge_pmd(struct fault_env *fe, pmd_t orig_pmd)
3432 if (vma_is_anonymous(fe->vma))
3433 return do_huge_pmd_wp_page(fe, orig_pmd);
3434 if (fe->vma->vm_ops->pmd_fault)
3435 return fe->vma->vm_ops->pmd_fault(fe->vma, fe->address, fe->pmd,
3436 fe->flags);
3438 /* COW handled on pte level: split pmd */
3439 VM_BUG_ON_VMA(fe->vma->vm_flags & VM_SHARED, fe->vma);
3440 split_huge_pmd(fe->vma, fe->pmd, fe->address);
3442 return VM_FAULT_FALLBACK;
3445 static inline bool vma_is_accessible(struct vm_area_struct *vma)
3447 return vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE);
3451 * These routines also need to handle stuff like marking pages dirty
3452 * and/or accessed for architectures that don't do it in hardware (most
3453 * RISC architectures). The early dirtying is also good on the i386.
3455 * There is also a hook called "update_mmu_cache()" that architectures
3456 * with external mmu caches can use to update those (ie the Sparc or
3457 * PowerPC hashed page tables that act as extended TLBs).
3459 * We enter with non-exclusive mmap_sem (to exclude vma changes, but allow
3460 * concurrent faults).
3462 * The mmap_sem may have been released depending on flags and our return value.
3463 * See filemap_fault() and __lock_page_or_retry().
3465 static int handle_pte_fault(struct fault_env *fe)
3467 pte_t entry;
3469 if (unlikely(pmd_none(*fe->pmd))) {
3471 * Leave __pte_alloc() until later: because vm_ops->fault may
3472 * want to allocate huge page, and if we expose page table
3473 * for an instant, it will be difficult to retract from
3474 * concurrent faults and from rmap lookups.
3476 fe->pte = NULL;
3477 } else {
3478 /* See comment in pte_alloc_one_map() */
3479 if (pmd_devmap_trans_unstable(fe->pmd))
3480 return 0;
3482 * A regular pmd is established and it can't morph into a huge
3483 * pmd from under us anymore at this point because we hold the
3484 * mmap_sem read mode and khugepaged takes it in write mode.
3485 * So now it's safe to run pte_offset_map().
3487 fe->pte = pte_offset_map(fe->pmd, fe->address);
3489 entry = *fe->pte;
3492 * some architectures can have larger ptes than wordsize,
3493 * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
3494 * CONFIG_32BIT=y, so READ_ONCE or ACCESS_ONCE cannot guarantee
3495 * atomic accesses. The code below just needs a consistent
3496 * view for the ifs and we later double check anyway with the
3497 * ptl lock held. So here a barrier will do.
3499 barrier();
3500 if (pte_none(entry)) {
3501 pte_unmap(fe->pte);
3502 fe->pte = NULL;
3506 if (!fe->pte) {
3507 if (vma_is_anonymous(fe->vma))
3508 return do_anonymous_page(fe);
3509 else
3510 return do_fault(fe);
3513 if (!pte_present(entry))
3514 return do_swap_page(fe, entry);
3516 if (pte_protnone(entry) && vma_is_accessible(fe->vma))
3517 return do_numa_page(fe, entry);
3519 fe->ptl = pte_lockptr(fe->vma->vm_mm, fe->pmd);
3520 spin_lock(fe->ptl);
3521 if (unlikely(!pte_same(*fe->pte, entry)))
3522 goto unlock;
3523 if (fe->flags & FAULT_FLAG_WRITE) {
3524 if (!pte_write(entry))
3525 return do_wp_page(fe, entry);
3526 entry = pte_mkdirty(entry);
3528 entry = pte_mkyoung(entry);
3529 if (ptep_set_access_flags(fe->vma, fe->address, fe->pte, entry,
3530 fe->flags & FAULT_FLAG_WRITE)) {
3531 update_mmu_cache(fe->vma, fe->address, fe->pte);
3532 } else {
3534 * This is needed only for protection faults but the arch code
3535 * is not yet telling us if this is a protection fault or not.
3536 * This still avoids useless tlb flushes for .text page faults
3537 * with threads.
3539 if (fe->flags & FAULT_FLAG_WRITE)
3540 flush_tlb_fix_spurious_fault(fe->vma, fe->address);
3542 unlock:
3543 pte_unmap_unlock(fe->pte, fe->ptl);
3544 return 0;
3548 * By the time we get here, we already hold the mm semaphore
3550 * The mmap_sem may have been released depending on flags and our
3551 * return value. See filemap_fault() and __lock_page_or_retry().
3553 static int __handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
3554 unsigned int flags)
3556 struct fault_env fe = {
3557 .vma = vma,
3558 .address = address,
3559 .flags = flags,
3561 struct mm_struct *mm = vma->vm_mm;
3562 pgd_t *pgd;
3563 pud_t *pud;
3565 pgd = pgd_offset(mm, address);
3566 pud = pud_alloc(mm, pgd, address);
3567 if (!pud)
3568 return VM_FAULT_OOM;
3569 fe.pmd = pmd_alloc(mm, pud, address);
3570 if (!fe.pmd)
3571 return VM_FAULT_OOM;
3572 if (pmd_none(*fe.pmd) && transparent_hugepage_enabled(vma)) {
3573 int ret = create_huge_pmd(&fe);
3574 if (!(ret & VM_FAULT_FALLBACK))
3575 return ret;
3576 } else {
3577 pmd_t orig_pmd = *fe.pmd;
3578 int ret;
3580 barrier();
3581 if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
3582 if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
3583 return do_huge_pmd_numa_page(&fe, orig_pmd);
3585 if ((fe.flags & FAULT_FLAG_WRITE) &&
3586 !pmd_write(orig_pmd)) {
3587 ret = wp_huge_pmd(&fe, orig_pmd);
3588 if (!(ret & VM_FAULT_FALLBACK))
3589 return ret;
3590 } else {
3591 huge_pmd_set_accessed(&fe, orig_pmd);
3592 return 0;
3597 return handle_pte_fault(&fe);
3601 * By the time we get here, we already hold the mm semaphore
3603 * The mmap_sem may have been released depending on flags and our
3604 * return value. See filemap_fault() and __lock_page_or_retry().
3606 int handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
3607 unsigned int flags)
3609 int ret;
3611 __set_current_state(TASK_RUNNING);
3613 count_vm_event(PGFAULT);
3614 mem_cgroup_count_vm_event(vma->vm_mm, PGFAULT);
3616 /* do counter updates before entering really critical section. */
3617 check_sync_rss_stat(current);
3619 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
3620 flags & FAULT_FLAG_INSTRUCTION,
3621 flags & FAULT_FLAG_REMOTE))
3622 return VM_FAULT_SIGSEGV;
3625 * Enable the memcg OOM handling for faults triggered in user
3626 * space. Kernel faults are handled more gracefully.
3628 if (flags & FAULT_FLAG_USER)
3629 mem_cgroup_oom_enable();
3631 if (unlikely(is_vm_hugetlb_page(vma)))
3632 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
3633 else
3634 ret = __handle_mm_fault(vma, address, flags);
3636 if (flags & FAULT_FLAG_USER) {
3637 mem_cgroup_oom_disable();
3639 * The task may have entered a memcg OOM situation but
3640 * if the allocation error was handled gracefully (no
3641 * VM_FAULT_OOM), there is no need to kill anything.
3642 * Just clean up the OOM state peacefully.
3644 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
3645 mem_cgroup_oom_synchronize(false);
3649 * This mm has been already reaped by the oom reaper and so the
3650 * refault cannot be trusted in general. Anonymous refaults would
3651 * lose data and give a zero page instead e.g. This is especially
3652 * problem for use_mm() because regular tasks will just die and
3653 * the corrupted data will not be visible anywhere while kthread
3654 * will outlive the oom victim and potentially propagate the date
3655 * further.
3657 if (unlikely((current->flags & PF_KTHREAD) && !(ret & VM_FAULT_ERROR)
3658 && test_bit(MMF_UNSTABLE, &vma->vm_mm->flags))) {
3661 * We are going to enforce SIGBUS but the PF path might have
3662 * dropped the mmap_sem already so take it again so that
3663 * we do not break expectations of all arch specific PF paths
3664 * and g-u-p
3666 if (ret & VM_FAULT_RETRY)
3667 down_read(&vma->vm_mm->mmap_sem);
3668 ret = VM_FAULT_SIGBUS;
3671 return ret;
3673 EXPORT_SYMBOL_GPL(handle_mm_fault);
3675 #ifndef __PAGETABLE_PUD_FOLDED
3677 * Allocate page upper directory.
3678 * We've already handled the fast-path in-line.
3680 int __pud_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
3682 pud_t *new = pud_alloc_one(mm, address);
3683 if (!new)
3684 return -ENOMEM;
3686 smp_wmb(); /* See comment in __pte_alloc */
3688 spin_lock(&mm->page_table_lock);
3689 if (pgd_present(*pgd)) /* Another has populated it */
3690 pud_free(mm, new);
3691 else
3692 pgd_populate(mm, pgd, new);
3693 spin_unlock(&mm->page_table_lock);
3694 return 0;
3696 #endif /* __PAGETABLE_PUD_FOLDED */
3698 #ifndef __PAGETABLE_PMD_FOLDED
3700 * Allocate page middle directory.
3701 * We've already handled the fast-path in-line.
3703 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
3705 pmd_t *new = pmd_alloc_one(mm, address);
3706 if (!new)
3707 return -ENOMEM;
3709 smp_wmb(); /* See comment in __pte_alloc */
3711 spin_lock(&mm->page_table_lock);
3712 #ifndef __ARCH_HAS_4LEVEL_HACK
3713 if (!pud_present(*pud)) {
3714 mm_inc_nr_pmds(mm);
3715 pud_populate(mm, pud, new);
3716 } else /* Another has populated it */
3717 pmd_free(mm, new);
3718 #else
3719 if (!pgd_present(*pud)) {
3720 mm_inc_nr_pmds(mm);
3721 pgd_populate(mm, pud, new);
3722 } else /* Another has populated it */
3723 pmd_free(mm, new);
3724 #endif /* __ARCH_HAS_4LEVEL_HACK */
3725 spin_unlock(&mm->page_table_lock);
3726 return 0;
3728 #endif /* __PAGETABLE_PMD_FOLDED */
3730 static int __follow_pte(struct mm_struct *mm, unsigned long address,
3731 pte_t **ptepp, spinlock_t **ptlp)
3733 pgd_t *pgd;
3734 pud_t *pud;
3735 pmd_t *pmd;
3736 pte_t *ptep;
3738 pgd = pgd_offset(mm, address);
3739 if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
3740 goto out;
3742 pud = pud_offset(pgd, address);
3743 if (pud_none(*pud) || unlikely(pud_bad(*pud)))
3744 goto out;
3746 pmd = pmd_offset(pud, address);
3747 VM_BUG_ON(pmd_trans_huge(*pmd));
3748 if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
3749 goto out;
3751 /* We cannot handle huge page PFN maps. Luckily they don't exist. */
3752 if (pmd_huge(*pmd))
3753 goto out;
3755 ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
3756 if (!ptep)
3757 goto out;
3758 if (!pte_present(*ptep))
3759 goto unlock;
3760 *ptepp = ptep;
3761 return 0;
3762 unlock:
3763 pte_unmap_unlock(ptep, *ptlp);
3764 out:
3765 return -EINVAL;
3768 static inline int follow_pte(struct mm_struct *mm, unsigned long address,
3769 pte_t **ptepp, spinlock_t **ptlp)
3771 int res;
3773 /* (void) is needed to make gcc happy */
3774 (void) __cond_lock(*ptlp,
3775 !(res = __follow_pte(mm, address, ptepp, ptlp)));
3776 return res;
3780 * follow_pfn - look up PFN at a user virtual address
3781 * @vma: memory mapping
3782 * @address: user virtual address
3783 * @pfn: location to store found PFN
3785 * Only IO mappings and raw PFN mappings are allowed.
3787 * Returns zero and the pfn at @pfn on success, -ve otherwise.
3789 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
3790 unsigned long *pfn)
3792 int ret = -EINVAL;
3793 spinlock_t *ptl;
3794 pte_t *ptep;
3796 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
3797 return ret;
3799 ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
3800 if (ret)
3801 return ret;
3802 *pfn = pte_pfn(*ptep);
3803 pte_unmap_unlock(ptep, ptl);
3804 return 0;
3806 EXPORT_SYMBOL(follow_pfn);
3808 #ifdef CONFIG_HAVE_IOREMAP_PROT
3809 int follow_phys(struct vm_area_struct *vma,
3810 unsigned long address, unsigned int flags,
3811 unsigned long *prot, resource_size_t *phys)
3813 int ret = -EINVAL;
3814 pte_t *ptep, pte;
3815 spinlock_t *ptl;
3817 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
3818 goto out;
3820 if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
3821 goto out;
3822 pte = *ptep;
3824 if ((flags & FOLL_WRITE) && !pte_write(pte))
3825 goto unlock;
3827 *prot = pgprot_val(pte_pgprot(pte));
3828 *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
3830 ret = 0;
3831 unlock:
3832 pte_unmap_unlock(ptep, ptl);
3833 out:
3834 return ret;
3837 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
3838 void *buf, int len, int write)
3840 resource_size_t phys_addr;
3841 unsigned long prot = 0;
3842 void __iomem *maddr;
3843 int offset = addr & (PAGE_SIZE-1);
3845 if (follow_phys(vma, addr, write, &prot, &phys_addr))
3846 return -EINVAL;
3848 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
3849 if (write)
3850 memcpy_toio(maddr + offset, buf, len);
3851 else
3852 memcpy_fromio(buf, maddr + offset, len);
3853 iounmap(maddr);
3855 return len;
3857 EXPORT_SYMBOL_GPL(generic_access_phys);
3858 #endif
3861 * Access another process' address space as given in mm. If non-NULL, use the
3862 * given task for page fault accounting.
3864 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
3865 unsigned long addr, void *buf, int len, unsigned int gup_flags)
3867 struct vm_area_struct *vma;
3868 void *old_buf = buf;
3869 int write = gup_flags & FOLL_WRITE;
3871 down_read(&mm->mmap_sem);
3872 /* ignore errors, just check how much was successfully transferred */
3873 while (len) {
3874 int bytes, ret, offset;
3875 void *maddr;
3876 struct page *page = NULL;
3878 ret = get_user_pages_remote(tsk, mm, addr, 1,
3879 gup_flags, &page, &vma);
3880 if (ret <= 0) {
3881 #ifndef CONFIG_HAVE_IOREMAP_PROT
3882 break;
3883 #else
3885 * Check if this is a VM_IO | VM_PFNMAP VMA, which
3886 * we can access using slightly different code.
3888 vma = find_vma(mm, addr);
3889 if (!vma || vma->vm_start > addr)
3890 break;
3891 if (vma->vm_ops && vma->vm_ops->access)
3892 ret = vma->vm_ops->access(vma, addr, buf,
3893 len, write);
3894 if (ret <= 0)
3895 break;
3896 bytes = ret;
3897 #endif
3898 } else {
3899 bytes = len;
3900 offset = addr & (PAGE_SIZE-1);
3901 if (bytes > PAGE_SIZE-offset)
3902 bytes = PAGE_SIZE-offset;
3904 maddr = kmap(page);
3905 if (write) {
3906 copy_to_user_page(vma, page, addr,
3907 maddr + offset, buf, bytes);
3908 set_page_dirty_lock(page);
3909 } else {
3910 copy_from_user_page(vma, page, addr,
3911 buf, maddr + offset, bytes);
3913 kunmap(page);
3914 put_page(page);
3916 len -= bytes;
3917 buf += bytes;
3918 addr += bytes;
3920 up_read(&mm->mmap_sem);
3922 return buf - old_buf;
3926 * access_remote_vm - access another process' address space
3927 * @mm: the mm_struct of the target address space
3928 * @addr: start address to access
3929 * @buf: source or destination buffer
3930 * @len: number of bytes to transfer
3931 * @gup_flags: flags modifying lookup behaviour
3933 * The caller must hold a reference on @mm.
3935 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
3936 void *buf, int len, unsigned int gup_flags)
3938 return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
3942 * Access another process' address space.
3943 * Source/target buffer must be kernel space,
3944 * Do not walk the page table directly, use get_user_pages
3946 int access_process_vm(struct task_struct *tsk, unsigned long addr,
3947 void *buf, int len, unsigned int gup_flags)
3949 struct mm_struct *mm;
3950 int ret;
3952 mm = get_task_mm(tsk);
3953 if (!mm)
3954 return 0;
3956 ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
3958 mmput(mm);
3960 return ret;
3964 * Print the name of a VMA.
3966 void print_vma_addr(char *prefix, unsigned long ip)
3968 struct mm_struct *mm = current->mm;
3969 struct vm_area_struct *vma;
3972 * Do not print if we are in atomic
3973 * contexts (in exception stacks, etc.):
3975 if (preempt_count())
3976 return;
3978 down_read(&mm->mmap_sem);
3979 vma = find_vma(mm, ip);
3980 if (vma && vma->vm_file) {
3981 struct file *f = vma->vm_file;
3982 char *buf = (char *)__get_free_page(GFP_KERNEL);
3983 if (buf) {
3984 char *p;
3986 p = file_path(f, buf, PAGE_SIZE);
3987 if (IS_ERR(p))
3988 p = "?";
3989 printk("%s%s[%lx+%lx]", prefix, kbasename(p),
3990 vma->vm_start,
3991 vma->vm_end - vma->vm_start);
3992 free_page((unsigned long)buf);
3995 up_read(&mm->mmap_sem);
3998 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
3999 void __might_fault(const char *file, int line)
4002 * Some code (nfs/sunrpc) uses socket ops on kernel memory while
4003 * holding the mmap_sem, this is safe because kernel memory doesn't
4004 * get paged out, therefore we'll never actually fault, and the
4005 * below annotations will generate false positives.
4007 if (segment_eq(get_fs(), KERNEL_DS))
4008 return;
4009 if (pagefault_disabled())
4010 return;
4011 __might_sleep(file, line, 0);
4012 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
4013 if (current->mm)
4014 might_lock_read(&current->mm->mmap_sem);
4015 #endif
4017 EXPORT_SYMBOL(__might_fault);
4018 #endif
4020 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
4021 static void clear_gigantic_page(struct page *page,
4022 unsigned long addr,
4023 unsigned int pages_per_huge_page)
4025 int i;
4026 struct page *p = page;
4028 might_sleep();
4029 for (i = 0; i < pages_per_huge_page;
4030 i++, p = mem_map_next(p, page, i)) {
4031 cond_resched();
4032 clear_user_highpage(p, addr + i * PAGE_SIZE);
4035 void clear_huge_page(struct page *page,
4036 unsigned long addr, unsigned int pages_per_huge_page)
4038 int i;
4040 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4041 clear_gigantic_page(page, addr, pages_per_huge_page);
4042 return;
4045 might_sleep();
4046 for (i = 0; i < pages_per_huge_page; i++) {
4047 cond_resched();
4048 clear_user_highpage(page + i, addr + i * PAGE_SIZE);
4052 static void copy_user_gigantic_page(struct page *dst, struct page *src,
4053 unsigned long addr,
4054 struct vm_area_struct *vma,
4055 unsigned int pages_per_huge_page)
4057 int i;
4058 struct page *dst_base = dst;
4059 struct page *src_base = src;
4061 for (i = 0; i < pages_per_huge_page; ) {
4062 cond_resched();
4063 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
4065 i++;
4066 dst = mem_map_next(dst, dst_base, i);
4067 src = mem_map_next(src, src_base, i);
4071 void copy_user_huge_page(struct page *dst, struct page *src,
4072 unsigned long addr, struct vm_area_struct *vma,
4073 unsigned int pages_per_huge_page)
4075 int i;
4077 if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
4078 copy_user_gigantic_page(dst, src, addr, vma,
4079 pages_per_huge_page);
4080 return;
4083 might_sleep();
4084 for (i = 0; i < pages_per_huge_page; i++) {
4085 cond_resched();
4086 copy_user_highpage(dst + i, src + i, addr + i*PAGE_SIZE, vma);
4089 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
4091 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
4093 static struct kmem_cache *page_ptl_cachep;
4095 void __init ptlock_cache_init(void)
4097 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
4098 SLAB_PANIC, NULL);
4101 bool ptlock_alloc(struct page *page)
4103 spinlock_t *ptl;
4105 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
4106 if (!ptl)
4107 return false;
4108 page->ptl = ptl;
4109 return true;
4112 void ptlock_free(struct page *page)
4114 kmem_cache_free(page_ptl_cachep, page->ptl);
4116 #endif