mm: THP: workaround: only allow including specific headers for FINEGRAINED_THP config...
[platform/kernel/linux-rpi.git] / mm / memory.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  linux/mm/memory.c
4  *
5  *  Copyright (C) 1991, 1992, 1993, 1994  Linus Torvalds
6  */
7
8 /*
9  * demand-loading started 01.12.91 - seems it is high on the list of
10  * things wanted, and it should be easy to implement. - Linus
11  */
12
13 /*
14  * Ok, demand-loading was easy, shared pages a little bit tricker. Shared
15  * pages started 02.12.91, seems to work. - Linus.
16  *
17  * Tested sharing by executing about 30 /bin/sh: under the old kernel it
18  * would have taken more than the 6M I have free, but it worked well as
19  * far as I could see.
20  *
21  * Also corrected some "invalidate()"s - I wasn't doing enough of them.
22  */
23
24 /*
25  * Real VM (paging to/from disk) started 18.12.91. Much more work and
26  * thought has to go into this. Oh, well..
27  * 19.12.91  -  works, somewhat. Sometimes I get faults, don't know why.
28  *              Found it. Everything seems to work now.
29  * 20.12.91  -  Ok, making the swap-device changeable like the root.
30  */
31
32 /*
33  * 05.04.94  -  Multi-page memory management added for v1.1.
34  *              Idea by Alex Bligh (alex@cconcepts.co.uk)
35  *
36  * 16.07.99  -  Support of BIGMEM added by Gerhard Wichert, Siemens AG
37  *              (Gerhard.Wichert@pdb.siemens.de)
38  *
39  * Aug/Sep 2004 Changed to four level page tables (Andi Kleen)
40  */
41
42 #include <linux/kernel_stat.h>
43 #include <linux/mm.h>
44 #include <linux/sched/mm.h>
45 #include <linux/sched/coredump.h>
46 #include <linux/sched/numa_balancing.h>
47 #include <linux/sched/task.h>
48 #include <linux/hugetlb.h>
49 #include <linux/mman.h>
50 #include <linux/swap.h>
51 #include <linux/highmem.h>
52 #include <linux/pagemap.h>
53 #include <linux/memremap.h>
54 #include <linux/ksm.h>
55 #include <linux/rmap.h>
56 #include <linux/export.h>
57 #include <linux/delayacct.h>
58 #include <linux/init.h>
59 #include <linux/pfn_t.h>
60 #include <linux/writeback.h>
61 #include <linux/memcontrol.h>
62 #include <linux/mmu_notifier.h>
63 #include <linux/swapops.h>
64 #include <linux/elf.h>
65 #include <linux/gfp.h>
66 #include <linux/migrate.h>
67 #include <linux/string.h>
68 #include <linux/debugfs.h>
69 #include <linux/userfaultfd_k.h>
70 #include <linux/dax.h>
71 #include <linux/oom.h>
72 #include <linux/numa.h>
73 #include <linux/perf_event.h>
74 #include <linux/ptrace.h>
75 #include <linux/vmalloc.h>
76
77 #include <trace/events/kmem.h>
78
79 #include <asm/io.h>
80 #include <asm/mmu_context.h>
81 #include <asm/pgalloc.h>
82 #include <linux/uaccess.h>
83 #include <asm/tlb.h>
84 #include <asm/tlbflush.h>
85 #ifdef CONFIG_FINEGRAINED_THP
86 #include <asm/huge_mm.h>
87 #include <asm/finegrained_thp.h>
88 #else
89 #include <asm-generic/huge_mm.h>
90 #include <asm-generic/finegrained_thp.h>
91 #endif
92
93 #include "pgalloc-track.h"
94 #include "internal.h"
95
96 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
97 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
98 #endif
99
100 #ifndef CONFIG_NEED_MULTIPLE_NODES
101 /* use the per-pgdat data instead for discontigmem - mbligh */
102 unsigned long max_mapnr;
103 EXPORT_SYMBOL(max_mapnr);
104
105 struct page *mem_map;
106 EXPORT_SYMBOL(mem_map);
107 #endif
108
109 /*
110  * A number of key systems in x86 including ioremap() rely on the assumption
111  * that high_memory defines the upper bound on direct map memory, then end
112  * of ZONE_NORMAL.  Under CONFIG_DISCONTIG this means that max_low_pfn and
113  * highstart_pfn must be the same; there must be no gap between ZONE_NORMAL
114  * and ZONE_HIGHMEM.
115  */
116 void *high_memory;
117 EXPORT_SYMBOL(high_memory);
118
119 /*
120  * Randomize the address space (stacks, mmaps, brk, etc.).
121  *
122  * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
123  *   as ancient (libc5 based) binaries can segfault. )
124  */
125 int randomize_va_space __read_mostly =
126 #ifdef CONFIG_COMPAT_BRK
127                                         1;
128 #else
129                                         2;
130 #endif
131
132 #ifndef arch_faults_on_old_pte
133 static inline bool arch_faults_on_old_pte(void)
134 {
135         /*
136          * Those arches which don't have hw access flag feature need to
137          * implement their own helper. By default, "true" means pagefault
138          * will be hit on old pte.
139          */
140         return true;
141 }
142 #endif
143
144 static int __init disable_randmaps(char *s)
145 {
146         randomize_va_space = 0;
147         return 1;
148 }
149 __setup("norandmaps", disable_randmaps);
150
151 unsigned long zero_pfn __read_mostly;
152 EXPORT_SYMBOL(zero_pfn);
153
154 unsigned long highest_memmap_pfn __read_mostly;
155
156 atomic_long_t nr_phys_cont_pte_pages;
157 atomic_long_t nr_phys_huge_pmd_pages;
158
159 unsigned long phys_cont_pte_pages(void)
160 {
161         return atomic_long_read(&nr_phys_cont_pte_pages);
162 }
163
164 unsigned long phys_huge_pmd_pages(void)
165 {
166         return atomic_long_read(&nr_phys_huge_pmd_pages);
167 }
168
169 /*
170  * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
171  */
172 static int __init init_zero_pfn(void)
173 {
174         zero_pfn = page_to_pfn(ZERO_PAGE(0));
175         return 0;
176 }
177 core_initcall(init_zero_pfn);
178
179 void mm_trace_rss_stat(struct mm_struct *mm, int member, long count)
180 {
181         trace_rss_stat(mm, member, count);
182 }
183
184 #if defined(SPLIT_RSS_COUNTING)
185
186 void sync_mm_rss(struct mm_struct *mm)
187 {
188         int i;
189
190         for (i = 0; i < NR_MM_COUNTERS; i++) {
191                 if (current->rss_stat.count[i]) {
192                         add_mm_counter(mm, i, current->rss_stat.count[i]);
193                         current->rss_stat.count[i] = 0;
194                 }
195         }
196         current->rss_stat.events = 0;
197 }
198
199 static void add_mm_counter_fast(struct mm_struct *mm, int member, int val)
200 {
201         struct task_struct *task = current;
202
203         if (likely(task->mm == mm))
204                 task->rss_stat.count[member] += val;
205         else
206                 add_mm_counter(mm, member, val);
207 }
208 #define inc_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, 1)
209 #define dec_mm_counter_fast(mm, member) add_mm_counter_fast(mm, member, -1)
210
211 /* sync counter once per 64 page faults */
212 #define TASK_RSS_EVENTS_THRESH  (64)
213 static void check_sync_rss_stat(struct task_struct *task)
214 {
215         if (unlikely(task != current))
216                 return;
217         if (unlikely(task->rss_stat.events++ > TASK_RSS_EVENTS_THRESH))
218                 sync_mm_rss(task->mm);
219 }
220 #else /* SPLIT_RSS_COUNTING */
221
222 #define inc_mm_counter_fast(mm, member) inc_mm_counter(mm, member)
223 #define dec_mm_counter_fast(mm, member) dec_mm_counter(mm, member)
224
225 static void check_sync_rss_stat(struct task_struct *task)
226 {
227 }
228
229 #endif /* SPLIT_RSS_COUNTING */
230
231 #ifdef CONFIG_FINEGRAINED_THP
232 void thp_print_cont_pte_table(struct mm_struct *mm,
233                         unsigned long addr, pte_t *ptep, unsigned long line);
234 #endif /* CONFIG_FINEGRAINED_THP */
235
236 /*
237  * Note: this doesn't free the actual pages themselves. That
238  * has been handled earlier when unmapping all the memory regions.
239  */
240 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
241                            unsigned long addr)
242 {
243         pgtable_t token = pmd_pgtable(*pmd);
244         pmd_clear(pmd);
245         pte_free_tlb(tlb, token, addr);
246         mm_dec_nr_ptes(tlb->mm);
247 }
248
249 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
250                                 unsigned long addr, unsigned long end,
251                                 unsigned long floor, unsigned long ceiling)
252 {
253         pmd_t *pmd;
254         unsigned long next;
255         unsigned long start;
256
257         start = addr;
258         pmd = pmd_offset(pud, addr);
259         do {
260                 next = pmd_addr_end(addr, end);
261                 if (pmd_none_or_clear_bad(pmd))
262                         continue;
263                 free_pte_range(tlb, pmd, addr);
264         } while (pmd++, addr = next, addr != end);
265
266         start &= PUD_MASK;
267         if (start < floor)
268                 return;
269         if (ceiling) {
270                 ceiling &= PUD_MASK;
271                 if (!ceiling)
272                         return;
273         }
274         if (end - 1 > ceiling - 1)
275                 return;
276
277         pmd = pmd_offset(pud, start);
278         pud_clear(pud);
279         pmd_free_tlb(tlb, pmd, start);
280         mm_dec_nr_pmds(tlb->mm);
281 }
282
283 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
284                                 unsigned long addr, unsigned long end,
285                                 unsigned long floor, unsigned long ceiling)
286 {
287         pud_t *pud;
288         unsigned long next;
289         unsigned long start;
290
291         start = addr;
292         pud = pud_offset(p4d, addr);
293         do {
294                 next = pud_addr_end(addr, end);
295                 if (pud_none_or_clear_bad(pud))
296                         continue;
297                 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
298         } while (pud++, addr = next, addr != end);
299
300         start &= P4D_MASK;
301         if (start < floor)
302                 return;
303         if (ceiling) {
304                 ceiling &= P4D_MASK;
305                 if (!ceiling)
306                         return;
307         }
308         if (end - 1 > ceiling - 1)
309                 return;
310
311         pud = pud_offset(p4d, start);
312         p4d_clear(p4d);
313         pud_free_tlb(tlb, pud, start);
314         mm_dec_nr_puds(tlb->mm);
315 }
316
317 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
318                                 unsigned long addr, unsigned long end,
319                                 unsigned long floor, unsigned long ceiling)
320 {
321         p4d_t *p4d;
322         unsigned long next;
323         unsigned long start;
324
325         start = addr;
326         p4d = p4d_offset(pgd, addr);
327         do {
328                 next = p4d_addr_end(addr, end);
329                 if (p4d_none_or_clear_bad(p4d))
330                         continue;
331                 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
332         } while (p4d++, addr = next, addr != end);
333
334         start &= PGDIR_MASK;
335         if (start < floor)
336                 return;
337         if (ceiling) {
338                 ceiling &= PGDIR_MASK;
339                 if (!ceiling)
340                         return;
341         }
342         if (end - 1 > ceiling - 1)
343                 return;
344
345         p4d = p4d_offset(pgd, start);
346         pgd_clear(pgd);
347         p4d_free_tlb(tlb, p4d, start);
348 }
349
350 /*
351  * This function frees user-level page tables of a process.
352  */
353 void free_pgd_range(struct mmu_gather *tlb,
354                         unsigned long addr, unsigned long end,
355                         unsigned long floor, unsigned long ceiling)
356 {
357         pgd_t *pgd;
358         unsigned long next;
359
360         /*
361          * The next few lines have given us lots of grief...
362          *
363          * Why are we testing PMD* at this top level?  Because often
364          * there will be no work to do at all, and we'd prefer not to
365          * go all the way down to the bottom just to discover that.
366          *
367          * Why all these "- 1"s?  Because 0 represents both the bottom
368          * of the address space and the top of it (using -1 for the
369          * top wouldn't help much: the masks would do the wrong thing).
370          * The rule is that addr 0 and floor 0 refer to the bottom of
371          * the address space, but end 0 and ceiling 0 refer to the top
372          * Comparisons need to use "end - 1" and "ceiling - 1" (though
373          * that end 0 case should be mythical).
374          *
375          * Wherever addr is brought up or ceiling brought down, we must
376          * be careful to reject "the opposite 0" before it confuses the
377          * subsequent tests.  But what about where end is brought down
378          * by PMD_SIZE below? no, end can't go down to 0 there.
379          *
380          * Whereas we round start (addr) and ceiling down, by different
381          * masks at different levels, in order to test whether a table
382          * now has no other vmas using it, so can be freed, we don't
383          * bother to round floor or end up - the tests don't need that.
384          */
385
386         addr &= PMD_MASK;
387         if (addr < floor) {
388                 addr += PMD_SIZE;
389                 if (!addr)
390                         return;
391         }
392         if (ceiling) {
393                 ceiling &= PMD_MASK;
394                 if (!ceiling)
395                         return;
396         }
397         if (end - 1 > ceiling - 1)
398                 end -= PMD_SIZE;
399         if (addr > end - 1)
400                 return;
401         /*
402          * We add page table cache pages with PAGE_SIZE,
403          * (see pte_free_tlb()), flush the tlb if we need
404          */
405         tlb_change_page_size(tlb, PAGE_SIZE);
406         pgd = pgd_offset(tlb->mm, addr);
407         do {
408                 next = pgd_addr_end(addr, end);
409                 if (pgd_none_or_clear_bad(pgd))
410                         continue;
411                 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
412         } while (pgd++, addr = next, addr != end);
413 }
414
415 void free_pgtables(struct mmu_gather *tlb, struct vm_area_struct *vma,
416                 unsigned long floor, unsigned long ceiling)
417 {
418         while (vma) {
419                 struct vm_area_struct *next = vma->vm_next;
420                 unsigned long addr = vma->vm_start;
421
422                 /*
423                  * Hide vma from rmap and truncate_pagecache before freeing
424                  * pgtables
425                  */
426                 unlink_anon_vmas(vma);
427                 unlink_file_vma(vma);
428
429                 if (is_vm_hugetlb_page(vma)) {
430                         hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
431                                 floor, next ? next->vm_start : ceiling);
432                 } else {
433                         /*
434                          * Optimization: gather nearby vmas into one call down
435                          */
436                         while (next && next->vm_start <= vma->vm_end + PMD_SIZE
437                                && !is_vm_hugetlb_page(next)) {
438                                 vma = next;
439                                 next = vma->vm_next;
440                                 unlink_anon_vmas(vma);
441                                 unlink_file_vma(vma);
442                         }
443                         free_pgd_range(tlb, addr, vma->vm_end,
444                                 floor, next ? next->vm_start : ceiling);
445                 }
446                 vma = next;
447         }
448 }
449
450 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
451 {
452         spinlock_t *ptl;
453         pgtable_t new = pte_alloc_one(mm);
454         if (!new)
455                 return -ENOMEM;
456
457         /*
458          * Ensure all pte setup (eg. pte page lock and page clearing) are
459          * visible before the pte is made visible to other CPUs by being
460          * put into page tables.
461          *
462          * The other side of the story is the pointer chasing in the page
463          * table walking code (when walking the page table without locking;
464          * ie. most of the time). Fortunately, these data accesses consist
465          * of a chain of data-dependent loads, meaning most CPUs (alpha
466          * being the notable exception) will already guarantee loads are
467          * seen in-order. See the alpha page table accessors for the
468          * smp_rmb() barriers in page table walking code.
469          */
470         smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
471
472         ptl = pmd_lock(mm, pmd);
473         if (likely(pmd_none(*pmd))) {   /* Has another populated it ? */
474                 mm_inc_nr_ptes(mm);
475                 pmd_populate(mm, pmd, new);
476                 new = NULL;
477         }
478         spin_unlock(ptl);
479         if (new)
480                 pte_free(mm, new);
481         return 0;
482 }
483
484 int __pte_alloc_kernel(pmd_t *pmd)
485 {
486         pte_t *new = pte_alloc_one_kernel(&init_mm);
487         if (!new)
488                 return -ENOMEM;
489
490         smp_wmb(); /* See comment in __pte_alloc */
491
492         spin_lock(&init_mm.page_table_lock);
493         if (likely(pmd_none(*pmd))) {   /* Has another populated it ? */
494                 pmd_populate_kernel(&init_mm, pmd, new);
495                 new = NULL;
496         }
497         spin_unlock(&init_mm.page_table_lock);
498         if (new)
499                 pte_free_kernel(&init_mm, new);
500         return 0;
501 }
502
503 static inline void init_rss_vec(int *rss)
504 {
505         memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
506 }
507
508 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
509 {
510         int i;
511
512         if (current->mm == mm)
513                 sync_mm_rss(mm);
514         for (i = 0; i < NR_MM_COUNTERS; i++)
515                 if (rss[i])
516                         add_mm_counter(mm, i, rss[i]);
517 }
518
519 /*
520  * This function is called to print an error when a bad pte
521  * is found. For example, we might have a PFN-mapped pte in
522  * a region that doesn't allow it.
523  *
524  * The calling function must still handle the error.
525  */
526 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
527                           pte_t pte, struct page *page)
528 {
529         pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
530         p4d_t *p4d = p4d_offset(pgd, addr);
531         pud_t *pud = pud_offset(p4d, addr);
532         pmd_t *pmd = pmd_offset(pud, addr);
533         struct address_space *mapping;
534         pgoff_t index;
535         static unsigned long resume;
536         static unsigned long nr_shown;
537         static unsigned long nr_unshown;
538
539         /*
540          * Allow a burst of 60 reports, then keep quiet for that minute;
541          * or allow a steady drip of one report per second.
542          */
543         if (nr_shown == 60) {
544                 if (time_before(jiffies, resume)) {
545                         nr_unshown++;
546                         return;
547                 }
548                 if (nr_unshown) {
549                         pr_alert("BUG: Bad page map: %lu messages suppressed\n",
550                                  nr_unshown);
551                         nr_unshown = 0;
552                 }
553                 nr_shown = 0;
554         }
555         if (nr_shown++ == 0)
556                 resume = jiffies + 60 * HZ;
557
558         mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
559         index = linear_page_index(vma, addr);
560
561         pr_alert("BUG: Bad page map in process %s  pte:%08llx pmd:%08llx\n",
562                  current->comm,
563                  (long long)pte_val(pte), (long long)pmd_val(*pmd));
564         if (page)
565                 dump_page(page, "bad pte");
566         pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n",
567                  (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
568         pr_alert("file:%pD fault:%ps mmap:%ps readpage:%ps\n",
569                  vma->vm_file,
570                  vma->vm_ops ? vma->vm_ops->fault : NULL,
571                  vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
572                  mapping ? mapping->a_ops->readpage : NULL);
573         dump_stack();
574         add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
575 }
576
577 /*
578  * vm_normal_page -- This function gets the "struct page" associated with a pte.
579  *
580  * "Special" mappings do not wish to be associated with a "struct page" (either
581  * it doesn't exist, or it exists but they don't want to touch it). In this
582  * case, NULL is returned here. "Normal" mappings do have a struct page.
583  *
584  * There are 2 broad cases. Firstly, an architecture may define a pte_special()
585  * pte bit, in which case this function is trivial. Secondly, an architecture
586  * may not have a spare pte bit, which requires a more complicated scheme,
587  * described below.
588  *
589  * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
590  * special mapping (even if there are underlying and valid "struct pages").
591  * COWed pages of a VM_PFNMAP are always normal.
592  *
593  * The way we recognize COWed pages within VM_PFNMAP mappings is through the
594  * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
595  * set, and the vm_pgoff will point to the first PFN mapped: thus every special
596  * mapping will always honor the rule
597  *
598  *      pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
599  *
600  * And for normal mappings this is false.
601  *
602  * This restricts such mappings to be a linear translation from virtual address
603  * to pfn. To get around this restriction, we allow arbitrary mappings so long
604  * as the vma is not a COW mapping; in that case, we know that all ptes are
605  * special (because none can have been COWed).
606  *
607  *
608  * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
609  *
610  * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
611  * page" backing, however the difference is that _all_ pages with a struct
612  * page (that is, those where pfn_valid is true) are refcounted and considered
613  * normal pages by the VM. The disadvantage is that pages are refcounted
614  * (which can be slower and simply not an option for some PFNMAP users). The
615  * advantage is that we don't have to follow the strict linearity rule of
616  * PFNMAP mappings in order to support COWable mappings.
617  *
618  */
619 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
620                             pte_t pte)
621 {
622         unsigned long pfn = pte_pfn(pte);
623
624         if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
625                 if (likely(!pte_special(pte)))
626                         goto check_pfn;
627                 if (vma->vm_ops && vma->vm_ops->find_special_page)
628                         return vma->vm_ops->find_special_page(vma, addr);
629                 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
630                         return NULL;
631                 if (is_zero_pfn(pfn))
632                         return NULL;
633                 if (pte_devmap(pte))
634                         return NULL;
635
636                 print_bad_pte(vma, addr, pte, NULL);
637                 return NULL;
638         }
639
640         /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
641
642         if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
643                 if (vma->vm_flags & VM_MIXEDMAP) {
644                         if (!pfn_valid(pfn))
645                                 return NULL;
646                         goto out;
647                 } else {
648                         unsigned long off;
649                         off = (addr - vma->vm_start) >> PAGE_SHIFT;
650                         if (pfn == vma->vm_pgoff + off)
651                                 return NULL;
652                         if (!is_cow_mapping(vma->vm_flags))
653                                 return NULL;
654                 }
655         }
656
657         if (is_zero_pfn(pfn))
658                 return NULL;
659
660 check_pfn:
661         if (unlikely(pfn > highest_memmap_pfn)) {
662                 print_bad_pte(vma, addr, pte, NULL);
663                 return NULL;
664         }
665
666         /*
667          * NOTE! We still have PageReserved() pages in the page tables.
668          * eg. VDSO mappings can cause them to exist.
669          */
670 out:
671         return pfn_to_page(pfn);
672 }
673
674 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
675 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
676                                 pmd_t pmd)
677 {
678         unsigned long pfn = pmd_pfn(pmd);
679
680         /*
681          * There is no pmd_special() but there may be special pmds, e.g.
682          * in a direct-access (dax) mapping, so let's just replicate the
683          * !CONFIG_ARCH_HAS_PTE_SPECIAL case from vm_normal_page() here.
684          */
685         if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
686                 if (vma->vm_flags & VM_MIXEDMAP) {
687                         if (!pfn_valid(pfn))
688                                 return NULL;
689                         goto out;
690                 } else {
691                         unsigned long off;
692                         off = (addr - vma->vm_start) >> PAGE_SHIFT;
693                         if (pfn == vma->vm_pgoff + off)
694                                 return NULL;
695                         if (!is_cow_mapping(vma->vm_flags))
696                                 return NULL;
697                 }
698         }
699
700         if (pmd_devmap(pmd))
701                 return NULL;
702         if (is_huge_zero_pmd(pmd))
703                 return NULL;
704         if (unlikely(pfn > highest_memmap_pfn))
705                 return NULL;
706
707         /*
708          * NOTE! We still have PageReserved() pages in the page tables.
709          * eg. VDSO mappings can cause them to exist.
710          */
711 out:
712         return pfn_to_page(pfn);
713 }
714 #endif
715
716 /*
717  * copy one vm_area from one task to the other. Assumes the page tables
718  * already present in the new task to be cleared in the whole range
719  * covered by this vma.
720  */
721
722 static unsigned long
723 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
724                 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *vma,
725                 unsigned long addr, int *rss)
726 {
727         unsigned long vm_flags = vma->vm_flags;
728         pte_t pte = *src_pte;
729         struct page *page;
730         swp_entry_t entry = pte_to_swp_entry(pte);
731
732         if (likely(!non_swap_entry(entry))) {
733                 if (swap_duplicate(entry) < 0)
734                         return entry.val;
735
736                 /* make sure dst_mm is on swapoff's mmlist. */
737                 if (unlikely(list_empty(&dst_mm->mmlist))) {
738                         spin_lock(&mmlist_lock);
739                         if (list_empty(&dst_mm->mmlist))
740                                 list_add(&dst_mm->mmlist,
741                                                 &src_mm->mmlist);
742                         spin_unlock(&mmlist_lock);
743                 }
744                 rss[MM_SWAPENTS]++;
745         } else if (is_migration_entry(entry)) {
746                 page = migration_entry_to_page(entry);
747
748                 rss[mm_counter(page)]++;
749
750                 if (is_write_migration_entry(entry) &&
751                                 is_cow_mapping(vm_flags)) {
752                         /*
753                          * COW mappings require pages in both
754                          * parent and child to be set to read.
755                          */
756                         make_migration_entry_read(&entry);
757                         pte = swp_entry_to_pte(entry);
758                         pte = arch_pte_clearhuge(pte);
759                         if (pte_swp_soft_dirty(*src_pte))
760                                 pte = pte_swp_mksoft_dirty(pte);
761                         if (pte_swp_uffd_wp(*src_pte))
762                                 pte = pte_swp_mkuffd_wp(pte);
763                         set_pte_at(src_mm, addr, src_pte, pte);
764                 }
765         } else if (is_device_private_entry(entry)) {
766                 page = device_private_entry_to_page(entry);
767
768                 /*
769                  * Update rss count even for unaddressable pages, as
770                  * they should treated just like normal pages in this
771                  * respect.
772                  *
773                  * We will likely want to have some new rss counters
774                  * for unaddressable pages, at some point. But for now
775                  * keep things as they are.
776                  */
777                 get_page(page);
778                 rss[mm_counter(page)]++;
779                 page_dup_rmap(page, false);
780
781                 /*
782                  * We do not preserve soft-dirty information, because so
783                  * far, checkpoint/restore is the only feature that
784                  * requires that. And checkpoint/restore does not work
785                  * when a device driver is involved (you cannot easily
786                  * save and restore device driver state).
787                  */
788                 if (is_write_device_private_entry(entry) &&
789                     is_cow_mapping(vm_flags)) {
790                         make_device_private_entry_read(&entry);
791                         pte = swp_entry_to_pte(entry);
792                         pte = arch_pte_clearhuge(pte);
793                         if (pte_swp_uffd_wp(*src_pte))
794                                 pte = pte_swp_mkuffd_wp(pte);
795                         set_pte_at(src_mm, addr, src_pte, pte);
796                 }
797         }
798         pte = arch_pte_clearhuge(pte);
799         set_pte_at(dst_mm, addr, dst_pte, pte);
800         return 0;
801 }
802
803 /*
804  * Copy a present and normal page if necessary.
805  *
806  * NOTE! The usual case is that this doesn't need to do
807  * anything, and can just return a positive value. That
808  * will let the caller know that it can just increase
809  * the page refcount and re-use the pte the traditional
810  * way.
811  *
812  * But _if_ we need to copy it because it needs to be
813  * pinned in the parent (and the child should get its own
814  * copy rather than just a reference to the same page),
815  * we'll do that here and return zero to let the caller
816  * know we're done.
817  *
818  * And if we need a pre-allocated page but don't yet have
819  * one, return a negative error to let the preallocation
820  * code know so that it can do so outside the page table
821  * lock.
822  */
823 static inline int
824 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
825                   pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
826                   struct page **prealloc, pte_t pte, struct page *page)
827 {
828         struct mm_struct *src_mm = src_vma->vm_mm;
829         struct page *new_page;
830
831         if (!is_cow_mapping(src_vma->vm_flags))
832                 return 1;
833
834         /*
835          * What we want to do is to check whether this page may
836          * have been pinned by the parent process.  If so,
837          * instead of wrprotect the pte on both sides, we copy
838          * the page immediately so that we'll always guarantee
839          * the pinned page won't be randomly replaced in the
840          * future.
841          *
842          * The page pinning checks are just "has this mm ever
843          * seen pinning", along with the (inexact) check of
844          * the page count. That might give false positives for
845          * for pinning, but it will work correctly.
846          */
847         if (likely(!atomic_read(&src_mm->has_pinned)))
848                 return 1;
849         if (likely(!page_maybe_dma_pinned(page)))
850                 return 1;
851
852         new_page = *prealloc;
853         if (!new_page)
854                 return -EAGAIN;
855
856         /*
857          * We have a prealloc page, all good!  Take it
858          * over and copy the page & arm it.
859          */
860         *prealloc = NULL;
861         copy_user_highpage(new_page, page, addr, src_vma);
862         __SetPageUptodate(new_page);
863         page_add_new_anon_rmap(new_page, dst_vma, addr, false);
864         lru_cache_add_inactive_or_unevictable(new_page, dst_vma);
865         rss[mm_counter(new_page)]++;
866
867         /* All done, just insert the new page copy in the child */
868         pte = mk_pte(new_page, dst_vma->vm_page_prot);
869         pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
870         set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
871         return 0;
872 }
873
874 /*
875  * Copy one pte.  Returns 0 if succeeded, or -EAGAIN if one preallocated page
876  * is required to copy this pte.
877  */
878 static inline int
879 copy_present_pte(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
880                  pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
881                  struct page **prealloc)
882 {
883         struct mm_struct *src_mm = src_vma->vm_mm;
884         unsigned long vm_flags = src_vma->vm_flags;
885         pte_t pte = *src_pte;
886         struct page *page;
887
888         page = vm_normal_page(src_vma, addr, pte);
889         if (page) {
890                 int retval;
891                 /*
892                  * when 64KB hugepage map is copied,
893                  * clear contiguous bit
894                  */
895                 pte = arch_pte_clearhuge(pte);
896
897                 retval = copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
898                                            addr, rss, prealloc, pte, page);
899                 if (retval <= 0)
900                         return retval;
901
902                 get_page(page);
903                 page_dup_rmap(page, false);
904                 rss[mm_counter(page)]++;
905         }
906
907         /*
908          * If it's a COW mapping, write protect it both
909          * in the parent and the child
910          */
911         if (is_cow_mapping(vm_flags) && pte_write(pte)) {
912                 ptep_set_wrprotect(src_mm, addr, src_pte);
913                 pte = pte_wrprotect(pte);
914         }
915
916         /*
917          * If it's a shared mapping, mark it clean in
918          * the child
919          */
920         if (vm_flags & VM_SHARED)
921                 pte = pte_mkclean(pte);
922         pte = pte_mkold(pte);
923         pte = arch_pte_clearhuge(pte);
924         /*
925          * Make sure the _PAGE_UFFD_WP bit is cleared if the new VMA
926          * does not have the VM_UFFD_WP, which means that the uffd
927          * fork event is not enabled.
928          */
929         if (!(vm_flags & VM_UFFD_WP))
930                 pte = pte_clear_uffd_wp(pte);
931
932         set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
933         return 0;
934 }
935
936 static inline struct page *
937 page_copy_prealloc(struct mm_struct *src_mm, struct vm_area_struct *vma,
938                    unsigned long addr)
939 {
940         struct page *new_page;
941
942         new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, addr);
943         if (!new_page)
944                 return NULL;
945
946         if (mem_cgroup_charge(new_page, src_mm, GFP_KERNEL)) {
947                 put_page(new_page);
948                 return NULL;
949         }
950         cgroup_throttle_swaprate(new_page, GFP_KERNEL);
951
952         return new_page;
953 }
954
955 static int
956 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
957                pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
958                unsigned long end)
959 {
960         struct mm_struct *dst_mm = dst_vma->vm_mm;
961         struct mm_struct *src_mm = src_vma->vm_mm;
962         pte_t *orig_src_pte, *orig_dst_pte;
963         pte_t *src_pte, *dst_pte;
964         spinlock_t *src_ptl, *dst_ptl;
965         int progress, ret = 0;
966         int rss[NR_MM_COUNTERS];
967         swp_entry_t entry = (swp_entry_t){0};
968         struct page *prealloc = NULL;
969
970 again:
971         progress = 0;
972         init_rss_vec(rss);
973
974         dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
975         if (!dst_pte) {
976                 ret = -ENOMEM;
977                 goto out;
978         }
979         src_pte = pte_offset_map(src_pmd, addr);
980         src_ptl = pte_lockptr(src_mm, src_pmd);
981         spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
982         orig_src_pte = src_pte;
983         orig_dst_pte = dst_pte;
984         arch_enter_lazy_mmu_mode();
985
986         do {
987                 /*
988                  * We are holding two locks at this point - either of them
989                  * could generate latencies in another task on another CPU.
990                  */
991                 if (progress >= 32) {
992                         progress = 0;
993                         if (need_resched() ||
994                             spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
995                                 break;
996                 }
997                 if (pte_none(*src_pte)) {
998                         progress++;
999                         continue;
1000                 }
1001
1002                 if (unlikely(!pte_present(*src_pte))) {
1003                         entry.val = copy_nonpresent_pte(dst_mm, src_mm,
1004                                                         dst_pte, src_pte,
1005                                                         src_vma, addr, rss);
1006                         if (entry.val)
1007                                 break;
1008                         progress += 8;
1009                         continue;
1010                 }
1011
1012                 /* copy_present_pte() will clear `*prealloc' if consumed */
1013                 ret = copy_present_pte(dst_vma, src_vma, dst_pte, src_pte,
1014                                        addr, rss, &prealloc);
1015                 /*
1016                  * If we need a pre-allocated page for this pte, drop the
1017                  * locks, allocate, and try again.
1018                  */
1019                 if (unlikely(ret == -EAGAIN))
1020                         break;
1021                 if (unlikely(prealloc)) {
1022                         /*
1023                          * pre-alloc page cannot be reused by next time so as
1024                          * to strictly follow mempolicy (e.g., alloc_page_vma()
1025                          * will allocate page according to address).  This
1026                          * could only happen if one pinned pte changed.
1027                          */
1028                         put_page(prealloc);
1029                         prealloc = NULL;
1030                 }
1031                 progress += 8;
1032         } while (dst_pte++, src_pte++, addr += PAGE_SIZE, addr != end);
1033
1034         arch_leave_lazy_mmu_mode();
1035         spin_unlock(src_ptl);
1036         pte_unmap(orig_src_pte);
1037         add_mm_rss_vec(dst_mm, rss);
1038         pte_unmap_unlock(orig_dst_pte, dst_ptl);
1039         cond_resched();
1040
1041         if (entry.val) {
1042                 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
1043                         ret = -ENOMEM;
1044                         goto out;
1045                 }
1046                 entry.val = 0;
1047         } else if (ret) {
1048                 WARN_ON_ONCE(ret != -EAGAIN);
1049                 prealloc = page_copy_prealloc(src_mm, src_vma, addr);
1050                 if (!prealloc)
1051                         return -ENOMEM;
1052                 /* We've captured and resolved the error. Reset, try again. */
1053                 ret = 0;
1054         }
1055         if (addr != end)
1056                 goto again;
1057 out:
1058         if (unlikely(prealloc))
1059                 put_page(prealloc);
1060         return ret;
1061 }
1062
1063 static inline int
1064 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1065                pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1066                unsigned long end)
1067 {
1068         struct mm_struct *dst_mm = dst_vma->vm_mm;
1069         struct mm_struct *src_mm = src_vma->vm_mm;
1070         pmd_t *src_pmd, *dst_pmd;
1071         unsigned long next;
1072
1073         dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1074         if (!dst_pmd)
1075                 return -ENOMEM;
1076         src_pmd = pmd_offset(src_pud, addr);
1077         do {
1078                 next = pmd_addr_end(addr, end);
1079                 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1080                         || pmd_devmap(*src_pmd)) {
1081                         int err;
1082                         VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
1083                         err = copy_huge_pmd(dst_mm, src_mm,
1084                                             dst_pmd, src_pmd, addr, src_vma);
1085                         if (err == -ENOMEM)
1086                                 return -ENOMEM;
1087                         if (!err)
1088                                 continue;
1089                         /* fall through */
1090                 }
1091                 if (pmd_none_or_clear_bad(src_pmd))
1092                         continue;
1093                 if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
1094                                    addr, next))
1095                         return -ENOMEM;
1096         } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1097         return 0;
1098 }
1099
1100 static inline int
1101 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1102                p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
1103                unsigned long end)
1104 {
1105         struct mm_struct *dst_mm = dst_vma->vm_mm;
1106         struct mm_struct *src_mm = src_vma->vm_mm;
1107         pud_t *src_pud, *dst_pud;
1108         unsigned long next;
1109
1110         dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1111         if (!dst_pud)
1112                 return -ENOMEM;
1113         src_pud = pud_offset(src_p4d, addr);
1114         do {
1115                 next = pud_addr_end(addr, end);
1116                 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1117                         int err;
1118
1119                         VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
1120                         err = copy_huge_pud(dst_mm, src_mm,
1121                                             dst_pud, src_pud, addr, src_vma);
1122                         if (err == -ENOMEM)
1123                                 return -ENOMEM;
1124                         if (!err)
1125                                 continue;
1126                         /* fall through */
1127                 }
1128                 if (pud_none_or_clear_bad(src_pud))
1129                         continue;
1130                 if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
1131                                    addr, next))
1132                         return -ENOMEM;
1133         } while (dst_pud++, src_pud++, addr = next, addr != end);
1134         return 0;
1135 }
1136
1137 static inline int
1138 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1139                pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
1140                unsigned long end)
1141 {
1142         struct mm_struct *dst_mm = dst_vma->vm_mm;
1143         p4d_t *src_p4d, *dst_p4d;
1144         unsigned long next;
1145
1146         dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1147         if (!dst_p4d)
1148                 return -ENOMEM;
1149         src_p4d = p4d_offset(src_pgd, addr);
1150         do {
1151                 next = p4d_addr_end(addr, end);
1152                 if (p4d_none_or_clear_bad(src_p4d))
1153                         continue;
1154                 if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
1155                                    addr, next))
1156                         return -ENOMEM;
1157         } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1158         return 0;
1159 }
1160
1161 #ifdef CONFIG_FINEGRAINED_THP
1162 bool zap_cont_pte_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
1163                         pmd_t *pmd, pte_t **ptep, unsigned long *addr,
1164                         unsigned long end, struct page *page,
1165                         int *rss, spinlock_t *ptl);
1166 #else /* CONFIG_FINEGRAINED_THP */
1167 bool zap_cont_pte_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
1168                         pmd_t *pmd, pte_t **ptep, unsigned long *addr,
1169                         unsigned long end, struct page *page,
1170                         int *rss, spinlock_t *ptl)
1171 {
1172         return false;
1173 }
1174 #endif /* CONFIG_FINEGRAINED_THP */
1175
1176 int
1177 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1178 {
1179         pgd_t *src_pgd, *dst_pgd;
1180         unsigned long next;
1181         unsigned long addr = src_vma->vm_start;
1182         unsigned long end = src_vma->vm_end;
1183         struct mm_struct *dst_mm = dst_vma->vm_mm;
1184         struct mm_struct *src_mm = src_vma->vm_mm;
1185         struct mmu_notifier_range range;
1186         bool is_cow;
1187         int ret;
1188
1189         /*
1190          * Don't copy ptes where a page fault will fill them correctly.
1191          * Fork becomes much lighter when there are big shared or private
1192          * readonly mappings. The tradeoff is that copy_page_range is more
1193          * efficient than faulting.
1194          */
1195         if (!(src_vma->vm_flags & (VM_HUGETLB | VM_PFNMAP | VM_MIXEDMAP)) &&
1196             !src_vma->anon_vma)
1197                 return 0;
1198
1199         if (is_vm_hugetlb_page(src_vma))
1200                 return copy_hugetlb_page_range(dst_mm, src_mm, src_vma);
1201
1202         if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
1203                 /*
1204                  * We do not free on error cases below as remove_vma
1205                  * gets called on error from higher level routine
1206                  */
1207                 ret = track_pfn_copy(src_vma);
1208                 if (ret)
1209                         return ret;
1210         }
1211
1212         /*
1213          * We need to invalidate the secondary MMU mappings only when
1214          * there could be a permission downgrade on the ptes of the
1215          * parent mm. And a permission downgrade will only happen if
1216          * is_cow_mapping() returns true.
1217          */
1218         is_cow = is_cow_mapping(src_vma->vm_flags);
1219
1220         if (is_cow) {
1221                 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
1222                                         0, src_vma, src_mm, addr, end);
1223                 mmu_notifier_invalidate_range_start(&range);
1224                 /*
1225                  * Disabling preemption is not needed for the write side, as
1226                  * the read side doesn't spin, but goes to the mmap_lock.
1227                  *
1228                  * Use the raw variant of the seqcount_t write API to avoid
1229                  * lockdep complaining about preemptibility.
1230                  */
1231                 mmap_assert_write_locked(src_mm);
1232                 raw_write_seqcount_begin(&src_mm->write_protect_seq);
1233         }
1234
1235         ret = 0;
1236         dst_pgd = pgd_offset(dst_mm, addr);
1237         src_pgd = pgd_offset(src_mm, addr);
1238         do {
1239                 next = pgd_addr_end(addr, end);
1240                 if (pgd_none_or_clear_bad(src_pgd))
1241                         continue;
1242                 if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
1243                                             addr, next))) {
1244                         ret = -ENOMEM;
1245                         break;
1246                 }
1247         } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1248
1249         if (is_cow) {
1250                 raw_write_seqcount_end(&src_mm->write_protect_seq);
1251                 mmu_notifier_invalidate_range_end(&range);
1252         }
1253         return ret;
1254 }
1255
1256 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1257                                 struct vm_area_struct *vma, pmd_t *pmd,
1258                                 unsigned long addr, unsigned long end,
1259                                 struct zap_details *details)
1260 {
1261         struct mm_struct *mm = tlb->mm;
1262         int force_flush = 0;
1263         int rss[NR_MM_COUNTERS];
1264         spinlock_t *ptl;
1265         pte_t *start_pte;
1266         pte_t *pte;
1267         swp_entry_t entry;
1268
1269         tlb_change_page_size(tlb, PAGE_SIZE);
1270 again:
1271         init_rss_vec(rss);
1272         start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1273         pte = start_pte;
1274         flush_tlb_batched_pending(mm);
1275         arch_enter_lazy_mmu_mode();
1276         do {
1277                 pte_t ptent = *pte;
1278                 if (pte_none(ptent))
1279                         continue;
1280
1281                 if (need_resched())
1282                         break;
1283
1284                 if (pte_present(ptent)) {
1285                         struct page *page;
1286
1287                         page = vm_normal_page(vma, addr, ptent);
1288                         if (unlikely(details) && page) {
1289                                 /*
1290                                  * unmap_shared_mapping_pages() wants to
1291                                  * invalidate cache without truncating:
1292                                  * unmap shared but keep private pages.
1293                                  */
1294                                 if (details->check_mapping &&
1295                                     details->check_mapping != page_rmapping(page))
1296                                         continue;
1297                         }
1298 #ifdef CONFIG_FINEGRAINED_THP
1299                         if (page && pte_cont(ptent) && PageTransHuge(compound_head(page))) {
1300                                 if (zap_cont_pte_range(tlb, vma, pmd, &pte,
1301                                                 &addr, end, page, rss, ptl)) {
1302                                         force_flush = 1;
1303                                         break;
1304                                 }
1305                         } else if (pte_cont(ptent))
1306                                 atomic_long_dec(&nr_phys_cont_pte_pages);
1307 #endif /* CONFIG_FINEGRAINED_THP */
1308                         ptent = ptep_get_and_clear_full(mm, addr, pte,
1309                                                         tlb->fullmm);
1310                         tlb_remove_tlb_entry(tlb, pte, addr);
1311                         if (unlikely(!page))
1312                                 continue;
1313
1314                         if (!PageAnon(page)) {
1315                                 if (pte_dirty(ptent)) {
1316                                         force_flush = 1;
1317                                         set_page_dirty(page);
1318                                 }
1319                                 if (pte_young(ptent) &&
1320                                     likely(!(vma->vm_flags & VM_SEQ_READ)))
1321                                         mark_page_accessed(page);
1322                         }
1323                         rss[mm_counter(page)]--;
1324                         page_remove_rmap(page, false);
1325                         if (unlikely(page_mapcount(page) < 0))
1326                                 print_bad_pte(vma, addr, ptent, page);
1327                         if (unlikely(__tlb_remove_page(tlb, page))) {
1328                                 force_flush = 1;
1329                                 addr += PAGE_SIZE;
1330                                 break;
1331                         }
1332                         continue;
1333                 }
1334
1335                 entry = pte_to_swp_entry(ptent);
1336                 if (is_device_private_entry(entry)) {
1337                         struct page *page = device_private_entry_to_page(entry);
1338
1339                         if (unlikely(details && details->check_mapping)) {
1340                                 /*
1341                                  * unmap_shared_mapping_pages() wants to
1342                                  * invalidate cache without truncating:
1343                                  * unmap shared but keep private pages.
1344                                  */
1345                                 if (details->check_mapping !=
1346                                     page_rmapping(page))
1347                                         continue;
1348                         }
1349
1350                         pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1351                         rss[mm_counter(page)]--;
1352                         page_remove_rmap(page, false);
1353                         put_page(page);
1354                         continue;
1355                 }
1356
1357                 /* If details->check_mapping, we leave swap entries. */
1358                 if (unlikely(details))
1359                         continue;
1360
1361                 if (!non_swap_entry(entry))
1362                         rss[MM_SWAPENTS]--;
1363                 else if (is_migration_entry(entry)) {
1364                         struct page *page;
1365
1366                         page = migration_entry_to_page(entry);
1367                         rss[mm_counter(page)]--;
1368                 }
1369                 if (unlikely(!free_swap_and_cache(entry)))
1370                         print_bad_pte(vma, addr, ptent, NULL);
1371                 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1372         } while (pte++, addr += PAGE_SIZE, addr != end);
1373
1374         add_mm_rss_vec(mm, rss);
1375         arch_leave_lazy_mmu_mode();
1376
1377         /* Do the actual TLB flush before dropping ptl */
1378         if (force_flush)
1379                 tlb_flush_mmu_tlbonly(tlb);
1380         pte_unmap_unlock(start_pte, ptl);
1381
1382         /*
1383          * If we forced a TLB flush (either due to running out of
1384          * batch buffers or because we needed to flush dirty TLB
1385          * entries before releasing the ptl), free the batched
1386          * memory too. Restart if we didn't do everything.
1387          */
1388         if (force_flush) {
1389                 force_flush = 0;
1390                 tlb_flush_mmu(tlb);
1391         }
1392
1393         if (addr != end) {
1394                 cond_resched();
1395                 goto again;
1396         }
1397
1398         return addr;
1399 }
1400
1401 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1402                                 struct vm_area_struct *vma, pud_t *pud,
1403                                 unsigned long addr, unsigned long end,
1404                                 struct zap_details *details)
1405 {
1406         pmd_t *pmd;
1407         unsigned long next;
1408
1409         pmd = pmd_offset(pud, addr);
1410         do {
1411                 next = pmd_addr_end(addr, end);
1412                 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1413                         if (next - addr != HPAGE_PMD_SIZE)
1414                                 __split_huge_pmd(vma, pmd, addr, false, NULL);
1415                         else if (zap_huge_pmd(tlb, vma, pmd, addr))
1416                                 goto next;
1417                         /* fall through */
1418                 }
1419                 /*
1420                  * Here there can be other concurrent MADV_DONTNEED or
1421                  * trans huge page faults running, and if the pmd is
1422                  * none or trans huge it can change under us. This is
1423                  * because MADV_DONTNEED holds the mmap_lock in read
1424                  * mode.
1425                  */
1426                 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1427                         goto next;
1428                 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1429 next:
1430                 cond_resched();
1431         } while (pmd++, addr = next, addr != end);
1432
1433         return addr;
1434 }
1435
1436 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1437                                 struct vm_area_struct *vma, p4d_t *p4d,
1438                                 unsigned long addr, unsigned long end,
1439                                 struct zap_details *details)
1440 {
1441         pud_t *pud;
1442         unsigned long next;
1443
1444         pud = pud_offset(p4d, addr);
1445         do {
1446                 next = pud_addr_end(addr, end);
1447                 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1448                         if (next - addr != HPAGE_PUD_SIZE) {
1449                                 mmap_assert_locked(tlb->mm);
1450                                 split_huge_pud(vma, pud, addr);
1451                         } else if (zap_huge_pud(tlb, vma, pud, addr))
1452                                 goto next;
1453                         /* fall through */
1454                 }
1455                 if (pud_none_or_clear_bad(pud))
1456                         continue;
1457                 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1458 next:
1459                 cond_resched();
1460         } while (pud++, addr = next, addr != end);
1461
1462         return addr;
1463 }
1464
1465 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1466                                 struct vm_area_struct *vma, pgd_t *pgd,
1467                                 unsigned long addr, unsigned long end,
1468                                 struct zap_details *details)
1469 {
1470         p4d_t *p4d;
1471         unsigned long next;
1472
1473         p4d = p4d_offset(pgd, addr);
1474         do {
1475                 next = p4d_addr_end(addr, end);
1476                 if (p4d_none_or_clear_bad(p4d))
1477                         continue;
1478                 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1479         } while (p4d++, addr = next, addr != end);
1480
1481         return addr;
1482 }
1483
1484 void unmap_page_range(struct mmu_gather *tlb,
1485                              struct vm_area_struct *vma,
1486                              unsigned long addr, unsigned long end,
1487                              struct zap_details *details)
1488 {
1489         pgd_t *pgd;
1490         unsigned long next;
1491
1492         BUG_ON(addr >= end);
1493         tlb_start_vma(tlb, vma);
1494         pgd = pgd_offset(vma->vm_mm, addr);
1495         do {
1496                 next = pgd_addr_end(addr, end);
1497                 if (pgd_none_or_clear_bad(pgd))
1498                         continue;
1499                 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1500         } while (pgd++, addr = next, addr != end);
1501         tlb_end_vma(tlb, vma);
1502 }
1503
1504
1505 static void unmap_single_vma(struct mmu_gather *tlb,
1506                 struct vm_area_struct *vma, unsigned long start_addr,
1507                 unsigned long end_addr,
1508                 struct zap_details *details)
1509 {
1510         unsigned long start = max(vma->vm_start, start_addr);
1511         unsigned long end;
1512
1513         if (start >= vma->vm_end)
1514                 return;
1515         end = min(vma->vm_end, end_addr);
1516         if (end <= vma->vm_start)
1517                 return;
1518
1519         if (vma->vm_file)
1520                 uprobe_munmap(vma, start, end);
1521
1522         if (unlikely(vma->vm_flags & VM_PFNMAP))
1523                 untrack_pfn(vma, 0, 0);
1524
1525         if (start != end) {
1526                 if (unlikely(is_vm_hugetlb_page(vma))) {
1527                         /*
1528                          * It is undesirable to test vma->vm_file as it
1529                          * should be non-null for valid hugetlb area.
1530                          * However, vm_file will be NULL in the error
1531                          * cleanup path of mmap_region. When
1532                          * hugetlbfs ->mmap method fails,
1533                          * mmap_region() nullifies vma->vm_file
1534                          * before calling this function to clean up.
1535                          * Since no pte has actually been setup, it is
1536                          * safe to do nothing in this case.
1537                          */
1538                         if (vma->vm_file) {
1539                                 i_mmap_lock_write(vma->vm_file->f_mapping);
1540                                 __unmap_hugepage_range_final(tlb, vma, start, end, NULL);
1541                                 i_mmap_unlock_write(vma->vm_file->f_mapping);
1542                         }
1543                 } else
1544                         unmap_page_range(tlb, vma, start, end, details);
1545         }
1546 }
1547
1548 /**
1549  * unmap_vmas - unmap a range of memory covered by a list of vma's
1550  * @tlb: address of the caller's struct mmu_gather
1551  * @vma: the starting vma
1552  * @start_addr: virtual address at which to start unmapping
1553  * @end_addr: virtual address at which to end unmapping
1554  *
1555  * Unmap all pages in the vma list.
1556  *
1557  * Only addresses between `start' and `end' will be unmapped.
1558  *
1559  * The VMA list must be sorted in ascending virtual address order.
1560  *
1561  * unmap_vmas() assumes that the caller will flush the whole unmapped address
1562  * range after unmap_vmas() returns.  So the only responsibility here is to
1563  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1564  * drops the lock and schedules.
1565  */
1566 void unmap_vmas(struct mmu_gather *tlb,
1567                 struct vm_area_struct *vma, unsigned long start_addr,
1568                 unsigned long end_addr)
1569 {
1570         struct mmu_notifier_range range;
1571
1572         mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
1573                                 start_addr, end_addr);
1574         mmu_notifier_invalidate_range_start(&range);
1575         for ( ; vma && vma->vm_start < end_addr; vma = vma->vm_next)
1576                 unmap_single_vma(tlb, vma, start_addr, end_addr, NULL);
1577         mmu_notifier_invalidate_range_end(&range);
1578 }
1579
1580 /**
1581  * zap_page_range - remove user pages in a given range
1582  * @vma: vm_area_struct holding the applicable pages
1583  * @start: starting address of pages to zap
1584  * @size: number of bytes to zap
1585  *
1586  * Caller must protect the VMA list
1587  */
1588 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1589                 unsigned long size)
1590 {
1591         struct mmu_notifier_range range;
1592         struct mmu_gather tlb;
1593
1594         lru_add_drain();
1595         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1596                                 start, start + size);
1597         tlb_gather_mmu(&tlb, vma->vm_mm, start, range.end);
1598         update_hiwater_rss(vma->vm_mm);
1599         mmu_notifier_invalidate_range_start(&range);
1600         for ( ; vma && vma->vm_start < range.end; vma = vma->vm_next)
1601                 unmap_single_vma(&tlb, vma, start, range.end, NULL);
1602         mmu_notifier_invalidate_range_end(&range);
1603         tlb_finish_mmu(&tlb, start, range.end);
1604 }
1605
1606 /**
1607  * zap_page_range_single - remove user pages in a given range
1608  * @vma: vm_area_struct holding the applicable pages
1609  * @address: starting address of pages to zap
1610  * @size: number of bytes to zap
1611  * @details: details of shared cache invalidation
1612  *
1613  * The range must fit into one VMA.
1614  */
1615 static void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1616                 unsigned long size, struct zap_details *details)
1617 {
1618         struct mmu_notifier_range range;
1619         struct mmu_gather tlb;
1620
1621         lru_add_drain();
1622         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1623                                 address, address + size);
1624         tlb_gather_mmu(&tlb, vma->vm_mm, address, range.end);
1625         update_hiwater_rss(vma->vm_mm);
1626         mmu_notifier_invalidate_range_start(&range);
1627         unmap_single_vma(&tlb, vma, address, range.end, details);
1628         mmu_notifier_invalidate_range_end(&range);
1629         tlb_finish_mmu(&tlb, address, range.end);
1630 }
1631
1632 /**
1633  * zap_vma_ptes - remove ptes mapping the vma
1634  * @vma: vm_area_struct holding ptes to be zapped
1635  * @address: starting address of pages to zap
1636  * @size: number of bytes to zap
1637  *
1638  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1639  *
1640  * The entire address range must be fully contained within the vma.
1641  *
1642  */
1643 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1644                 unsigned long size)
1645 {
1646         if (address < vma->vm_start || address + size > vma->vm_end ||
1647                         !(vma->vm_flags & VM_PFNMAP))
1648                 return;
1649
1650         zap_page_range_single(vma, address, size, NULL);
1651 }
1652 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1653
1654 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
1655 {
1656         pgd_t *pgd;
1657         p4d_t *p4d;
1658         pud_t *pud;
1659         pmd_t *pmd;
1660
1661         pgd = pgd_offset(mm, addr);
1662         p4d = p4d_alloc(mm, pgd, addr);
1663         if (!p4d)
1664                 return NULL;
1665         pud = pud_alloc(mm, p4d, addr);
1666         if (!pud)
1667                 return NULL;
1668         pmd = pmd_alloc(mm, pud, addr);
1669         if (!pmd)
1670                 return NULL;
1671
1672         VM_BUG_ON(pmd_trans_huge(*pmd));
1673         return pmd;
1674 }
1675
1676 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1677                         spinlock_t **ptl)
1678 {
1679         pmd_t *pmd = walk_to_pmd(mm, addr);
1680
1681         if (!pmd)
1682                 return NULL;
1683         return pte_alloc_map_lock(mm, pmd, addr, ptl);
1684 }
1685
1686 static int validate_page_before_insert(struct page *page)
1687 {
1688         if (PageAnon(page) || PageSlab(page) || page_has_type(page))
1689                 return -EINVAL;
1690         flush_dcache_page(page);
1691         return 0;
1692 }
1693
1694 static int insert_page_into_pte_locked(struct mm_struct *mm, pte_t *pte,
1695                         unsigned long addr, struct page *page, pgprot_t prot)
1696 {
1697         if (!pte_none(*pte))
1698                 return -EBUSY;
1699         /* Ok, finally just insert the thing.. */
1700         get_page(page);
1701         inc_mm_counter_fast(mm, mm_counter_file(page));
1702         page_add_file_rmap(page, false);
1703         set_pte_at(mm, addr, pte, mk_pte(page, prot));
1704         return 0;
1705 }
1706
1707 /*
1708  * This is the old fallback for page remapping.
1709  *
1710  * For historical reasons, it only allows reserved pages. Only
1711  * old drivers should use this, and they needed to mark their
1712  * pages reserved for the old functions anyway.
1713  */
1714 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1715                         struct page *page, pgprot_t prot)
1716 {
1717         struct mm_struct *mm = vma->vm_mm;
1718         int retval;
1719         pte_t *pte;
1720         spinlock_t *ptl;
1721
1722         retval = validate_page_before_insert(page);
1723         if (retval)
1724                 goto out;
1725         retval = -ENOMEM;
1726         pte = get_locked_pte(mm, addr, &ptl);
1727         if (!pte)
1728                 goto out;
1729         retval = insert_page_into_pte_locked(mm, pte, addr, page, prot);
1730         pte_unmap_unlock(pte, ptl);
1731 out:
1732         return retval;
1733 }
1734
1735 #ifdef pte_index
1736 static int insert_page_in_batch_locked(struct mm_struct *mm, pte_t *pte,
1737                         unsigned long addr, struct page *page, pgprot_t prot)
1738 {
1739         int err;
1740
1741         if (!page_count(page))
1742                 return -EINVAL;
1743         err = validate_page_before_insert(page);
1744         if (err)
1745                 return err;
1746         return insert_page_into_pte_locked(mm, pte, addr, page, prot);
1747 }
1748
1749 /* insert_pages() amortizes the cost of spinlock operations
1750  * when inserting pages in a loop. Arch *must* define pte_index.
1751  */
1752 static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
1753                         struct page **pages, unsigned long *num, pgprot_t prot)
1754 {
1755         pmd_t *pmd = NULL;
1756         pte_t *start_pte, *pte;
1757         spinlock_t *pte_lock;
1758         struct mm_struct *const mm = vma->vm_mm;
1759         unsigned long curr_page_idx = 0;
1760         unsigned long remaining_pages_total = *num;
1761         unsigned long pages_to_write_in_pmd;
1762         int ret;
1763 more:
1764         ret = -EFAULT;
1765         pmd = walk_to_pmd(mm, addr);
1766         if (!pmd)
1767                 goto out;
1768
1769         pages_to_write_in_pmd = min_t(unsigned long,
1770                 remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
1771
1772         /* Allocate the PTE if necessary; takes PMD lock once only. */
1773         ret = -ENOMEM;
1774         if (pte_alloc(mm, pmd))
1775                 goto out;
1776
1777         while (pages_to_write_in_pmd) {
1778                 int pte_idx = 0;
1779                 const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
1780
1781                 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
1782                 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
1783                         int err = insert_page_in_batch_locked(mm, pte,
1784                                 addr, pages[curr_page_idx], prot);
1785                         if (unlikely(err)) {
1786                                 pte_unmap_unlock(start_pte, pte_lock);
1787                                 ret = err;
1788                                 remaining_pages_total -= pte_idx;
1789                                 goto out;
1790                         }
1791                         addr += PAGE_SIZE;
1792                         ++curr_page_idx;
1793                 }
1794                 pte_unmap_unlock(start_pte, pte_lock);
1795                 pages_to_write_in_pmd -= batch_size;
1796                 remaining_pages_total -= batch_size;
1797         }
1798         if (remaining_pages_total)
1799                 goto more;
1800         ret = 0;
1801 out:
1802         *num = remaining_pages_total;
1803         return ret;
1804 }
1805 #endif  /* ifdef pte_index */
1806
1807 /**
1808  * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
1809  * @vma: user vma to map to
1810  * @addr: target start user address of these pages
1811  * @pages: source kernel pages
1812  * @num: in: number of pages to map. out: number of pages that were *not*
1813  * mapped. (0 means all pages were successfully mapped).
1814  *
1815  * Preferred over vm_insert_page() when inserting multiple pages.
1816  *
1817  * In case of error, we may have mapped a subset of the provided
1818  * pages. It is the caller's responsibility to account for this case.
1819  *
1820  * The same restrictions apply as in vm_insert_page().
1821  */
1822 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
1823                         struct page **pages, unsigned long *num)
1824 {
1825 #ifdef pte_index
1826         const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
1827
1828         if (addr < vma->vm_start || end_addr >= vma->vm_end)
1829                 return -EFAULT;
1830         if (!(vma->vm_flags & VM_MIXEDMAP)) {
1831                 BUG_ON(mmap_read_trylock(vma->vm_mm));
1832                 BUG_ON(vma->vm_flags & VM_PFNMAP);
1833                 vma->vm_flags |= VM_MIXEDMAP;
1834         }
1835         /* Defer page refcount checking till we're about to map that page. */
1836         return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
1837 #else
1838         unsigned long idx = 0, pgcount = *num;
1839         int err = -EINVAL;
1840
1841         for (; idx < pgcount; ++idx) {
1842                 err = vm_insert_page(vma, addr + (PAGE_SIZE * idx), pages[idx]);
1843                 if (err)
1844                         break;
1845         }
1846         *num = pgcount - idx;
1847         return err;
1848 #endif  /* ifdef pte_index */
1849 }
1850 EXPORT_SYMBOL(vm_insert_pages);
1851
1852 /**
1853  * vm_insert_page - insert single page into user vma
1854  * @vma: user vma to map to
1855  * @addr: target user address of this page
1856  * @page: source kernel page
1857  *
1858  * This allows drivers to insert individual pages they've allocated
1859  * into a user vma.
1860  *
1861  * The page has to be a nice clean _individual_ kernel allocation.
1862  * If you allocate a compound page, you need to have marked it as
1863  * such (__GFP_COMP), or manually just split the page up yourself
1864  * (see split_page()).
1865  *
1866  * NOTE! Traditionally this was done with "remap_pfn_range()" which
1867  * took an arbitrary page protection parameter. This doesn't allow
1868  * that. Your vma protection will have to be set up correctly, which
1869  * means that if you want a shared writable mapping, you'd better
1870  * ask for a shared writable mapping!
1871  *
1872  * The page does not need to be reserved.
1873  *
1874  * Usually this function is called from f_op->mmap() handler
1875  * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
1876  * Caller must set VM_MIXEDMAP on vma if it wants to call this
1877  * function from other places, for example from page-fault handler.
1878  *
1879  * Return: %0 on success, negative error code otherwise.
1880  */
1881 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
1882                         struct page *page)
1883 {
1884         if (addr < vma->vm_start || addr >= vma->vm_end)
1885                 return -EFAULT;
1886         if (!page_count(page))
1887                 return -EINVAL;
1888         if (!(vma->vm_flags & VM_MIXEDMAP)) {
1889                 BUG_ON(mmap_read_trylock(vma->vm_mm));
1890                 BUG_ON(vma->vm_flags & VM_PFNMAP);
1891                 vma->vm_flags |= VM_MIXEDMAP;
1892         }
1893         return insert_page(vma, addr, page, vma->vm_page_prot);
1894 }
1895 EXPORT_SYMBOL(vm_insert_page);
1896
1897 /*
1898  * __vm_map_pages - maps range of kernel pages into user vma
1899  * @vma: user vma to map to
1900  * @pages: pointer to array of source kernel pages
1901  * @num: number of pages in page array
1902  * @offset: user's requested vm_pgoff
1903  *
1904  * This allows drivers to map range of kernel pages into a user vma.
1905  *
1906  * Return: 0 on success and error code otherwise.
1907  */
1908 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
1909                                 unsigned long num, unsigned long offset)
1910 {
1911         unsigned long count = vma_pages(vma);
1912         unsigned long uaddr = vma->vm_start;
1913         int ret, i;
1914
1915         /* Fail if the user requested offset is beyond the end of the object */
1916         if (offset >= num)
1917                 return -ENXIO;
1918
1919         /* Fail if the user requested size exceeds available object size */
1920         if (count > num - offset)
1921                 return -ENXIO;
1922
1923         for (i = 0; i < count; i++) {
1924                 ret = vm_insert_page(vma, uaddr, pages[offset + i]);
1925                 if (ret < 0)
1926                         return ret;
1927                 uaddr += PAGE_SIZE;
1928         }
1929
1930         return 0;
1931 }
1932
1933 /**
1934  * vm_map_pages - maps range of kernel pages starts with non zero offset
1935  * @vma: user vma to map to
1936  * @pages: pointer to array of source kernel pages
1937  * @num: number of pages in page array
1938  *
1939  * Maps an object consisting of @num pages, catering for the user's
1940  * requested vm_pgoff
1941  *
1942  * If we fail to insert any page into the vma, the function will return
1943  * immediately leaving any previously inserted pages present.  Callers
1944  * from the mmap handler may immediately return the error as their caller
1945  * will destroy the vma, removing any successfully inserted pages. Other
1946  * callers should make their own arrangements for calling unmap_region().
1947  *
1948  * Context: Process context. Called by mmap handlers.
1949  * Return: 0 on success and error code otherwise.
1950  */
1951 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
1952                                 unsigned long num)
1953 {
1954         return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
1955 }
1956 EXPORT_SYMBOL(vm_map_pages);
1957
1958 /**
1959  * vm_map_pages_zero - map range of kernel pages starts with zero offset
1960  * @vma: user vma to map to
1961  * @pages: pointer to array of source kernel pages
1962  * @num: number of pages in page array
1963  *
1964  * Similar to vm_map_pages(), except that it explicitly sets the offset
1965  * to 0. This function is intended for the drivers that did not consider
1966  * vm_pgoff.
1967  *
1968  * Context: Process context. Called by mmap handlers.
1969  * Return: 0 on success and error code otherwise.
1970  */
1971 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
1972                                 unsigned long num)
1973 {
1974         return __vm_map_pages(vma, pages, num, 0);
1975 }
1976 EXPORT_SYMBOL(vm_map_pages_zero);
1977
1978 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
1979                         pfn_t pfn, pgprot_t prot, bool mkwrite)
1980 {
1981         struct mm_struct *mm = vma->vm_mm;
1982         pte_t *pte, entry;
1983         spinlock_t *ptl;
1984
1985         pte = get_locked_pte(mm, addr, &ptl);
1986         if (!pte)
1987                 return VM_FAULT_OOM;
1988         if (!pte_none(*pte)) {
1989                 if (mkwrite) {
1990                         /*
1991                          * For read faults on private mappings the PFN passed
1992                          * in may not match the PFN we have mapped if the
1993                          * mapped PFN is a writeable COW page.  In the mkwrite
1994                          * case we are creating a writable PTE for a shared
1995                          * mapping and we expect the PFNs to match. If they
1996                          * don't match, we are likely racing with block
1997                          * allocation and mapping invalidation so just skip the
1998                          * update.
1999                          */
2000                         if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
2001                                 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
2002                                 goto out_unlock;
2003                         }
2004                         entry = pte_mkyoung(*pte);
2005                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2006                         if (ptep_set_access_flags(vma, addr, pte, entry, 1))
2007                                 update_mmu_cache(vma, addr, pte);
2008                 }
2009                 goto out_unlock;
2010         }
2011
2012         /* Ok, finally just insert the thing.. */
2013         if (pfn_t_devmap(pfn))
2014                 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
2015         else
2016                 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
2017
2018         if (mkwrite) {
2019                 entry = pte_mkyoung(entry);
2020                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2021         }
2022
2023         set_pte_at(mm, addr, pte, entry);
2024         update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2025
2026 out_unlock:
2027         pte_unmap_unlock(pte, ptl);
2028         return VM_FAULT_NOPAGE;
2029 }
2030
2031 /**
2032  * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
2033  * @vma: user vma to map to
2034  * @addr: target user address of this page
2035  * @pfn: source kernel pfn
2036  * @pgprot: pgprot flags for the inserted page
2037  *
2038  * This is exactly like vmf_insert_pfn(), except that it allows drivers
2039  * to override pgprot on a per-page basis.
2040  *
2041  * This only makes sense for IO mappings, and it makes no sense for
2042  * COW mappings.  In general, using multiple vmas is preferable;
2043  * vmf_insert_pfn_prot should only be used if using multiple VMAs is
2044  * impractical.
2045  *
2046  * See vmf_insert_mixed_prot() for a discussion of the implication of using
2047  * a value of @pgprot different from that of @vma->vm_page_prot.
2048  *
2049  * Context: Process context.  May allocate using %GFP_KERNEL.
2050  * Return: vm_fault_t value.
2051  */
2052 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
2053                         unsigned long pfn, pgprot_t pgprot)
2054 {
2055         /*
2056          * Technically, architectures with pte_special can avoid all these
2057          * restrictions (same for remap_pfn_range).  However we would like
2058          * consistency in testing and feature parity among all, so we should
2059          * try to keep these invariants in place for everybody.
2060          */
2061         BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2062         BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2063                                                 (VM_PFNMAP|VM_MIXEDMAP));
2064         BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2065         BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2066
2067         if (addr < vma->vm_start || addr >= vma->vm_end)
2068                 return VM_FAULT_SIGBUS;
2069
2070         if (!pfn_modify_allowed(pfn, pgprot))
2071                 return VM_FAULT_SIGBUS;
2072
2073         track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
2074
2075         return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
2076                         false);
2077 }
2078 EXPORT_SYMBOL(vmf_insert_pfn_prot);
2079
2080 /**
2081  * vmf_insert_pfn - insert single pfn into user vma
2082  * @vma: user vma to map to
2083  * @addr: target user address of this page
2084  * @pfn: source kernel pfn
2085  *
2086  * Similar to vm_insert_page, this allows drivers to insert individual pages
2087  * they've allocated into a user vma. Same comments apply.
2088  *
2089  * This function should only be called from a vm_ops->fault handler, and
2090  * in that case the handler should return the result of this function.
2091  *
2092  * vma cannot be a COW mapping.
2093  *
2094  * As this is called only for pages that do not currently exist, we
2095  * do not need to flush old virtual caches or the TLB.
2096  *
2097  * Context: Process context.  May allocate using %GFP_KERNEL.
2098  * Return: vm_fault_t value.
2099  */
2100 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2101                         unsigned long pfn)
2102 {
2103         return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
2104 }
2105 EXPORT_SYMBOL(vmf_insert_pfn);
2106
2107 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn)
2108 {
2109         /* these checks mirror the abort conditions in vm_normal_page */
2110         if (vma->vm_flags & VM_MIXEDMAP)
2111                 return true;
2112         if (pfn_t_devmap(pfn))
2113                 return true;
2114         if (pfn_t_special(pfn))
2115                 return true;
2116         if (is_zero_pfn(pfn_t_to_pfn(pfn)))
2117                 return true;
2118         return false;
2119 }
2120
2121 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
2122                 unsigned long addr, pfn_t pfn, pgprot_t pgprot,
2123                 bool mkwrite)
2124 {
2125         int err;
2126
2127         BUG_ON(!vm_mixed_ok(vma, pfn));
2128
2129         if (addr < vma->vm_start || addr >= vma->vm_end)
2130                 return VM_FAULT_SIGBUS;
2131
2132         track_pfn_insert(vma, &pgprot, pfn);
2133
2134         if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
2135                 return VM_FAULT_SIGBUS;
2136
2137         /*
2138          * If we don't have pte special, then we have to use the pfn_valid()
2139          * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2140          * refcount the page if pfn_valid is true (hence insert_page rather
2141          * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
2142          * without pte special, it would there be refcounted as a normal page.
2143          */
2144         if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
2145             !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
2146                 struct page *page;
2147
2148                 /*
2149                  * At this point we are committed to insert_page()
2150                  * regardless of whether the caller specified flags that
2151                  * result in pfn_t_has_page() == false.
2152                  */
2153                 page = pfn_to_page(pfn_t_to_pfn(pfn));
2154                 err = insert_page(vma, addr, page, pgprot);
2155         } else {
2156                 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2157         }
2158
2159         if (err == -ENOMEM)
2160                 return VM_FAULT_OOM;
2161         if (err < 0 && err != -EBUSY)
2162                 return VM_FAULT_SIGBUS;
2163
2164         return VM_FAULT_NOPAGE;
2165 }
2166
2167 /**
2168  * vmf_insert_mixed_prot - insert single pfn into user vma with specified pgprot
2169  * @vma: user vma to map to
2170  * @addr: target user address of this page
2171  * @pfn: source kernel pfn
2172  * @pgprot: pgprot flags for the inserted page
2173  *
2174  * This is exactly like vmf_insert_mixed(), except that it allows drivers
2175  * to override pgprot on a per-page basis.
2176  *
2177  * Typically this function should be used by drivers to set caching- and
2178  * encryption bits different than those of @vma->vm_page_prot, because
2179  * the caching- or encryption mode may not be known at mmap() time.
2180  * This is ok as long as @vma->vm_page_prot is not used by the core vm
2181  * to set caching and encryption bits for those vmas (except for COW pages).
2182  * This is ensured by core vm only modifying these page table entries using
2183  * functions that don't touch caching- or encryption bits, using pte_modify()
2184  * if needed. (See for example mprotect()).
2185  * Also when new page-table entries are created, this is only done using the
2186  * fault() callback, and never using the value of vma->vm_page_prot,
2187  * except for page-table entries that point to anonymous pages as the result
2188  * of COW.
2189  *
2190  * Context: Process context.  May allocate using %GFP_KERNEL.
2191  * Return: vm_fault_t value.
2192  */
2193 vm_fault_t vmf_insert_mixed_prot(struct vm_area_struct *vma, unsigned long addr,
2194                                  pfn_t pfn, pgprot_t pgprot)
2195 {
2196         return __vm_insert_mixed(vma, addr, pfn, pgprot, false);
2197 }
2198 EXPORT_SYMBOL(vmf_insert_mixed_prot);
2199
2200 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2201                 pfn_t pfn)
2202 {
2203         return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, false);
2204 }
2205 EXPORT_SYMBOL(vmf_insert_mixed);
2206
2207 /*
2208  *  If the insertion of PTE failed because someone else already added a
2209  *  different entry in the mean time, we treat that as success as we assume
2210  *  the same entry was actually inserted.
2211  */
2212 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2213                 unsigned long addr, pfn_t pfn)
2214 {
2215         return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, true);
2216 }
2217 EXPORT_SYMBOL(vmf_insert_mixed_mkwrite);
2218
2219
2220 /*
2221  * maps a range of physical memory into the requested pages. the old
2222  * mappings are removed. any references to nonexistent pages results
2223  * in null mappings (currently treated as "copy-on-access")
2224  */
2225 #ifdef CONFIG_FINEGRAINED_THP
2226 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2227                         unsigned long addr, unsigned long end,
2228                         unsigned long pfn, pgprot_t prot)
2229 {
2230         return arch_remap_pte_range(mm, pmd, addr, end, pfn, prot);
2231 }
2232 #else /* CONFIG_FINEGRAINED_THP */
2233 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2234                         unsigned long addr, unsigned long end,
2235                         unsigned long pfn, pgprot_t prot)
2236 {
2237         pte_t *pte, *mapped_pte;
2238         spinlock_t *ptl;
2239         int err = 0;
2240
2241         mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2242         if (!pte)
2243                 return -ENOMEM;
2244         arch_enter_lazy_mmu_mode();
2245         do {
2246                 BUG_ON(!pte_none(*pte));
2247                 if (!pfn_modify_allowed(pfn, prot)) {
2248                         err = -EACCES;
2249                         break;
2250                 }
2251
2252                 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2253                 pfn++;
2254                 pte++;
2255                 addr += PAGE_SIZE;
2256         } while (addr != end);
2257         arch_leave_lazy_mmu_mode();
2258         pte_unmap_unlock(mapped_pte, ptl);
2259         return err;
2260 }
2261 #endif /* CONFIG_FINEGRAINED_THP */
2262
2263 static int remap_try_huge_pmd(struct mm_struct *mm, pmd_t *pmd, unsigned long addr,
2264                                 unsigned long end, unsigned long pfn,
2265                                 pgprot_t prot)
2266 {
2267         phys_addr_t phys_addr = __pfn_to_phys(pfn);
2268         spinlock_t *ptl;
2269         int ret;
2270
2271         if ((end - addr) != PMD_SIZE)
2272                 return 0;
2273
2274         if (!IS_ALIGNED(addr, PMD_SIZE))
2275                 return 0;
2276
2277         if (!IS_ALIGNED(phys_addr, PMD_SIZE))
2278                 return 0;
2279
2280         /* fixme - is this correct? */
2281         if (pmd_present(*pmd) && !pmd_free_pte_page(pmd, addr)) {
2282                 pr_info("%s %d - freed pmd page??\n", __func__, __LINE__);
2283                 return 0;
2284         }
2285
2286         ptl = pmd_lock(mm, pmd);
2287         ret = pmd_set_huge(pmd, phys_addr, prot);
2288         spin_unlock(ptl);
2289
2290         atomic_long_inc(&nr_phys_huge_pmd_pages);
2291
2292         return ret;
2293 }
2294
2295 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2296                         unsigned long addr, unsigned long end,
2297                         unsigned long pfn, pgprot_t prot)
2298 {
2299         pmd_t *pmd;
2300         unsigned long next;
2301         int err;
2302
2303         pfn -= addr >> PAGE_SHIFT;
2304         pmd = pmd_alloc(mm, pud, addr);
2305         if (!pmd)
2306                 return -ENOMEM;
2307         VM_BUG_ON(pmd_trans_huge(*pmd));
2308         do {
2309                 next = pmd_addr_end(addr, end);
2310
2311                 if (remap_try_huge_pmd(mm, pmd, addr, next,
2312                                        pfn + (addr >> PAGE_SHIFT), prot))
2313                         continue;
2314
2315                 err = remap_pte_range(mm, pmd, addr, next,
2316                                 pfn + (addr >> PAGE_SHIFT), prot);
2317                 if (err)
2318                         return err;
2319         } while (pmd++, addr = next, addr != end);
2320         return 0;
2321 }
2322
2323 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2324                         unsigned long addr, unsigned long end,
2325                         unsigned long pfn, pgprot_t prot)
2326 {
2327         pud_t *pud;
2328         unsigned long next;
2329         int err;
2330
2331         pfn -= addr >> PAGE_SHIFT;
2332         pud = pud_alloc(mm, p4d, addr);
2333         if (!pud)
2334                 return -ENOMEM;
2335         do {
2336                 next = pud_addr_end(addr, end);
2337                 err = remap_pmd_range(mm, pud, addr, next,
2338                                 pfn + (addr >> PAGE_SHIFT), prot);
2339                 if (err)
2340                         return err;
2341         } while (pud++, addr = next, addr != end);
2342         return 0;
2343 }
2344
2345 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2346                         unsigned long addr, unsigned long end,
2347                         unsigned long pfn, pgprot_t prot)
2348 {
2349         p4d_t *p4d;
2350         unsigned long next;
2351         int err;
2352
2353         pfn -= addr >> PAGE_SHIFT;
2354         p4d = p4d_alloc(mm, pgd, addr);
2355         if (!p4d)
2356                 return -ENOMEM;
2357         do {
2358                 next = p4d_addr_end(addr, end);
2359                 err = remap_pud_range(mm, p4d, addr, next,
2360                                 pfn + (addr >> PAGE_SHIFT), prot);
2361                 if (err)
2362                         return err;
2363         } while (p4d++, addr = next, addr != end);
2364         return 0;
2365 }
2366
2367 /**
2368  * remap_pfn_range - remap kernel memory to userspace
2369  * @vma: user vma to map to
2370  * @addr: target page aligned user address to start at
2371  * @pfn: page frame number of kernel physical memory address
2372  * @size: size of mapping area
2373  * @prot: page protection flags for this mapping
2374  *
2375  * Note: this is only safe if the mm semaphore is held when called.
2376  *
2377  * Return: %0 on success, negative error code otherwise.
2378  */
2379 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2380                     unsigned long pfn, unsigned long size, pgprot_t prot)
2381 {
2382         pgd_t *pgd;
2383         unsigned long next;
2384         unsigned long end = addr + PAGE_ALIGN(size);
2385         struct mm_struct *mm = vma->vm_mm;
2386         unsigned long remap_pfn = pfn;
2387         int err;
2388
2389         if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
2390                 return -EINVAL;
2391
2392         /*
2393          * Physically remapped pages are special. Tell the
2394          * rest of the world about it:
2395          *   VM_IO tells people not to look at these pages
2396          *      (accesses can have side effects).
2397          *   VM_PFNMAP tells the core MM that the base pages are just
2398          *      raw PFN mappings, and do not have a "struct page" associated
2399          *      with them.
2400          *   VM_DONTEXPAND
2401          *      Disable vma merging and expanding with mremap().
2402          *   VM_DONTDUMP
2403          *      Omit vma from core dump, even when VM_IO turned off.
2404          *
2405          * There's a horrible special case to handle copy-on-write
2406          * behaviour that some programs depend on. We mark the "original"
2407          * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2408          * See vm_normal_page() for details.
2409          */
2410         if (is_cow_mapping(vma->vm_flags)) {
2411                 if (addr != vma->vm_start || end != vma->vm_end)
2412                         return -EINVAL;
2413                 vma->vm_pgoff = pfn;
2414         }
2415
2416         err = track_pfn_remap(vma, &prot, remap_pfn, addr, PAGE_ALIGN(size));
2417         if (err)
2418                 return -EINVAL;
2419
2420         vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2421
2422         BUG_ON(addr >= end);
2423         pfn -= addr >> PAGE_SHIFT;
2424         pgd = pgd_offset(mm, addr);
2425         flush_cache_range(vma, addr, end);
2426         do {
2427                 next = pgd_addr_end(addr, end);
2428                 err = remap_p4d_range(mm, pgd, addr, next,
2429                                 pfn + (addr >> PAGE_SHIFT), prot);
2430                 if (err)
2431                         break;
2432         } while (pgd++, addr = next, addr != end);
2433
2434         if (err)
2435                 untrack_pfn(vma, remap_pfn, PAGE_ALIGN(size));
2436
2437         return err;
2438 }
2439 EXPORT_SYMBOL(remap_pfn_range);
2440
2441 /**
2442  * vm_iomap_memory - remap memory to userspace
2443  * @vma: user vma to map to
2444  * @start: start of the physical memory to be mapped
2445  * @len: size of area
2446  *
2447  * This is a simplified io_remap_pfn_range() for common driver use. The
2448  * driver just needs to give us the physical memory range to be mapped,
2449  * we'll figure out the rest from the vma information.
2450  *
2451  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2452  * whatever write-combining details or similar.
2453  *
2454  * Return: %0 on success, negative error code otherwise.
2455  */
2456 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2457 {
2458         unsigned long vm_len, pfn, pages;
2459
2460         /* Check that the physical memory area passed in looks valid */
2461         if (start + len < start)
2462                 return -EINVAL;
2463         /*
2464          * You *really* shouldn't map things that aren't page-aligned,
2465          * but we've historically allowed it because IO memory might
2466          * just have smaller alignment.
2467          */
2468         len += start & ~PAGE_MASK;
2469         pfn = start >> PAGE_SHIFT;
2470         pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2471         if (pfn + pages < pfn)
2472                 return -EINVAL;
2473
2474         /* We start the mapping 'vm_pgoff' pages into the area */
2475         if (vma->vm_pgoff > pages)
2476                 return -EINVAL;
2477         pfn += vma->vm_pgoff;
2478         pages -= vma->vm_pgoff;
2479
2480         /* Can we fit all of the mapping? */
2481         vm_len = vma->vm_end - vma->vm_start;
2482         if (vm_len >> PAGE_SHIFT > pages)
2483                 return -EINVAL;
2484
2485         /* Ok, let it rip */
2486         return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2487 }
2488 EXPORT_SYMBOL(vm_iomap_memory);
2489
2490 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2491                                      unsigned long addr, unsigned long end,
2492                                      pte_fn_t fn, void *data, bool create,
2493                                      pgtbl_mod_mask *mask)
2494 {
2495         pte_t *pte;
2496         int err = 0;
2497         spinlock_t *ptl;
2498
2499         if (create) {
2500                 pte = (mm == &init_mm) ?
2501                         pte_alloc_kernel_track(pmd, addr, mask) :
2502                         pte_alloc_map_lock(mm, pmd, addr, &ptl);
2503                 if (!pte)
2504                         return -ENOMEM;
2505         } else {
2506                 pte = (mm == &init_mm) ?
2507                         pte_offset_kernel(pmd, addr) :
2508                         pte_offset_map_lock(mm, pmd, addr, &ptl);
2509         }
2510
2511         BUG_ON(pmd_huge(*pmd));
2512
2513         arch_enter_lazy_mmu_mode();
2514
2515         if (fn) {
2516                 do {
2517                         if (create || !pte_none(*pte)) {
2518                                 err = fn(pte++, addr, data);
2519                                 if (err)
2520                                         break;
2521                         }
2522                 } while (addr += PAGE_SIZE, addr != end);
2523         }
2524         *mask |= PGTBL_PTE_MODIFIED;
2525
2526         arch_leave_lazy_mmu_mode();
2527
2528         if (mm != &init_mm)
2529                 pte_unmap_unlock(pte-1, ptl);
2530         return err;
2531 }
2532
2533 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2534                                      unsigned long addr, unsigned long end,
2535                                      pte_fn_t fn, void *data, bool create,
2536                                      pgtbl_mod_mask *mask)
2537 {
2538         pmd_t *pmd;
2539         unsigned long next;
2540         int err = 0;
2541
2542         BUG_ON(pud_huge(*pud));
2543
2544         if (create) {
2545                 pmd = pmd_alloc_track(mm, pud, addr, mask);
2546                 if (!pmd)
2547                         return -ENOMEM;
2548         } else {
2549                 pmd = pmd_offset(pud, addr);
2550         }
2551         do {
2552                 next = pmd_addr_end(addr, end);
2553                 if (create || !pmd_none_or_clear_bad(pmd)) {
2554                         err = apply_to_pte_range(mm, pmd, addr, next, fn, data,
2555                                                  create, mask);
2556                         if (err)
2557                                 break;
2558                 }
2559         } while (pmd++, addr = next, addr != end);
2560         return err;
2561 }
2562
2563 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2564                                      unsigned long addr, unsigned long end,
2565                                      pte_fn_t fn, void *data, bool create,
2566                                      pgtbl_mod_mask *mask)
2567 {
2568         pud_t *pud;
2569         unsigned long next;
2570         int err = 0;
2571
2572         if (create) {
2573                 pud = pud_alloc_track(mm, p4d, addr, mask);
2574                 if (!pud)
2575                         return -ENOMEM;
2576         } else {
2577                 pud = pud_offset(p4d, addr);
2578         }
2579         do {
2580                 next = pud_addr_end(addr, end);
2581                 if (create || !pud_none_or_clear_bad(pud)) {
2582                         err = apply_to_pmd_range(mm, pud, addr, next, fn, data,
2583                                                  create, mask);
2584                         if (err)
2585                                 break;
2586                 }
2587         } while (pud++, addr = next, addr != end);
2588         return err;
2589 }
2590
2591 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2592                                      unsigned long addr, unsigned long end,
2593                                      pte_fn_t fn, void *data, bool create,
2594                                      pgtbl_mod_mask *mask)
2595 {
2596         p4d_t *p4d;
2597         unsigned long next;
2598         int err = 0;
2599
2600         if (create) {
2601                 p4d = p4d_alloc_track(mm, pgd, addr, mask);
2602                 if (!p4d)
2603                         return -ENOMEM;
2604         } else {
2605                 p4d = p4d_offset(pgd, addr);
2606         }
2607         do {
2608                 next = p4d_addr_end(addr, end);
2609                 if (create || !p4d_none_or_clear_bad(p4d)) {
2610                         err = apply_to_pud_range(mm, p4d, addr, next, fn, data,
2611                                                  create, mask);
2612                         if (err)
2613                                 break;
2614                 }
2615         } while (p4d++, addr = next, addr != end);
2616         return err;
2617 }
2618
2619 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2620                                  unsigned long size, pte_fn_t fn,
2621                                  void *data, bool create)
2622 {
2623         pgd_t *pgd;
2624         unsigned long start = addr, next;
2625         unsigned long end = addr + size;
2626         pgtbl_mod_mask mask = 0;
2627         int err = 0;
2628
2629         if (WARN_ON(addr >= end))
2630                 return -EINVAL;
2631
2632         pgd = pgd_offset(mm, addr);
2633         do {
2634                 next = pgd_addr_end(addr, end);
2635                 if (!create && pgd_none_or_clear_bad(pgd))
2636                         continue;
2637                 err = apply_to_p4d_range(mm, pgd, addr, next, fn, data, create, &mask);
2638                 if (err)
2639                         break;
2640         } while (pgd++, addr = next, addr != end);
2641
2642         if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
2643                 arch_sync_kernel_mappings(start, start + size);
2644
2645         return err;
2646 }
2647
2648 /*
2649  * Scan a region of virtual memory, filling in page tables as necessary
2650  * and calling a provided function on each leaf page table.
2651  */
2652 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2653                         unsigned long size, pte_fn_t fn, void *data)
2654 {
2655         return __apply_to_page_range(mm, addr, size, fn, data, true);
2656 }
2657 EXPORT_SYMBOL_GPL(apply_to_page_range);
2658
2659 /*
2660  * Scan a region of virtual memory, calling a provided function on
2661  * each leaf page table where it exists.
2662  *
2663  * Unlike apply_to_page_range, this does _not_ fill in page tables
2664  * where they are absent.
2665  */
2666 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
2667                                  unsigned long size, pte_fn_t fn, void *data)
2668 {
2669         return __apply_to_page_range(mm, addr, size, fn, data, false);
2670 }
2671 EXPORT_SYMBOL_GPL(apply_to_existing_page_range);
2672
2673 /*
2674  * handle_pte_fault chooses page fault handler according to an entry which was
2675  * read non-atomically.  Before making any commitment, on those architectures
2676  * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2677  * parts, do_swap_page must check under lock before unmapping the pte and
2678  * proceeding (but do_wp_page is only called after already making such a check;
2679  * and do_anonymous_page can safely check later on).
2680  */
2681 static inline int pte_unmap_same(struct mm_struct *mm, pmd_t *pmd,
2682                                 pte_t *page_table, pte_t orig_pte)
2683 {
2684         int same = 1;
2685 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
2686         if (sizeof(pte_t) > sizeof(unsigned long)) {
2687                 spinlock_t *ptl = pte_lockptr(mm, pmd);
2688                 spin_lock(ptl);
2689                 same = pte_same(*page_table, orig_pte);
2690                 spin_unlock(ptl);
2691         }
2692 #endif
2693         pte_unmap(page_table);
2694         return same;
2695 }
2696
2697 static inline bool cow_user_page(struct page *dst, struct page *src,
2698                                  struct vm_fault *vmf)
2699 {
2700         bool ret;
2701         void *kaddr;
2702         void __user *uaddr;
2703         bool locked = false;
2704         struct vm_area_struct *vma = vmf->vma;
2705         struct mm_struct *mm = vma->vm_mm;
2706         unsigned long addr = vmf->address;
2707
2708         if (likely(src)) {
2709                 copy_user_highpage(dst, src, addr, vma);
2710                 return true;
2711         }
2712
2713         /*
2714          * If the source page was a PFN mapping, we don't have
2715          * a "struct page" for it. We do a best-effort copy by
2716          * just copying from the original user address. If that
2717          * fails, we just zero-fill it. Live with it.
2718          */
2719         kaddr = kmap_atomic(dst);
2720         uaddr = (void __user *)(addr & PAGE_MASK);
2721
2722         /*
2723          * On architectures with software "accessed" bits, we would
2724          * take a double page fault, so mark it accessed here.
2725          */
2726         if (arch_faults_on_old_pte() && !pte_young(vmf->orig_pte)) {
2727                 pte_t entry;
2728
2729                 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2730                 locked = true;
2731                 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2732                         /*
2733                          * Other thread has already handled the fault
2734                          * and update local tlb only
2735                          */
2736                         update_mmu_tlb(vma, addr, vmf->pte);
2737                         ret = false;
2738                         goto pte_unlock;
2739                 }
2740
2741                 entry = pte_mkyoung(vmf->orig_pte);
2742                 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2743                         update_mmu_cache(vma, addr, vmf->pte);
2744         }
2745
2746         /*
2747          * This really shouldn't fail, because the page is there
2748          * in the page tables. But it might just be unreadable,
2749          * in which case we just give up and fill the result with
2750          * zeroes.
2751          */
2752         if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2753                 if (locked)
2754                         goto warn;
2755
2756                 /* Re-validate under PTL if the page is still mapped */
2757                 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2758                 locked = true;
2759                 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2760                         /* The PTE changed under us, update local tlb */
2761                         update_mmu_tlb(vma, addr, vmf->pte);
2762                         ret = false;
2763                         goto pte_unlock;
2764                 }
2765
2766                 /*
2767                  * The same page can be mapped back since last copy attempt.
2768                  * Try to copy again under PTL.
2769                  */
2770                 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2771                         /*
2772                          * Give a warn in case there can be some obscure
2773                          * use-case
2774                          */
2775 warn:
2776                         WARN_ON_ONCE(1);
2777                         clear_page(kaddr);
2778                 }
2779         }
2780
2781         ret = true;
2782
2783 pte_unlock:
2784         if (locked)
2785                 pte_unmap_unlock(vmf->pte, vmf->ptl);
2786         kunmap_atomic(kaddr);
2787         flush_dcache_page(dst);
2788
2789         return ret;
2790 }
2791
2792 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2793 {
2794         struct file *vm_file = vma->vm_file;
2795
2796         if (vm_file)
2797                 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2798
2799         /*
2800          * Special mappings (e.g. VDSO) do not have any file so fake
2801          * a default GFP_KERNEL for them.
2802          */
2803         return GFP_KERNEL;
2804 }
2805
2806 /*
2807  * Notify the address space that the page is about to become writable so that
2808  * it can prohibit this or wait for the page to get into an appropriate state.
2809  *
2810  * We do this without the lock held, so that it can sleep if it needs to.
2811  */
2812 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf)
2813 {
2814         vm_fault_t ret;
2815         struct page *page = vmf->page;
2816         unsigned int old_flags = vmf->flags;
2817
2818         vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2819
2820         if (vmf->vma->vm_file &&
2821             IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
2822                 return VM_FAULT_SIGBUS;
2823
2824         ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2825         /* Restore original flags so that caller is not surprised */
2826         vmf->flags = old_flags;
2827         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2828                 return ret;
2829         if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2830                 lock_page(page);
2831                 if (!page->mapping) {
2832                         unlock_page(page);
2833                         return 0; /* retry */
2834                 }
2835                 ret |= VM_FAULT_LOCKED;
2836         } else
2837                 VM_BUG_ON_PAGE(!PageLocked(page), page);
2838         return ret;
2839 }
2840
2841 /*
2842  * Handle dirtying of a page in shared file mapping on a write fault.
2843  *
2844  * The function expects the page to be locked and unlocks it.
2845  */
2846 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
2847 {
2848         struct vm_area_struct *vma = vmf->vma;
2849         struct address_space *mapping;
2850         struct page *page = vmf->page;
2851         bool dirtied;
2852         bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
2853
2854         dirtied = set_page_dirty(page);
2855         VM_BUG_ON_PAGE(PageAnon(page), page);
2856         /*
2857          * Take a local copy of the address_space - page.mapping may be zeroed
2858          * by truncate after unlock_page().   The address_space itself remains
2859          * pinned by vma->vm_file's reference.  We rely on unlock_page()'s
2860          * release semantics to prevent the compiler from undoing this copying.
2861          */
2862         mapping = page_rmapping(page);
2863         unlock_page(page);
2864
2865         if (!page_mkwrite)
2866                 file_update_time(vma->vm_file);
2867
2868         /*
2869          * Throttle page dirtying rate down to writeback speed.
2870          *
2871          * mapping may be NULL here because some device drivers do not
2872          * set page.mapping but still dirty their pages
2873          *
2874          * Drop the mmap_lock before waiting on IO, if we can. The file
2875          * is pinning the mapping, as per above.
2876          */
2877         if ((dirtied || page_mkwrite) && mapping) {
2878                 struct file *fpin;
2879
2880                 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
2881                 balance_dirty_pages_ratelimited(mapping);
2882                 if (fpin) {
2883                         fput(fpin);
2884                         return VM_FAULT_RETRY;
2885                 }
2886         }
2887
2888         return 0;
2889 }
2890
2891 /*
2892  * Handle write page faults for pages that can be reused in the current vma
2893  *
2894  * This can happen either due to the mapping being with the VM_SHARED flag,
2895  * or due to us being the last reference standing to the page. In either
2896  * case, all we need to do here is to mark the page as writable and update
2897  * any related book-keeping.
2898  */
2899 static inline void wp_page_reuse(struct vm_fault *vmf)
2900         __releases(vmf->ptl)
2901 {
2902         struct vm_area_struct *vma = vmf->vma;
2903         struct page *page = vmf->page;
2904         pte_t entry;
2905         /*
2906          * Clear the pages cpupid information as the existing
2907          * information potentially belongs to a now completely
2908          * unrelated process.
2909          */
2910         if (page)
2911                 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
2912
2913         flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
2914         entry = pte_mkyoung(vmf->orig_pte);
2915         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2916         if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
2917                 update_mmu_cache(vma, vmf->address, vmf->pte);
2918         pte_unmap_unlock(vmf->pte, vmf->ptl);
2919         count_vm_event(PGREUSE);
2920 }
2921
2922 /*
2923  * Handle the case of a page which we actually need to copy to a new page.
2924  *
2925  * Called with mmap_lock locked and the old page referenced, but
2926  * without the ptl held.
2927  *
2928  * High level logic flow:
2929  *
2930  * - Allocate a page, copy the content of the old page to the new one.
2931  * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
2932  * - Take the PTL. If the pte changed, bail out and release the allocated page
2933  * - If the pte is still the way we remember it, update the page table and all
2934  *   relevant references. This includes dropping the reference the page-table
2935  *   held to the old page, as well as updating the rmap.
2936  * - In any case, unlock the PTL and drop the reference we took to the old page.
2937  */
2938 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
2939 {
2940         struct vm_area_struct *vma = vmf->vma;
2941         struct mm_struct *mm = vma->vm_mm;
2942         struct page *old_page = vmf->page;
2943         struct page *new_page = NULL;
2944         pte_t entry;
2945         int page_copied = 0;
2946         struct mmu_notifier_range range;
2947
2948         if (unlikely(anon_vma_prepare(vma)))
2949                 goto oom;
2950
2951         if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
2952                 new_page = alloc_zeroed_user_highpage_movable(vma,
2953                                                               vmf->address);
2954                 if (!new_page)
2955                         goto oom;
2956         } else {
2957                 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
2958                                 vmf->address);
2959                 if (!new_page)
2960                         goto oom;
2961
2962                 if (!cow_user_page(new_page, old_page, vmf)) {
2963                         /*
2964                          * COW failed, if the fault was solved by other,
2965                          * it's fine. If not, userspace would re-fault on
2966                          * the same address and we will handle the fault
2967                          * from the second attempt.
2968                          */
2969                         put_page(new_page);
2970                         if (old_page)
2971                                 put_page(old_page);
2972                         return 0;
2973                 }
2974         }
2975
2976         if (mem_cgroup_charge(new_page, mm, GFP_KERNEL))
2977                 goto oom_free_new;
2978         cgroup_throttle_swaprate(new_page, GFP_KERNEL);
2979
2980         __SetPageUptodate(new_page);
2981
2982         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
2983                                 vmf->address & PAGE_MASK,
2984                                 (vmf->address & PAGE_MASK) + PAGE_SIZE);
2985         mmu_notifier_invalidate_range_start(&range);
2986
2987         /*
2988          * Re-check the pte - we dropped the lock
2989          */
2990         vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
2991         if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2992                 if (old_page) {
2993                         if (!PageAnon(old_page)) {
2994                                 dec_mm_counter_fast(mm,
2995                                                 mm_counter_file(old_page));
2996                                 inc_mm_counter_fast(mm, MM_ANONPAGES);
2997                         }
2998                 } else {
2999                         inc_mm_counter_fast(mm, MM_ANONPAGES);
3000                 }
3001                 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3002                 entry = mk_pte(new_page, vma->vm_page_prot);
3003                 entry = pte_sw_mkyoung(entry);
3004                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3005                 /*
3006                  * Clear the pte entry and flush it first, before updating the
3007                  * pte with the new entry. This will avoid a race condition
3008                  * seen in the presence of one thread doing SMC and another
3009                  * thread doing COW.
3010                  */
3011                 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
3012                 page_add_new_anon_rmap(new_page, vma, vmf->address, false);
3013                 lru_cache_add_inactive_or_unevictable(new_page, vma);
3014                 /*
3015                  * We call the notify macro here because, when using secondary
3016                  * mmu page tables (such as kvm shadow page tables), we want the
3017                  * new page to be mapped directly into the secondary page table.
3018                  */
3019                 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
3020                 update_mmu_cache(vma, vmf->address, vmf->pte);
3021                 if (old_page) {
3022                         /*
3023                          * Only after switching the pte to the new page may
3024                          * we remove the mapcount here. Otherwise another
3025                          * process may come and find the rmap count decremented
3026                          * before the pte is switched to the new page, and
3027                          * "reuse" the old page writing into it while our pte
3028                          * here still points into it and can be read by other
3029                          * threads.
3030                          *
3031                          * The critical issue is to order this
3032                          * page_remove_rmap with the ptp_clear_flush above.
3033                          * Those stores are ordered by (if nothing else,)
3034                          * the barrier present in the atomic_add_negative
3035                          * in page_remove_rmap.
3036                          *
3037                          * Then the TLB flush in ptep_clear_flush ensures that
3038                          * no process can access the old page before the
3039                          * decremented mapcount is visible. And the old page
3040                          * cannot be reused until after the decremented
3041                          * mapcount is visible. So transitively, TLBs to
3042                          * old page will be flushed before it can be reused.
3043                          */
3044                         page_remove_rmap(old_page, false);
3045                 }
3046
3047                 /* Free the old page.. */
3048                 new_page = old_page;
3049                 page_copied = 1;
3050         } else {
3051                 update_mmu_tlb(vma, vmf->address, vmf->pte);
3052         }
3053
3054         if (new_page)
3055                 put_page(new_page);
3056
3057         pte_unmap_unlock(vmf->pte, vmf->ptl);
3058         /*
3059          * No need to double call mmu_notifier->invalidate_range() callback as
3060          * the above ptep_clear_flush_notify() did already call it.
3061          */
3062         mmu_notifier_invalidate_range_only_end(&range);
3063         if (old_page) {
3064                 /*
3065                  * Don't let another task, with possibly unlocked vma,
3066                  * keep the mlocked page.
3067                  */
3068                 if (page_copied && (vma->vm_flags & VM_LOCKED)) {
3069                         lock_page(old_page);    /* LRU manipulation */
3070                         if (PageMlocked(old_page))
3071                                 munlock_vma_page(old_page);
3072                         unlock_page(old_page);
3073                 }
3074                 put_page(old_page);
3075         }
3076         return page_copied ? VM_FAULT_WRITE : 0;
3077 oom_free_new:
3078         put_page(new_page);
3079 oom:
3080         if (old_page)
3081                 put_page(old_page);
3082         return VM_FAULT_OOM;
3083 }
3084
3085 /**
3086  * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
3087  *                        writeable once the page is prepared
3088  *
3089  * @vmf: structure describing the fault
3090  *
3091  * This function handles all that is needed to finish a write page fault in a
3092  * shared mapping due to PTE being read-only once the mapped page is prepared.
3093  * It handles locking of PTE and modifying it.
3094  *
3095  * The function expects the page to be locked or other protection against
3096  * concurrent faults / writeback (such as DAX radix tree locks).
3097  *
3098  * Return: %VM_FAULT_WRITE on success, %0 when PTE got changed before
3099  * we acquired PTE lock.
3100  */
3101 vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf)
3102 {
3103         WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
3104         vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
3105                                        &vmf->ptl);
3106         /*
3107          * We might have raced with another page fault while we released the
3108          * pte_offset_map_lock.
3109          */
3110         if (!pte_same(*vmf->pte, vmf->orig_pte)) {
3111                 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
3112                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3113                 return VM_FAULT_NOPAGE;
3114         }
3115         wp_page_reuse(vmf);
3116         return 0;
3117 }
3118
3119 /*
3120  * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
3121  * mapping
3122  */
3123 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
3124 {
3125         struct vm_area_struct *vma = vmf->vma;
3126
3127         if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
3128                 vm_fault_t ret;
3129
3130                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3131                 vmf->flags |= FAULT_FLAG_MKWRITE;
3132                 ret = vma->vm_ops->pfn_mkwrite(vmf);
3133                 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
3134                         return ret;
3135                 return finish_mkwrite_fault(vmf);
3136         }
3137         wp_page_reuse(vmf);
3138         return VM_FAULT_WRITE;
3139 }
3140
3141 static vm_fault_t wp_page_shared(struct vm_fault *vmf)
3142         __releases(vmf->ptl)
3143 {
3144         struct vm_area_struct *vma = vmf->vma;
3145         vm_fault_t ret = VM_FAULT_WRITE;
3146
3147         get_page(vmf->page);
3148
3149         if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
3150                 vm_fault_t tmp;
3151
3152                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3153                 tmp = do_page_mkwrite(vmf);
3154                 if (unlikely(!tmp || (tmp &
3155                                       (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3156                         put_page(vmf->page);
3157                         return tmp;
3158                 }
3159                 tmp = finish_mkwrite_fault(vmf);
3160                 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3161                         unlock_page(vmf->page);
3162                         put_page(vmf->page);
3163                         return tmp;
3164                 }
3165         } else {
3166                 wp_page_reuse(vmf);
3167                 lock_page(vmf->page);
3168         }
3169         ret |= fault_dirty_shared_page(vmf);
3170         put_page(vmf->page);
3171
3172         return ret;
3173 }
3174
3175 /*
3176  * This routine handles present pages, when users try to write
3177  * to a shared page. It is done by copying the page to a new address
3178  * and decrementing the shared-page counter for the old page.
3179  *
3180  * Note that this routine assumes that the protection checks have been
3181  * done by the caller (the low-level page fault routine in most cases).
3182  * Thus we can safely just mark it writable once we've done any necessary
3183  * COW.
3184  *
3185  * We also mark the page dirty at this point even though the page will
3186  * change only once the write actually happens. This avoids a few races,
3187  * and potentially makes it more efficient.
3188  *
3189  * We enter with non-exclusive mmap_lock (to exclude vma changes,
3190  * but allow concurrent faults), with pte both mapped and locked.
3191  * We return with mmap_lock still held, but pte unmapped and unlocked.
3192  */
3193 static vm_fault_t do_wp_page(struct vm_fault *vmf)
3194         __releases(vmf->ptl)
3195 {
3196         struct vm_area_struct *vma = vmf->vma;
3197
3198         if (userfaultfd_pte_wp(vma, *vmf->pte)) {
3199                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3200                 return handle_userfault(vmf, VM_UFFD_WP);
3201         }
3202
3203         /*
3204          * Userfaultfd write-protect can defer flushes. Ensure the TLB
3205          * is flushed in this case before copying.
3206          */
3207         if (unlikely(userfaultfd_wp(vmf->vma) &&
3208                      mm_tlb_flush_pending(vmf->vma->vm_mm)))
3209                 flush_tlb_page(vmf->vma, vmf->address);
3210
3211         vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
3212         if (!vmf->page) {
3213                 /*
3214                  * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
3215                  * VM_PFNMAP VMA.
3216                  *
3217                  * We should not cow pages in a shared writeable mapping.
3218                  * Just mark the pages writable and/or call ops->pfn_mkwrite.
3219                  */
3220                 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3221                                      (VM_WRITE|VM_SHARED))
3222                         return wp_pfn_shared(vmf);
3223
3224                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3225                 return wp_page_copy(vmf);
3226         }
3227
3228         /*
3229          * Take out anonymous pages first, anonymous shared vmas are
3230          * not dirty accountable.
3231          */
3232         if (PageAnon(vmf->page)) {
3233                 struct page *page = vmf->page;
3234
3235                 /* PageKsm() doesn't necessarily raise the page refcount */
3236                 if (PageKsm(page) || page_count(page) != 1)
3237                         goto copy;
3238                 if (!trylock_page(page))
3239                         goto copy;
3240                 if (PageKsm(page) || page_mapcount(page) != 1 || page_count(page) != 1) {
3241                         unlock_page(page);
3242                         goto copy;
3243                 }
3244                 /*
3245                  * Ok, we've got the only map reference, and the only
3246                  * page count reference, and the page is locked,
3247                  * it's dark out, and we're wearing sunglasses. Hit it.
3248                  */
3249                 unlock_page(page);
3250                 wp_page_reuse(vmf);
3251                 return VM_FAULT_WRITE;
3252         } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3253                                         (VM_WRITE|VM_SHARED))) {
3254                 return wp_page_shared(vmf);
3255         }
3256 copy:
3257         /*
3258          * Ok, we need to copy. Oh, well..
3259          */
3260         get_page(vmf->page);
3261
3262         pte_unmap_unlock(vmf->pte, vmf->ptl);
3263         return wp_page_copy(vmf);
3264 }
3265
3266 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
3267                 unsigned long start_addr, unsigned long end_addr,
3268                 struct zap_details *details)
3269 {
3270         zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
3271 }
3272
3273 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
3274                                             struct zap_details *details)
3275 {
3276         struct vm_area_struct *vma;
3277         pgoff_t vba, vea, zba, zea;
3278
3279         vma_interval_tree_foreach(vma, root,
3280                         details->first_index, details->last_index) {
3281
3282                 vba = vma->vm_pgoff;
3283                 vea = vba + vma_pages(vma) - 1;
3284                 zba = details->first_index;
3285                 if (zba < vba)
3286                         zba = vba;
3287                 zea = details->last_index;
3288                 if (zea > vea)
3289                         zea = vea;
3290
3291                 unmap_mapping_range_vma(vma,
3292                         ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
3293                         ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3294                                 details);
3295         }
3296 }
3297
3298 /**
3299  * unmap_mapping_pages() - Unmap pages from processes.
3300  * @mapping: The address space containing pages to be unmapped.
3301  * @start: Index of first page to be unmapped.
3302  * @nr: Number of pages to be unmapped.  0 to unmap to end of file.
3303  * @even_cows: Whether to unmap even private COWed pages.
3304  *
3305  * Unmap the pages in this address space from any userspace process which
3306  * has them mmaped.  Generally, you want to remove COWed pages as well when
3307  * a file is being truncated, but not when invalidating pages from the page
3308  * cache.
3309  */
3310 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
3311                 pgoff_t nr, bool even_cows)
3312 {
3313         struct zap_details details = { };
3314
3315         details.check_mapping = even_cows ? NULL : mapping;
3316         details.first_index = start;
3317         details.last_index = start + nr - 1;
3318         if (details.last_index < details.first_index)
3319                 details.last_index = ULONG_MAX;
3320
3321         i_mmap_lock_write(mapping);
3322         if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3323                 unmap_mapping_range_tree(&mapping->i_mmap, &details);
3324         i_mmap_unlock_write(mapping);
3325 }
3326
3327 /**
3328  * unmap_mapping_range - unmap the portion of all mmaps in the specified
3329  * address_space corresponding to the specified byte range in the underlying
3330  * file.
3331  *
3332  * @mapping: the address space containing mmaps to be unmapped.
3333  * @holebegin: byte in first page to unmap, relative to the start of
3334  * the underlying file.  This will be rounded down to a PAGE_SIZE
3335  * boundary.  Note that this is different from truncate_pagecache(), which
3336  * must keep the partial page.  In contrast, we must get rid of
3337  * partial pages.
3338  * @holelen: size of prospective hole in bytes.  This will be rounded
3339  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
3340  * end of the file.
3341  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3342  * but 0 when invalidating pagecache, don't throw away private data.
3343  */
3344 void unmap_mapping_range(struct address_space *mapping,
3345                 loff_t const holebegin, loff_t const holelen, int even_cows)
3346 {
3347         pgoff_t hba = holebegin >> PAGE_SHIFT;
3348         pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3349
3350         /* Check for overflow. */
3351         if (sizeof(holelen) > sizeof(hlen)) {
3352                 long long holeend =
3353                         (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3354                 if (holeend & ~(long long)ULONG_MAX)
3355                         hlen = ULONG_MAX - hba + 1;
3356         }
3357
3358         unmap_mapping_pages(mapping, hba, hlen, even_cows);
3359 }
3360 EXPORT_SYMBOL(unmap_mapping_range);
3361
3362 /*
3363  * We enter with non-exclusive mmap_lock (to exclude vma changes,
3364  * but allow concurrent faults), and pte mapped but not yet locked.
3365  * We return with pte unmapped and unlocked.
3366  *
3367  * We return with the mmap_lock locked or unlocked in the same cases
3368  * as does filemap_fault().
3369  */
3370 vm_fault_t do_swap_page(struct vm_fault *vmf)
3371 {
3372         struct vm_area_struct *vma = vmf->vma;
3373         struct page *page = NULL, *swapcache;
3374         swp_entry_t entry;
3375         pte_t pte;
3376         int locked;
3377         int exclusive = 0;
3378         vm_fault_t ret = 0;
3379         void *shadow = NULL;
3380
3381         if (!pte_unmap_same(vma->vm_mm, vmf->pmd, vmf->pte, vmf->orig_pte))
3382                 goto out;
3383
3384         entry = pte_to_swp_entry(vmf->orig_pte);
3385         if (unlikely(non_swap_entry(entry))) {
3386                 if (is_migration_entry(entry)) {
3387                         migration_entry_wait(vma->vm_mm, vmf->pmd,
3388                                              vmf->address);
3389                 } else if (is_device_private_entry(entry)) {
3390                         vmf->page = device_private_entry_to_page(entry);
3391                         ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
3392                 } else if (is_hwpoison_entry(entry)) {
3393                         ret = VM_FAULT_HWPOISON;
3394                 } else {
3395                         print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3396                         ret = VM_FAULT_SIGBUS;
3397                 }
3398                 goto out;
3399         }
3400
3401
3402         delayacct_set_flag(DELAYACCT_PF_SWAPIN);
3403         page = lookup_swap_cache(entry, vma, vmf->address);
3404         swapcache = page;
3405
3406         if (!page) {
3407                 struct swap_info_struct *si = swp_swap_info(entry);
3408
3409                 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
3410                     __swap_count(entry) == 1) {
3411                         /* skip swapcache */
3412                         page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3413                                                         vmf->address);
3414                         if (page) {
3415                                 int err;
3416
3417                                 __SetPageLocked(page);
3418                                 __SetPageSwapBacked(page);
3419                                 set_page_private(page, entry.val);
3420
3421                                 /* Tell memcg to use swap ownership records */
3422                                 SetPageSwapCache(page);
3423                                 err = mem_cgroup_charge(page, vma->vm_mm,
3424                                                         GFP_KERNEL);
3425                                 ClearPageSwapCache(page);
3426                                 if (err) {
3427                                         ret = VM_FAULT_OOM;
3428                                         goto out_page;
3429                                 }
3430
3431                                 shadow = get_shadow_from_swap_cache(entry);
3432                                 if (shadow)
3433                                         workingset_refault(page, shadow);
3434
3435                                 lru_cache_add(page);
3436                                 swap_readpage(page, true);
3437                         }
3438                 } else {
3439                         page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3440                                                 vmf);
3441                         swapcache = page;
3442                 }
3443
3444                 if (!page) {
3445                         /*
3446                          * Back out if somebody else faulted in this pte
3447                          * while we released the pte lock.
3448                          */
3449                         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3450                                         vmf->address, &vmf->ptl);
3451                         if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3452                                 ret = VM_FAULT_OOM;
3453                         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3454                         goto unlock;
3455                 }
3456
3457                 /* Had to read the page from swap area: Major fault */
3458                 ret = VM_FAULT_MAJOR;
3459                 count_vm_event(PGMAJFAULT);
3460                 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3461         } else if (PageHWPoison(page)) {
3462                 /*
3463                  * hwpoisoned dirty swapcache pages are kept for killing
3464                  * owner processes (which may be unknown at hwpoison time)
3465                  */
3466                 ret = VM_FAULT_HWPOISON;
3467                 delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3468                 goto out_release;
3469         }
3470
3471         locked = lock_page_or_retry(page, vma->vm_mm, vmf->flags);
3472
3473         delayacct_clear_flag(DELAYACCT_PF_SWAPIN);
3474         if (!locked) {
3475                 ret |= VM_FAULT_RETRY;
3476                 goto out_release;
3477         }
3478
3479         /*
3480          * Make sure try_to_free_swap or reuse_swap_page or swapoff did not
3481          * release the swapcache from under us.  The page pin, and pte_same
3482          * test below, are not enough to exclude that.  Even if it is still
3483          * swapcache, we need to check that the page's swap has not changed.
3484          */
3485         if (unlikely((!PageSwapCache(page) ||
3486                         page_private(page) != entry.val)) && swapcache)
3487                 goto out_page;
3488
3489         page = ksm_might_need_to_copy(page, vma, vmf->address);
3490         if (unlikely(!page)) {
3491                 ret = VM_FAULT_OOM;
3492                 page = swapcache;
3493                 goto out_page;
3494         }
3495
3496         cgroup_throttle_swaprate(page, GFP_KERNEL);
3497
3498         /*
3499          * Back out if somebody else already faulted in this pte.
3500          */
3501         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3502                         &vmf->ptl);
3503         if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3504                 goto out_nomap;
3505
3506         if (unlikely(!PageUptodate(page))) {
3507                 ret = VM_FAULT_SIGBUS;
3508                 goto out_nomap;
3509         }
3510
3511         /*
3512          * The page isn't present yet, go ahead with the fault.
3513          *
3514          * Be careful about the sequence of operations here.
3515          * To get its accounting right, reuse_swap_page() must be called
3516          * while the page is counted on swap but not yet in mapcount i.e.
3517          * before page_add_anon_rmap() and swap_free(); try_to_free_swap()
3518          * must be called after the swap_free(), or it will never succeed.
3519          */
3520
3521         inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3522         dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3523         pte = mk_pte(page, vma->vm_page_prot);
3524         if ((vmf->flags & FAULT_FLAG_WRITE) && reuse_swap_page(page, NULL)) {
3525                 pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3526                 vmf->flags &= ~FAULT_FLAG_WRITE;
3527                 ret |= VM_FAULT_WRITE;
3528                 exclusive = RMAP_EXCLUSIVE;
3529         }
3530         flush_icache_page(vma, page);
3531         if (pte_swp_soft_dirty(vmf->orig_pte))
3532                 pte = pte_mksoft_dirty(pte);
3533         if (pte_swp_uffd_wp(vmf->orig_pte)) {
3534                 pte = pte_mkuffd_wp(pte);
3535                 pte = pte_wrprotect(pte);
3536         }
3537         set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3538         arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
3539         vmf->orig_pte = pte;
3540
3541         /* ksm created a completely new copy */
3542         if (unlikely(page != swapcache && swapcache)) {
3543                 page_add_new_anon_rmap(page, vma, vmf->address, false);
3544                 lru_cache_add_inactive_or_unevictable(page, vma);
3545         } else {
3546                 do_page_add_anon_rmap(page, vma, vmf->address, exclusive);
3547         }
3548
3549         swap_free(entry);
3550         if (mem_cgroup_swap_full(page) ||
3551             (vma->vm_flags & VM_LOCKED) || PageMlocked(page))
3552                 try_to_free_swap(page);
3553         unlock_page(page);
3554         if (page != swapcache && swapcache) {
3555                 /*
3556                  * Hold the lock to avoid the swap entry to be reused
3557                  * until we take the PT lock for the pte_same() check
3558                  * (to avoid false positives from pte_same). For
3559                  * further safety release the lock after the swap_free
3560                  * so that the swap count won't change under a
3561                  * parallel locked swapcache.
3562                  */
3563                 unlock_page(swapcache);
3564                 put_page(swapcache);
3565         }
3566
3567         if (vmf->flags & FAULT_FLAG_WRITE) {
3568                 ret |= do_wp_page(vmf);
3569                 if (ret & VM_FAULT_ERROR)
3570                         ret &= VM_FAULT_ERROR;
3571                 goto out;
3572         }
3573
3574         /* No need to invalidate - it was non-present before */
3575         update_mmu_cache(vma, vmf->address, vmf->pte);
3576 unlock:
3577         pte_unmap_unlock(vmf->pte, vmf->ptl);
3578 out:
3579         return ret;
3580 out_nomap:
3581         pte_unmap_unlock(vmf->pte, vmf->ptl);
3582 out_page:
3583         unlock_page(page);
3584 out_release:
3585         put_page(page);
3586         if (page != swapcache && swapcache) {
3587                 unlock_page(swapcache);
3588                 put_page(swapcache);
3589         }
3590         return ret;
3591 }
3592
3593 extern bool eager_allocation;
3594
3595 /*
3596  * We enter with non-exclusive mmap_lock (to exclude vma changes,
3597  * but allow concurrent faults), and pte mapped but not yet locked.
3598  * We return with mmap_lock still held, but pte unmapped and unlocked.
3599  */
3600 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
3601 {
3602         struct vm_area_struct *vma = vmf->vma;
3603         struct page *page;
3604         vm_fault_t ret = 0;
3605         pte_t entry;
3606
3607         /* File mapping without ->vm_ops ? */
3608         if (vma->vm_flags & VM_SHARED)
3609                 return VM_FAULT_SIGBUS;
3610
3611         /*
3612          * Use pte_alloc() instead of pte_alloc_map().  We can't run
3613          * pte_offset_map() on pmds where a huge pmd might be created
3614          * from a different thread.
3615          *
3616          * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
3617          * parallel threads are excluded by other means.
3618          *
3619          * Here we only have mmap_read_lock(mm).
3620          */
3621         if (pte_alloc(vma->vm_mm, vmf->pmd))
3622                 return VM_FAULT_OOM;
3623
3624         /* See the comment in pte_alloc_one_map() */
3625         if (unlikely(pmd_trans_unstable(vmf->pmd)))
3626                 return 0;
3627
3628         /* Use the zero-page for reads */
3629         if (!(vmf->flags & FAULT_FLAG_WRITE) &&
3630                         !mm_forbids_zeropage(vma->vm_mm)) {
3631                 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
3632                                                 vma->vm_page_prot));
3633                 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3634                                 vmf->address, &vmf->ptl);
3635                 if (!pte_none(*vmf->pte)) {
3636                         update_mmu_tlb(vma, vmf->address, vmf->pte);
3637                         goto unlock;
3638                 }
3639                 ret = check_stable_address_space(vma->vm_mm);
3640                 if (ret)
3641                         goto unlock;
3642                 /* Deliver the page fault to userland, check inside PT lock */
3643                 if (userfaultfd_missing(vma)) {
3644                         pte_unmap_unlock(vmf->pte, vmf->ptl);
3645                         return handle_userfault(vmf, VM_UFFD_MISSING);
3646                 }
3647                 goto setpte;
3648         }
3649
3650         /* Allocate our own private page. */
3651         if (unlikely(anon_vma_prepare(vma)))
3652                 goto oom;
3653 #ifdef CONFIG_FINEGRAINED_THP
3654 #ifndef CONFIG_THP_CONSERVATIVE
3655         /*
3656          * 64KB hugepage creation on page fault is only allowed
3657          * in an aggressive policy or a near-conservative policy
3658          */
3659         if (__transparent_hugepage_enabled(vma)) {
3660                 ret = arch_do_huge_pte_anonymous_page(vmf);
3661                 if (!(ret & VM_FAULT_FALLBACK)) {
3662                         return ret;
3663                 }
3664                 ret = 0;
3665         }
3666 #endif /* CONFIG_THP_CONSERVATIVE */
3667 #endif /* CONFIG_FINEGRAINED_THP */
3668
3669         page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
3670         if (!page)
3671                 goto oom;
3672
3673         if (mem_cgroup_charge(page, vma->vm_mm, GFP_KERNEL))
3674                 goto oom_free_page;
3675         cgroup_throttle_swaprate(page, GFP_KERNEL);
3676
3677         /*
3678          * The memory barrier inside __SetPageUptodate makes sure that
3679          * preceding stores to the page contents become visible before
3680          * the set_pte_at() write.
3681          */
3682         __SetPageUptodate(page);
3683
3684         entry = mk_pte(page, vma->vm_page_prot);
3685         entry = pte_sw_mkyoung(entry);
3686         if (vma->vm_flags & VM_WRITE)
3687                 entry = pte_mkwrite(pte_mkdirty(entry));
3688
3689         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3690                         &vmf->ptl);
3691         if (!pte_none(*vmf->pte)) {
3692                 update_mmu_cache(vma, vmf->address, vmf->pte);
3693                 goto release;
3694         }
3695
3696         ret = check_stable_address_space(vma->vm_mm);
3697         if (ret)
3698                 goto release;
3699
3700         /* Deliver the page fault to userland, check inside PT lock */
3701         if (userfaultfd_missing(vma)) {
3702                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3703                 put_page(page);
3704                 return handle_userfault(vmf, VM_UFFD_MISSING);
3705         }
3706
3707         inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3708         page_add_new_anon_rmap(page, vma, vmf->address, false);
3709         lru_cache_add_inactive_or_unevictable(page, vma);
3710 setpte:
3711         set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3712
3713         /* No need to invalidate - it was non-present before */
3714         update_mmu_cache(vma, vmf->address, vmf->pte);
3715 unlock:
3716         pte_unmap_unlock(vmf->pte, vmf->ptl);
3717         return ret;
3718 release:
3719         put_page(page);
3720         goto unlock;
3721 oom_free_page:
3722         put_page(page);
3723 oom:
3724         return VM_FAULT_OOM;
3725 }
3726
3727 /*
3728  * The mmap_lock must have been held on entry, and may have been
3729  * released depending on flags and vma->vm_ops->fault() return value.
3730  * See filemap_fault() and __lock_page_retry().
3731  */
3732 static vm_fault_t __do_fault(struct vm_fault *vmf)
3733 {
3734         struct vm_area_struct *vma = vmf->vma;
3735         vm_fault_t ret;
3736
3737         /*
3738          * Preallocate pte before we take page_lock because this might lead to
3739          * deadlocks for memcg reclaim which waits for pages under writeback:
3740          *                              lock_page(A)
3741          *                              SetPageWriteback(A)
3742          *                              unlock_page(A)
3743          * lock_page(B)
3744          *                              lock_page(B)
3745          * pte_alloc_one
3746          *   shrink_page_list
3747          *     wait_on_page_writeback(A)
3748          *                              SetPageWriteback(B)
3749          *                              unlock_page(B)
3750          *                              # flush A, B to clear the writeback
3751          */
3752         if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
3753                 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3754                 if (!vmf->prealloc_pte)
3755                         return VM_FAULT_OOM;
3756                 smp_wmb(); /* See comment in __pte_alloc() */
3757         }
3758
3759         ret = vma->vm_ops->fault(vmf);
3760         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
3761                             VM_FAULT_DONE_COW)))
3762                 return ret;
3763
3764         if (unlikely(PageHWPoison(vmf->page))) {
3765                 if (ret & VM_FAULT_LOCKED)
3766                         unlock_page(vmf->page);
3767                 put_page(vmf->page);
3768                 vmf->page = NULL;
3769                 return VM_FAULT_HWPOISON;
3770         }
3771
3772         if (unlikely(!(ret & VM_FAULT_LOCKED)))
3773                 lock_page(vmf->page);
3774         else
3775                 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
3776
3777         return ret;
3778 }
3779
3780 /*
3781  * The ordering of these checks is important for pmds with _PAGE_DEVMAP set.
3782  * If we check pmd_trans_unstable() first we will trip the bad_pmd() check
3783  * inside of pmd_none_or_trans_huge_or_clear_bad(). This will end up correctly
3784  * returning 1 but not before it spams dmesg with the pmd_clear_bad() output.
3785  */
3786 static int pmd_devmap_trans_unstable(pmd_t *pmd)
3787 {
3788         return pmd_devmap(*pmd) || pmd_trans_unstable(pmd);
3789 }
3790
3791 static vm_fault_t pte_alloc_one_map(struct vm_fault *vmf)
3792 {
3793         struct vm_area_struct *vma = vmf->vma;
3794
3795         if (!pmd_none(*vmf->pmd))
3796                 goto map_pte;
3797         if (vmf->prealloc_pte) {
3798                 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3799                 if (unlikely(!pmd_none(*vmf->pmd))) {
3800                         spin_unlock(vmf->ptl);
3801                         goto map_pte;
3802                 }
3803
3804                 mm_inc_nr_ptes(vma->vm_mm);
3805                 pmd_populate(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3806                 spin_unlock(vmf->ptl);
3807                 vmf->prealloc_pte = NULL;
3808         } else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd))) {
3809                 return VM_FAULT_OOM;
3810         }
3811 map_pte:
3812         /*
3813          * If a huge pmd materialized under us just retry later.  Use
3814          * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead of
3815          * pmd_trans_huge() to ensure the pmd didn't become pmd_trans_huge
3816          * under us and then back to pmd_none, as a result of MADV_DONTNEED
3817          * running immediately after a huge pmd fault in a different thread of
3818          * this mm, in turn leading to a misleading pmd_trans_huge() retval.
3819          * All we have to ensure is that it is a regular pmd that we can walk
3820          * with pte_offset_map() and we can do that through an atomic read in
3821          * C, which is what pmd_trans_unstable() provides.
3822          */
3823         if (pmd_devmap_trans_unstable(vmf->pmd))
3824                 return VM_FAULT_NOPAGE;
3825
3826         /*
3827          * At this point we know that our vmf->pmd points to a page of ptes
3828          * and it cannot become pmd_none(), pmd_devmap() or pmd_trans_huge()
3829          * for the duration of the fault.  If a racing MADV_DONTNEED runs and
3830          * we zap the ptes pointed to by our vmf->pmd, the vmf->ptl will still
3831          * be valid and we will re-check to make sure the vmf->pte isn't
3832          * pte_none() under vmf->ptl protection when we return to
3833          * alloc_set_pte().
3834          */
3835         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3836                         &vmf->ptl);
3837         return 0;
3838 }
3839
3840 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
3841 static void deposit_prealloc_pte(struct vm_fault *vmf)
3842 {
3843         struct vm_area_struct *vma = vmf->vma;
3844
3845         pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
3846         /*
3847          * We are going to consume the prealloc table,
3848          * count that as nr_ptes.
3849          */
3850         mm_inc_nr_ptes(vma->vm_mm);
3851         vmf->prealloc_pte = NULL;
3852 }
3853
3854 static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3855 {
3856         struct vm_area_struct *vma = vmf->vma;
3857         bool write = vmf->flags & FAULT_FLAG_WRITE;
3858         unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
3859         pmd_t entry;
3860         int i;
3861         vm_fault_t ret = VM_FAULT_FALLBACK;
3862
3863         if (!transhuge_vma_suitable(vma, haddr))
3864                 return ret;
3865
3866         page = compound_head(page);
3867         if (compound_order(page) != HPAGE_PMD_ORDER)
3868                 return ret;
3869
3870         /*
3871          * Archs like ppc64 need additonal space to store information
3872          * related to pte entry. Use the preallocated table for that.
3873          */
3874         if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
3875                 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
3876                 if (!vmf->prealloc_pte)
3877                         return VM_FAULT_OOM;
3878                 smp_wmb(); /* See comment in __pte_alloc() */
3879         }
3880
3881         vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
3882         if (unlikely(!pmd_none(*vmf->pmd)))
3883                 goto out;
3884
3885         for (i = 0; i < HPAGE_PMD_NR; i++)
3886                 flush_icache_page(vma, page + i);
3887
3888         entry = mk_huge_pmd(page, vma->vm_page_prot);
3889         if (write)
3890                 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
3891
3892         add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
3893         page_add_file_rmap(page, true);
3894         /*
3895          * deposit and withdraw with pmd lock held
3896          */
3897         if (arch_needs_pgtable_deposit())
3898                 deposit_prealloc_pte(vmf);
3899
3900         set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
3901
3902         update_mmu_cache_pmd(vma, haddr, vmf->pmd);
3903
3904         /* fault is handled */
3905         ret = 0;
3906         count_vm_event(THP_FILE_MAPPED);
3907 out:
3908         spin_unlock(vmf->ptl);
3909         return ret;
3910 }
3911 #else
3912 static vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
3913 {
3914         BUILD_BUG();
3915         return 0;
3916 }
3917
3918 #ifdef CONFIG_FINEGRAINED_THP
3919 static vm_fault_t arch_do_set_huge_pte(struct vm_fault *vmf, struct page *page)
3920 {
3921         BUILD_BUG();
3922         return 0;
3923 }
3924 #endif
3925 #endif
3926
3927 /**
3928  * alloc_set_pte - setup new PTE entry for given page and add reverse page
3929  * mapping. If needed, the function allocates page table or use pre-allocated.
3930  *
3931  * @vmf: fault environment
3932  * @page: page to map
3933  *
3934  * Caller must take care of unlocking vmf->ptl, if vmf->pte is non-NULL on
3935  * return.
3936  *
3937  * Target users are page handler itself and implementations of
3938  * vm_ops->map_pages.
3939  *
3940  * Return: %0 on success, %VM_FAULT_ code in case of error.
3941  */
3942 vm_fault_t alloc_set_pte(struct vm_fault *vmf, struct page *page)
3943 {
3944         struct vm_area_struct *vma = vmf->vma;
3945         bool write = vmf->flags & FAULT_FLAG_WRITE;
3946         pte_t entry;
3947         vm_fault_t ret;
3948
3949         if (pmd_none(*vmf->pmd) && PageTransCompound(page) &&
3950                         compound_nr(compound_head(page)) == HPAGE_PMD_NR) {
3951                 ret = do_set_pmd(vmf, page);
3952                 if (ret != VM_FAULT_FALLBACK)
3953                         return ret;
3954         }
3955
3956 #ifdef CONFIG_FINEGRAINED_THP
3957         /* PageTransHuge cannot find hugepage if the page is not a head */
3958         if (PageTransCompound(page) &&
3959                         compound_nr(compound_head(page)) == HPAGE_CONT_PTE_NR) {
3960                 ret = arch_do_set_huge_pte(vmf, page);
3961                 if (ret != VM_FAULT_FALLBACK)
3962                         return ret;
3963         }
3964 #endif /* CONFIG_FINEGRAINED_THP */
3965
3966         if (!vmf->pte) {
3967                 ret = pte_alloc_one_map(vmf);
3968                 if (ret)
3969                         return ret;
3970         }
3971
3972         /* Re-check under ptl */
3973         if (unlikely(!pte_none(*vmf->pte))) {
3974                 update_mmu_tlb(vma, vmf->address, vmf->pte);
3975                 return VM_FAULT_NOPAGE;
3976         }
3977         /*
3978         if (!strcmp(current->comm, "org.tizen.nlp.s") || !strcmp(current->comm, "memps"))
3979                 pr_info("THP-wp: huge fault for addr (%lx) (%s) %s\n",
3980                         vmf->address, current->comm, __func__);
3981         */
3982         flush_icache_page(vma, page);
3983         entry = mk_pte(page, vma->vm_page_prot);
3984         entry = pte_sw_mkyoung(entry);
3985         if (write)
3986                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3987         /* copy-on-write page */
3988         if (write && !(vma->vm_flags & VM_SHARED)) {
3989                 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3990                 page_add_new_anon_rmap(page, vma, vmf->address, false);
3991                 lru_cache_add_inactive_or_unevictable(page, vma);
3992         } else {
3993                 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
3994                 page_add_file_rmap(page, false);
3995         }
3996         set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
3997
3998         /* no need to invalidate: a not-present page won't be cached */
3999         update_mmu_cache(vma, vmf->address, vmf->pte);
4000
4001         return 0;
4002 }
4003
4004
4005 /**
4006  * finish_fault - finish page fault once we have prepared the page to fault
4007  *
4008  * @vmf: structure describing the fault
4009  *
4010  * This function handles all that is needed to finish a page fault once the
4011  * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
4012  * given page, adds reverse page mapping, handles memcg charges and LRU
4013  * addition.
4014  *
4015  * The function expects the page to be locked and on success it consumes a
4016  * reference of a page being mapped (for the PTE which maps it).
4017  *
4018  * Return: %0 on success, %VM_FAULT_ code in case of error.
4019  */
4020 vm_fault_t finish_fault(struct vm_fault *vmf)
4021 {
4022         struct page *page;
4023         vm_fault_t ret = 0;
4024
4025         /* Did we COW the page? */
4026         if ((vmf->flags & FAULT_FLAG_WRITE) &&
4027             !(vmf->vma->vm_flags & VM_SHARED))
4028                 page = vmf->cow_page;
4029         else
4030                 page = vmf->page;
4031
4032         /*
4033          * check even for read faults because we might have lost our CoWed
4034          * page
4035          */
4036         if (!(vmf->vma->vm_flags & VM_SHARED))
4037                 ret = check_stable_address_space(vmf->vma->vm_mm);
4038         if (!ret)
4039                 ret = alloc_set_pte(vmf, page);
4040         if (vmf->pte)
4041                 pte_unmap_unlock(vmf->pte, vmf->ptl);
4042         return ret;
4043 }
4044
4045 static unsigned long fault_around_bytes __read_mostly =
4046         rounddown_pow_of_two(4096);
4047
4048 #ifdef CONFIG_DEBUG_FS
4049 static int fault_around_bytes_get(void *data, u64 *val)
4050 {
4051         *val = fault_around_bytes;
4052         return 0;
4053 }
4054
4055 /*
4056  * fault_around_bytes must be rounded down to the nearest page order as it's
4057  * what do_fault_around() expects to see.
4058  */
4059 static int fault_around_bytes_set(void *data, u64 val)
4060 {
4061         if (val / PAGE_SIZE > PTRS_PER_PTE)
4062                 return -EINVAL;
4063         if (val > PAGE_SIZE)
4064                 fault_around_bytes = rounddown_pow_of_two(val);
4065         else
4066                 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
4067         return 0;
4068 }
4069 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
4070                 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
4071
4072 static int __init fault_around_debugfs(void)
4073 {
4074         debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
4075                                    &fault_around_bytes_fops);
4076         return 0;
4077 }
4078 late_initcall(fault_around_debugfs);
4079 #endif
4080
4081 /*
4082  * do_fault_around() tries to map few pages around the fault address. The hope
4083  * is that the pages will be needed soon and this will lower the number of
4084  * faults to handle.
4085  *
4086  * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
4087  * not ready to be mapped: not up-to-date, locked, etc.
4088  *
4089  * This function is called with the page table lock taken. In the split ptlock
4090  * case the page table lock only protects only those entries which belong to
4091  * the page table corresponding to the fault address.
4092  *
4093  * This function doesn't cross the VMA boundaries, in order to call map_pages()
4094  * only once.
4095  *
4096  * fault_around_bytes defines how many bytes we'll try to map.
4097  * do_fault_around() expects it to be set to a power of two less than or equal
4098  * to PTRS_PER_PTE.
4099  *
4100  * The virtual address of the area that we map is naturally aligned to
4101  * fault_around_bytes rounded down to the machine page size
4102  * (and therefore to page order).  This way it's easier to guarantee
4103  * that we don't cross page table boundaries.
4104  */
4105 static vm_fault_t do_fault_around(struct vm_fault *vmf)
4106 {
4107         unsigned long address = vmf->address, nr_pages, mask;
4108         pgoff_t start_pgoff = vmf->pgoff;
4109         pgoff_t end_pgoff;
4110         int off;
4111         vm_fault_t ret = 0;
4112
4113         nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
4114         mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
4115
4116         vmf->address = max(address & mask, vmf->vma->vm_start);
4117         off = ((address - vmf->address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
4118         start_pgoff -= off;
4119
4120         /*
4121          *  end_pgoff is either the end of the page table, the end of
4122          *  the vma or nr_pages from start_pgoff, depending what is nearest.
4123          */
4124         end_pgoff = start_pgoff -
4125                 ((vmf->address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
4126                 PTRS_PER_PTE - 1;
4127         end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
4128                         start_pgoff + nr_pages - 1);
4129
4130         if (pmd_none(*vmf->pmd)) {
4131                 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
4132                 if (!vmf->prealloc_pte)
4133                         goto out;
4134                 smp_wmb(); /* See comment in __pte_alloc() */
4135         }
4136
4137         vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
4138
4139         /* Huge page is mapped? Page fault is solved */
4140         if (pmd_trans_huge(*vmf->pmd)) {
4141                 ret = VM_FAULT_NOPAGE;
4142                 goto out;
4143         }
4144
4145         /* ->map_pages() haven't done anything useful. Cold page cache? */
4146         if (!vmf->pte)
4147                 goto out;
4148
4149         /* check if the page fault is solved */
4150         vmf->pte -= (vmf->address >> PAGE_SHIFT) - (address >> PAGE_SHIFT);
4151         if (!pte_none(*vmf->pte))
4152                 ret = VM_FAULT_NOPAGE;
4153         pte_unmap_unlock(vmf->pte, vmf->ptl);
4154 out:
4155         vmf->address = address;
4156         vmf->pte = NULL;
4157         return ret;
4158 }
4159
4160 static vm_fault_t do_read_fault(struct vm_fault *vmf)
4161 {
4162         struct vm_area_struct *vma = vmf->vma;
4163         vm_fault_t ret = 0;
4164
4165         /*
4166          * Let's call ->map_pages() first and use ->fault() as fallback
4167          * if page by the offset is not ready to be mapped (cold cache or
4168          * something).
4169          */
4170         if (vma->vm_ops->map_pages && fault_around_bytes >> PAGE_SHIFT > 1) {
4171                 ret = do_fault_around(vmf);
4172                 if (ret)
4173                         return ret;
4174         }
4175
4176         ret = __do_fault(vmf);
4177         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4178                 return ret;
4179
4180         ret |= finish_fault(vmf);
4181         unlock_page(vmf->page);
4182         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4183                 put_page(vmf->page);
4184         return ret;
4185 }
4186
4187 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
4188 {
4189         struct vm_area_struct *vma = vmf->vma;
4190         vm_fault_t ret;
4191
4192         if (unlikely(anon_vma_prepare(vma)))
4193                 return VM_FAULT_OOM;
4194
4195         vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
4196         if (!vmf->cow_page)
4197                 return VM_FAULT_OOM;
4198
4199         if (mem_cgroup_charge(vmf->cow_page, vma->vm_mm, GFP_KERNEL)) {
4200                 put_page(vmf->cow_page);
4201                 return VM_FAULT_OOM;
4202         }
4203         cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL);
4204
4205         ret = __do_fault(vmf);
4206         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4207                 goto uncharge_out;
4208         if (ret & VM_FAULT_DONE_COW)
4209                 return ret;
4210         copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
4211         __SetPageUptodate(vmf->cow_page);
4212
4213         ret |= finish_fault(vmf);
4214         unlock_page(vmf->page);
4215         put_page(vmf->page);
4216         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4217                 goto uncharge_out;
4218         return ret;
4219 uncharge_out:
4220         put_page(vmf->cow_page);
4221         return ret;
4222 }
4223
4224 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
4225 {
4226         struct vm_area_struct *vma = vmf->vma;
4227         vm_fault_t ret, tmp;
4228
4229         ret = __do_fault(vmf);
4230         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4231                 return ret;
4232
4233         /*
4234          * Check if the backing address space wants to know that the page is
4235          * about to become writable
4236          */
4237         if (vma->vm_ops->page_mkwrite) {
4238                 unlock_page(vmf->page);
4239                 tmp = do_page_mkwrite(vmf);
4240                 if (unlikely(!tmp ||
4241                                 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
4242                         put_page(vmf->page);
4243                         return tmp;
4244                 }
4245         }
4246
4247         ret |= finish_fault(vmf);
4248         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
4249                                         VM_FAULT_RETRY))) {
4250                 unlock_page(vmf->page);
4251                 put_page(vmf->page);
4252                 return ret;
4253         }
4254
4255         ret |= fault_dirty_shared_page(vmf);
4256         return ret;
4257 }
4258
4259 /*
4260  * We enter with non-exclusive mmap_lock (to exclude vma changes,
4261  * but allow concurrent faults).
4262  * The mmap_lock may have been released depending on flags and our
4263  * return value.  See filemap_fault() and __lock_page_or_retry().
4264  * If mmap_lock is released, vma may become invalid (for example
4265  * by other thread calling munmap()).
4266  */
4267 static vm_fault_t do_fault(struct vm_fault *vmf)
4268 {
4269         struct vm_area_struct *vma = vmf->vma;
4270         struct mm_struct *vm_mm = vma->vm_mm;
4271         vm_fault_t ret;
4272
4273         /*
4274          * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
4275          */
4276         if (!vma->vm_ops->fault) {
4277                 /*
4278                  * If we find a migration pmd entry or a none pmd entry, which
4279                  * should never happen, return SIGBUS
4280                  */
4281                 if (unlikely(!pmd_present(*vmf->pmd)))
4282                         ret = VM_FAULT_SIGBUS;
4283                 else {
4284                         vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
4285                                                        vmf->pmd,
4286                                                        vmf->address,
4287                                                        &vmf->ptl);
4288                         /*
4289                          * Make sure this is not a temporary clearing of pte
4290                          * by holding ptl and checking again. A R/M/W update
4291                          * of pte involves: take ptl, clearing the pte so that
4292                          * we don't have concurrent modification by hardware
4293                          * followed by an update.
4294                          */
4295                         if (unlikely(pte_none(*vmf->pte)))
4296                                 ret = VM_FAULT_SIGBUS;
4297                         else
4298                                 ret = VM_FAULT_NOPAGE;
4299
4300                         pte_unmap_unlock(vmf->pte, vmf->ptl);
4301                 }
4302         } else if (!(vmf->flags & FAULT_FLAG_WRITE))
4303                 ret = do_read_fault(vmf);
4304         else if (!(vma->vm_flags & VM_SHARED))
4305                 ret = do_cow_fault(vmf);
4306         else
4307                 ret = do_shared_fault(vmf);
4308
4309         /* preallocated pagetable is unused: free it */
4310         if (vmf->prealloc_pte) {
4311                 pte_free(vm_mm, vmf->prealloc_pte);
4312                 vmf->prealloc_pte = NULL;
4313         }
4314         return ret;
4315 }
4316
4317 static int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
4318                                 unsigned long addr, int page_nid,
4319                                 int *flags)
4320 {
4321         get_page(page);
4322
4323         count_vm_numa_event(NUMA_HINT_FAULTS);
4324         if (page_nid == numa_node_id()) {
4325                 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
4326                 *flags |= TNF_FAULT_LOCAL;
4327         }
4328
4329         return mpol_misplaced(page, vma, addr);
4330 }
4331
4332 static vm_fault_t do_numa_page(struct vm_fault *vmf)
4333 {
4334         struct vm_area_struct *vma = vmf->vma;
4335         struct page *page = NULL;
4336         int page_nid = NUMA_NO_NODE;
4337         int last_cpupid;
4338         int target_nid;
4339         bool migrated = false;
4340         pte_t pte, old_pte;
4341         bool was_writable = pte_savedwrite(vmf->orig_pte);
4342         int flags = 0;
4343
4344         /*
4345          * The "pte" at this point cannot be used safely without
4346          * validation through pte_unmap_same(). It's of NUMA type but
4347          * the pfn may be screwed if the read is non atomic.
4348          */
4349         vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
4350         spin_lock(vmf->ptl);
4351         if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4352                 pte_unmap_unlock(vmf->pte, vmf->ptl);
4353                 goto out;
4354         }
4355
4356         /*
4357          * Make it present again, Depending on how arch implementes non
4358          * accessible ptes, some can allow access by kernel mode.
4359          */
4360         old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte);
4361         pte = pte_modify(old_pte, vma->vm_page_prot);
4362         pte = pte_mkyoung(pte);
4363         if (was_writable)
4364                 pte = pte_mkwrite(pte);
4365         ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte);
4366         update_mmu_cache(vma, vmf->address, vmf->pte);
4367
4368         page = vm_normal_page(vma, vmf->address, pte);
4369         if (!page) {
4370                 pte_unmap_unlock(vmf->pte, vmf->ptl);
4371                 return 0;
4372         }
4373
4374         /* TODO: handle PTE-mapped THP */
4375         if (PageCompound(page)) {
4376                 pte_unmap_unlock(vmf->pte, vmf->ptl);
4377                 return 0;
4378         }
4379
4380         /*
4381          * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
4382          * much anyway since they can be in shared cache state. This misses
4383          * the case where a mapping is writable but the process never writes
4384          * to it but pte_write gets cleared during protection updates and
4385          * pte_dirty has unpredictable behaviour between PTE scan updates,
4386          * background writeback, dirty balancing and application behaviour.
4387          */
4388         if (!pte_write(pte))
4389                 flags |= TNF_NO_GROUP;
4390
4391         /*
4392          * Flag if the page is shared between multiple address spaces. This
4393          * is later used when determining whether to group tasks together
4394          */
4395         if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
4396                 flags |= TNF_SHARED;
4397
4398         last_cpupid = page_cpupid_last(page);
4399         page_nid = page_to_nid(page);
4400         target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
4401                         &flags);
4402         pte_unmap_unlock(vmf->pte, vmf->ptl);
4403         if (target_nid == NUMA_NO_NODE) {
4404                 put_page(page);
4405                 goto out;
4406         }
4407
4408         /* Migrate to the requested node */
4409         migrated = migrate_misplaced_page(page, vma, target_nid);
4410         if (migrated) {
4411                 page_nid = target_nid;
4412                 flags |= TNF_MIGRATED;
4413         } else
4414                 flags |= TNF_MIGRATE_FAIL;
4415
4416 out:
4417         if (page_nid != NUMA_NO_NODE)
4418                 task_numa_fault(last_cpupid, page_nid, 1, flags);
4419         return 0;
4420 }
4421
4422 #ifdef CONFIG_FINEGRAINED_THP
4423 static inline vm_fault_t __do_huge_pmd_anonymous_page(struct vm_fault *vmf)
4424 {
4425         //struct timespec64 ts, te, diff;
4426         int ret;
4427
4428 #ifdef CONFIG_FINEGRAINED_THP
4429         return VM_FAULT_FALLBACK;
4430 #endif
4431
4432         //ktime_get_ts64(&ts);
4433         ret = do_huge_pmd_anonymous_page(vmf);
4434         /*
4435         ktime_get_ts64(&te);
4436         diff = timespec64_sub(te, ts);
4437         if (!(ret & VM_FAULT_FALLBACK))
4438                 pr_info("THP-fault: 2MB hugepage takes %lu nsecs\n",
4439                                 timespec64_to_ns(&diff));
4440         */
4441         return ret;
4442 }
4443 #endif /* CONFIG_FINEGRAINED_THP */
4444
4445 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4446 {
4447         if (vma_is_anonymous(vmf->vma))
4448 #ifdef CONFIG_FINEGRAINED_THP
4449                 return __do_huge_pmd_anonymous_page(vmf);
4450 #else
4451                 return do_huge_pmd_anonymous_page(vmf);
4452 #endif
4453         if (vmf->vma->vm_ops->huge_fault)
4454                 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4455         return VM_FAULT_FALLBACK;
4456 }
4457
4458 /* `inline' is required to avoid gcc 4.1.2 build error */
4459 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf, pmd_t orig_pmd)
4460 {
4461         if (vma_is_anonymous(vmf->vma)) {
4462                 if (userfaultfd_huge_pmd_wp(vmf->vma, orig_pmd))
4463                         return handle_userfault(vmf, VM_UFFD_WP);
4464                 return do_huge_pmd_wp_page(vmf, orig_pmd);
4465         }
4466         if (vmf->vma->vm_ops->huge_fault) {
4467                 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4468
4469                 if (!(ret & VM_FAULT_FALLBACK))
4470                         return ret;
4471         }
4472
4473         /* COW or write-notify handled on pte level: split pmd. */
4474         __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4475
4476         return VM_FAULT_FALLBACK;
4477 }
4478
4479 #ifdef CONFIG_FINEGRAINED_THP
4480 vm_fault_t wp_huge_pte(struct vm_fault *vmf, pte_t orig_pte);
4481 #endif /* CONFIG_FINEGRAINED_THP */
4482
4483 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4484 {
4485 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) &&                     \
4486         defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4487         /* No support for anonymous transparent PUD pages yet */
4488         if (vma_is_anonymous(vmf->vma))
4489                 goto split;
4490         if (vmf->vma->vm_ops->huge_fault) {
4491                 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4492
4493                 if (!(ret & VM_FAULT_FALLBACK))
4494                         return ret;
4495         }
4496 split:
4497         /* COW or write-notify not handled on PUD level: split pud.*/
4498         __split_huge_pud(vmf->vma, vmf->pud, vmf->address);
4499 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4500         return VM_FAULT_FALLBACK;
4501 }
4502
4503 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4504 {
4505 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4506         /* No support for anonymous transparent PUD pages yet */
4507         if (vma_is_anonymous(vmf->vma))
4508                 return VM_FAULT_FALLBACK;
4509         if (vmf->vma->vm_ops->huge_fault)
4510                 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4511 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4512         return VM_FAULT_FALLBACK;
4513 }
4514
4515 /*
4516  * These routines also need to handle stuff like marking pages dirty
4517  * and/or accessed for architectures that don't do it in hardware (most
4518  * RISC architectures).  The early dirtying is also good on the i386.
4519  *
4520  * There is also a hook called "update_mmu_cache()" that architectures
4521  * with external mmu caches can use to update those (ie the Sparc or
4522  * PowerPC hashed page tables that act as extended TLBs).
4523  *
4524  * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
4525  * concurrent faults).
4526  *
4527  * The mmap_lock may have been released depending on flags and our return value.
4528  * See filemap_fault() and __lock_page_or_retry().
4529  */
4530 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4531 {
4532         pte_t entry;
4533
4534         if (unlikely(pmd_none(*vmf->pmd))) {
4535                 /*
4536                  * Leave __pte_alloc() until later: because vm_ops->fault may
4537                  * want to allocate huge page, and if we expose page table
4538                  * for an instant, it will be difficult to retract from
4539                  * concurrent faults and from rmap lookups.
4540                  */
4541                 vmf->pte = NULL;
4542         } else {
4543                 /* See comment in pte_alloc_one_map() */
4544                 if (pmd_devmap_trans_unstable(vmf->pmd))
4545                         return 0;
4546                 /*
4547                  * A regular pmd is established and it can't morph into a huge
4548                  * pmd from under us anymore at this point because we hold the
4549                  * mmap_lock read mode and khugepaged takes it in write mode.
4550                  * So now it's safe to run pte_offset_map().
4551                  */
4552                 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4553                 vmf->orig_pte = *vmf->pte;
4554
4555                 /*
4556                  * some architectures can have larger ptes than wordsize,
4557                  * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4558                  * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4559                  * accesses.  The code below just needs a consistent view
4560                  * for the ifs and we later double check anyway with the
4561                  * ptl lock held. So here a barrier will do.
4562                  */
4563                 barrier();
4564                 if (pte_none(vmf->orig_pte)) {
4565                         pte_unmap(vmf->pte);
4566                         vmf->pte = NULL;
4567                 }
4568         }
4569
4570         if (!vmf->pte) {
4571                 if (vma_is_anonymous(vmf->vma))
4572                         return do_anonymous_page(vmf);
4573                 else
4574                         return do_fault(vmf);
4575         }
4576
4577         if (!pte_present(vmf->orig_pte))
4578                 return do_swap_page(vmf);
4579
4580         if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4581                 return do_numa_page(vmf);
4582
4583         vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4584         spin_lock(vmf->ptl);
4585         entry = vmf->orig_pte;
4586         if (unlikely(!pte_same(*vmf->pte, entry))) {
4587                 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
4588                 goto unlock;
4589         }
4590         if (vmf->flags & FAULT_FLAG_WRITE) {
4591                 if (!pte_write(entry)) {
4592                         int ret = arch_do_wp_page(vmf, entry);
4593
4594                         if (!(ret & VM_FAULT_FALLBACK))
4595                                 return ret;
4596                         return do_wp_page(vmf);
4597                 }
4598                 if (arch_huge_pte_set_accessed(vmf, entry))
4599                         goto unlock;
4600                 entry = pte_mkdirty(entry);
4601         }
4602         entry = pte_mkyoung(entry);
4603         if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4604                                 vmf->flags & FAULT_FLAG_WRITE)) {
4605                 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4606         } else {
4607                 /* Skip spurious TLB flush for retried page fault */
4608                 if (vmf->flags & FAULT_FLAG_TRIED)
4609                         goto unlock;
4610                 /*
4611                  * This is needed only for protection faults but the arch code
4612                  * is not yet telling us if this is a protection fault or not.
4613                  * This still avoids useless tlb flushes for .text page faults
4614                  * with threads.
4615                  */
4616                 if (vmf->flags & FAULT_FLAG_WRITE)
4617                         flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4618         }
4619 unlock:
4620         pte_unmap_unlock(vmf->pte, vmf->ptl);
4621         return 0;
4622 }
4623
4624 /*
4625  * By the time we get here, we already hold the mm semaphore
4626  *
4627  * The mmap_lock may have been released depending on flags and our
4628  * return value.  See filemap_fault() and __lock_page_or_retry().
4629  */
4630 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
4631                 unsigned long address, unsigned int flags)
4632 {
4633         struct vm_fault vmf = {
4634                 .vma = vma,
4635                 .address = address & PAGE_MASK,
4636                 .flags = flags,
4637                 .pgoff = linear_page_index(vma, address),
4638                 .gfp_mask = __get_fault_gfp_mask(vma),
4639         };
4640         unsigned int dirty = flags & FAULT_FLAG_WRITE;
4641         struct mm_struct *mm = vma->vm_mm;
4642         pgd_t *pgd;
4643         p4d_t *p4d;
4644         vm_fault_t ret;
4645
4646         pgd = pgd_offset(mm, address);
4647         p4d = p4d_alloc(mm, pgd, address);
4648         if (!p4d)
4649                 return VM_FAULT_OOM;
4650
4651         vmf.pud = pud_alloc(mm, p4d, address);
4652         if (!vmf.pud)
4653                 return VM_FAULT_OOM;
4654 retry_pud:
4655         if (pud_none(*vmf.pud) && __transparent_hugepage_enabled(vma)) {
4656                 ret = create_huge_pud(&vmf);
4657                 if (!(ret & VM_FAULT_FALLBACK))
4658                         return ret;
4659         } else {
4660                 pud_t orig_pud = *vmf.pud;
4661
4662                 barrier();
4663                 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
4664
4665                         /* NUMA case for anonymous PUDs would go here */
4666
4667                         if (dirty && !pud_write(orig_pud)) {
4668                                 ret = wp_huge_pud(&vmf, orig_pud);
4669                                 if (!(ret & VM_FAULT_FALLBACK))
4670                                         return ret;
4671                         } else {
4672                                 huge_pud_set_accessed(&vmf, orig_pud);
4673                                 return 0;
4674                         }
4675                 }
4676         }
4677
4678         vmf.pmd = pmd_alloc(mm, vmf.pud, address);
4679         if (!vmf.pmd)
4680                 return VM_FAULT_OOM;
4681
4682         /* Huge pud page fault raced with pmd_alloc? */
4683         if (pud_trans_unstable(vmf.pud))
4684                 goto retry_pud;
4685
4686         if (pmd_none(*vmf.pmd) && __transparent_hugepage_enabled(vma)) {
4687                 ret = create_huge_pmd(&vmf);
4688                 if (!(ret & VM_FAULT_FALLBACK))
4689                         return ret;
4690         } else {
4691                 pmd_t orig_pmd = *vmf.pmd;
4692
4693                 barrier();
4694                 if (unlikely(is_swap_pmd(orig_pmd))) {
4695                         VM_BUG_ON(thp_migration_supported() &&
4696                                           !is_pmd_migration_entry(orig_pmd));
4697                         if (is_pmd_migration_entry(orig_pmd))
4698                                 pmd_migration_entry_wait(mm, vmf.pmd);
4699                         return 0;
4700                 }
4701                 if (pmd_trans_huge(orig_pmd) || pmd_devmap(orig_pmd)) {
4702                         if (pmd_protnone(orig_pmd) && vma_is_accessible(vma))
4703                                 return do_huge_pmd_numa_page(&vmf, orig_pmd);
4704
4705                         if (dirty && !pmd_write(orig_pmd)) {
4706                                 ret = wp_huge_pmd(&vmf, orig_pmd);
4707                                 if (!(ret & VM_FAULT_FALLBACK))
4708                                         return ret;
4709                         } else {
4710                                 huge_pmd_set_accessed(&vmf, orig_pmd);
4711                                 return 0;
4712                         }
4713                 }
4714         }
4715
4716         return handle_pte_fault(&vmf);
4717 }
4718
4719 /**
4720  * mm_account_fault - Do page fault accountings
4721  *
4722  * @regs: the pt_regs struct pointer.  When set to NULL, will skip accounting
4723  *        of perf event counters, but we'll still do the per-task accounting to
4724  *        the task who triggered this page fault.
4725  * @address: the faulted address.
4726  * @flags: the fault flags.
4727  * @ret: the fault retcode.
4728  *
4729  * This will take care of most of the page fault accountings.  Meanwhile, it
4730  * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
4731  * updates.  However note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
4732  * still be in per-arch page fault handlers at the entry of page fault.
4733  */
4734 static inline void mm_account_fault(struct pt_regs *regs,
4735                                     unsigned long address, unsigned int flags,
4736                                     vm_fault_t ret)
4737 {
4738         bool major;
4739
4740         /*
4741          * We don't do accounting for some specific faults:
4742          *
4743          * - Unsuccessful faults (e.g. when the address wasn't valid).  That
4744          *   includes arch_vma_access_permitted() failing before reaching here.
4745          *   So this is not a "this many hardware page faults" counter.  We
4746          *   should use the hw profiling for that.
4747          *
4748          * - Incomplete faults (VM_FAULT_RETRY).  They will only be counted
4749          *   once they're completed.
4750          */
4751         if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY))
4752                 return;
4753
4754         /*
4755          * We define the fault as a major fault when the final successful fault
4756          * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
4757          * handle it immediately previously).
4758          */
4759         major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
4760
4761         if (major)
4762                 current->maj_flt++;
4763         else
4764                 current->min_flt++;
4765
4766         /*
4767          * If the fault is done for GUP, regs will be NULL.  We only do the
4768          * accounting for the per thread fault counters who triggered the
4769          * fault, and we skip the perf event updates.
4770          */
4771         if (!regs)
4772                 return;
4773
4774         if (major)
4775                 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
4776         else
4777                 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
4778 }
4779
4780 /*
4781  * By the time we get here, we already hold the mm semaphore
4782  *
4783  * The mmap_lock may have been released depending on flags and our
4784  * return value.  See filemap_fault() and __lock_page_or_retry().
4785  */
4786 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
4787                            unsigned int flags, struct pt_regs *regs)
4788 {
4789         vm_fault_t ret;
4790
4791         __set_current_state(TASK_RUNNING);
4792
4793         count_vm_event(PGFAULT);
4794         count_memcg_event_mm(vma->vm_mm, PGFAULT);
4795
4796         /* do counter updates before entering really critical section. */
4797         check_sync_rss_stat(current);
4798
4799         if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
4800                                             flags & FAULT_FLAG_INSTRUCTION,
4801                                             flags & FAULT_FLAG_REMOTE))
4802                 return VM_FAULT_SIGSEGV;
4803
4804         /*
4805          * Enable the memcg OOM handling for faults triggered in user
4806          * space.  Kernel faults are handled more gracefully.
4807          */
4808         if (flags & FAULT_FLAG_USER)
4809                 mem_cgroup_enter_user_fault();
4810
4811         if (unlikely(is_vm_hugetlb_page(vma)))
4812                 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
4813         else
4814                 ret = __handle_mm_fault(vma, address, flags);
4815
4816         if (flags & FAULT_FLAG_USER) {
4817                 mem_cgroup_exit_user_fault();
4818                 /*
4819                  * The task may have entered a memcg OOM situation but
4820                  * if the allocation error was handled gracefully (no
4821                  * VM_FAULT_OOM), there is no need to kill anything.
4822                  * Just clean up the OOM state peacefully.
4823                  */
4824                 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
4825                         mem_cgroup_oom_synchronize(false);
4826         }
4827
4828         mm_account_fault(regs, address, flags, ret);
4829
4830         return ret;
4831 }
4832 EXPORT_SYMBOL_GPL(handle_mm_fault);
4833
4834 #ifndef __PAGETABLE_P4D_FOLDED
4835 /*
4836  * Allocate p4d page table.
4837  * We've already handled the fast-path in-line.
4838  */
4839 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
4840 {
4841         p4d_t *new = p4d_alloc_one(mm, address);
4842         if (!new)
4843                 return -ENOMEM;
4844
4845         smp_wmb(); /* See comment in __pte_alloc */
4846
4847         spin_lock(&mm->page_table_lock);
4848         if (pgd_present(*pgd))          /* Another has populated it */
4849                 p4d_free(mm, new);
4850         else
4851                 pgd_populate(mm, pgd, new);
4852         spin_unlock(&mm->page_table_lock);
4853         return 0;
4854 }
4855 #endif /* __PAGETABLE_P4D_FOLDED */
4856
4857 #ifndef __PAGETABLE_PUD_FOLDED
4858 /*
4859  * Allocate page upper directory.
4860  * We've already handled the fast-path in-line.
4861  */
4862 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
4863 {
4864         pud_t *new = pud_alloc_one(mm, address);
4865         if (!new)
4866                 return -ENOMEM;
4867
4868         smp_wmb(); /* See comment in __pte_alloc */
4869
4870         spin_lock(&mm->page_table_lock);
4871         if (!p4d_present(*p4d)) {
4872                 mm_inc_nr_puds(mm);
4873                 p4d_populate(mm, p4d, new);
4874         } else  /* Another has populated it */
4875                 pud_free(mm, new);
4876         spin_unlock(&mm->page_table_lock);
4877         return 0;
4878 }
4879 #endif /* __PAGETABLE_PUD_FOLDED */
4880
4881 #ifndef __PAGETABLE_PMD_FOLDED
4882 /*
4883  * Allocate page middle directory.
4884  * We've already handled the fast-path in-line.
4885  */
4886 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
4887 {
4888         spinlock_t *ptl;
4889         pmd_t *new = pmd_alloc_one(mm, address);
4890         if (!new)
4891                 return -ENOMEM;
4892
4893         smp_wmb(); /* See comment in __pte_alloc */
4894
4895         ptl = pud_lock(mm, pud);
4896         if (!pud_present(*pud)) {
4897                 mm_inc_nr_pmds(mm);
4898                 pud_populate(mm, pud, new);
4899         } else  /* Another has populated it */
4900                 pmd_free(mm, new);
4901         spin_unlock(ptl);
4902         return 0;
4903 }
4904 #endif /* __PAGETABLE_PMD_FOLDED */
4905
4906 int follow_invalidate_pte(struct mm_struct *mm, unsigned long address,
4907                           struct mmu_notifier_range *range, pte_t **ptepp,
4908                           pmd_t **pmdpp, spinlock_t **ptlp)
4909 {
4910         pgd_t *pgd;
4911         p4d_t *p4d;
4912         pud_t *pud;
4913         pmd_t *pmd;
4914         pte_t *ptep;
4915
4916         pgd = pgd_offset(mm, address);
4917         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
4918                 goto out;
4919
4920         p4d = p4d_offset(pgd, address);
4921         if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
4922                 goto out;
4923
4924         pud = pud_offset(p4d, address);
4925         if (pud_none(*pud) || unlikely(pud_bad(*pud)))
4926                 goto out;
4927
4928         pmd = pmd_offset(pud, address);
4929         VM_BUG_ON(pmd_trans_huge(*pmd));
4930
4931         if (pmd_huge(*pmd)) {
4932                 if (!pmdpp)
4933                         goto out;
4934
4935                 if (range) {
4936                         mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0,
4937                                                 NULL, mm, address & PMD_MASK,
4938                                                 (address & PMD_MASK) + PMD_SIZE);
4939                         mmu_notifier_invalidate_range_start(range);
4940                 }
4941                 *ptlp = pmd_lock(mm, pmd);
4942                 if (pmd_huge(*pmd)) {
4943                         *pmdpp = pmd;
4944                         return 0;
4945                 }
4946                 spin_unlock(*ptlp);
4947                 if (range)
4948                         mmu_notifier_invalidate_range_end(range);
4949         }
4950
4951         if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
4952                 goto out;
4953
4954         if (range) {
4955                 mmu_notifier_range_init(range, MMU_NOTIFY_CLEAR, 0, NULL, mm,
4956                                         address & PAGE_MASK,
4957                                         (address & PAGE_MASK) + PAGE_SIZE);
4958                 mmu_notifier_invalidate_range_start(range);
4959         }
4960         ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
4961         if (!pte_present(*ptep))
4962                 goto unlock;
4963         *ptepp = ptep;
4964         return 0;
4965 unlock:
4966         pte_unmap_unlock(ptep, *ptlp);
4967         if (range)
4968                 mmu_notifier_invalidate_range_end(range);
4969 out:
4970         return -EINVAL;
4971 }
4972
4973 /**
4974  * follow_pte - look up PTE at a user virtual address
4975  * @mm: the mm_struct of the target address space
4976  * @address: user virtual address
4977  * @ptepp: location to store found PTE
4978  * @ptlp: location to store the lock for the PTE
4979  *
4980  * On a successful return, the pointer to the PTE is stored in @ptepp;
4981  * the corresponding lock is taken and its location is stored in @ptlp.
4982  * The contents of the PTE are only stable until @ptlp is released;
4983  * any further use, if any, must be protected against invalidation
4984  * with MMU notifiers.
4985  *
4986  * Only IO mappings and raw PFN mappings are allowed.  The mmap semaphore
4987  * should be taken for read.
4988  *
4989  * KVM uses this function.  While it is arguably less bad than ``follow_pfn``,
4990  * it is not a good general-purpose API.
4991  *
4992  * Return: zero on success, -ve otherwise.
4993  */
4994 int follow_pte(struct mm_struct *mm, unsigned long address,
4995                pte_t **ptepp, spinlock_t **ptlp)
4996 {
4997         return follow_invalidate_pte(mm, address, NULL, ptepp, NULL, ptlp);
4998 }
4999 EXPORT_SYMBOL_GPL(follow_pte);
5000
5001 /**
5002  * follow_pfn - look up PFN at a user virtual address
5003  * @vma: memory mapping
5004  * @address: user virtual address
5005  * @pfn: location to store found PFN
5006  *
5007  * Only IO mappings and raw PFN mappings are allowed.
5008  *
5009  * This function does not allow the caller to read the permissions
5010  * of the PTE.  Do not use it.
5011  *
5012  * Return: zero and the pfn at @pfn on success, -ve otherwise.
5013  */
5014 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
5015         unsigned long *pfn)
5016 {
5017         int ret = -EINVAL;
5018         spinlock_t *ptl;
5019         pte_t *ptep;
5020
5021         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5022                 return ret;
5023
5024         ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
5025         if (ret)
5026                 return ret;
5027         *pfn = pte_pfn(*ptep);
5028         pte_unmap_unlock(ptep, ptl);
5029         return 0;
5030 }
5031 EXPORT_SYMBOL(follow_pfn);
5032
5033 #ifdef CONFIG_HAVE_IOREMAP_PROT
5034 int follow_phys(struct vm_area_struct *vma,
5035                 unsigned long address, unsigned int flags,
5036                 unsigned long *prot, resource_size_t *phys)
5037 {
5038         int ret = -EINVAL;
5039         pte_t *ptep, pte;
5040         spinlock_t *ptl;
5041
5042         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5043                 goto out;
5044
5045         if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
5046                 goto out;
5047         pte = *ptep;
5048
5049         if ((flags & FOLL_WRITE) && !pte_write(pte))
5050                 goto unlock;
5051
5052         *prot = pgprot_val(pte_pgprot(pte));
5053         *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5054
5055         ret = 0;
5056 unlock:
5057         pte_unmap_unlock(ptep, ptl);
5058 out:
5059         return ret;
5060 }
5061
5062 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
5063                         void *buf, int len, int write)
5064 {
5065         resource_size_t phys_addr;
5066         unsigned long prot = 0;
5067         void __iomem *maddr;
5068         int offset = addr & (PAGE_SIZE-1);
5069
5070         if (follow_phys(vma, addr, write, &prot, &phys_addr))
5071                 return -EINVAL;
5072
5073         maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
5074         if (!maddr)
5075                 return -ENOMEM;
5076
5077         if (write)
5078                 memcpy_toio(maddr + offset, buf, len);
5079         else
5080                 memcpy_fromio(buf, maddr + offset, len);
5081         iounmap(maddr);
5082
5083         return len;
5084 }
5085 EXPORT_SYMBOL_GPL(generic_access_phys);
5086 #endif
5087
5088 /*
5089  * Access another process' address space as given in mm.  If non-NULL, use the
5090  * given task for page fault accounting.
5091  */
5092 int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
5093                 unsigned long addr, void *buf, int len, unsigned int gup_flags)
5094 {
5095         struct vm_area_struct *vma;
5096         void *old_buf = buf;
5097         int write = gup_flags & FOLL_WRITE;
5098
5099         if (mmap_read_lock_killable(mm))
5100                 return 0;
5101
5102         /* ignore errors, just check how much was successfully transferred */
5103         while (len) {
5104                 int bytes, ret, offset;
5105                 void *maddr;
5106                 struct page *page = NULL;
5107
5108                 ret = get_user_pages_remote(mm, addr, 1,
5109                                 gup_flags, &page, &vma, NULL);
5110                 if (ret <= 0) {
5111 #ifndef CONFIG_HAVE_IOREMAP_PROT
5112                         break;
5113 #else
5114                         /*
5115                          * Check if this is a VM_IO | VM_PFNMAP VMA, which
5116                          * we can access using slightly different code.
5117                          */
5118                         vma = find_vma(mm, addr);
5119                         if (!vma || vma->vm_start > addr)
5120                                 break;
5121                         if (vma->vm_ops && vma->vm_ops->access)
5122                                 ret = vma->vm_ops->access(vma, addr, buf,
5123                                                           len, write);
5124                         if (ret <= 0)
5125                                 break;
5126                         bytes = ret;
5127 #endif
5128                 } else {
5129                         bytes = len;
5130                         offset = addr & (PAGE_SIZE-1);
5131                         if (bytes > PAGE_SIZE-offset)
5132                                 bytes = PAGE_SIZE-offset;
5133
5134                         maddr = kmap(page);
5135                         if (write) {
5136                                 copy_to_user_page(vma, page, addr,
5137                                                   maddr + offset, buf, bytes);
5138                                 set_page_dirty_lock(page);
5139                         } else {
5140                                 copy_from_user_page(vma, page, addr,
5141                                                     buf, maddr + offset, bytes);
5142                         }
5143                         kunmap(page);
5144                         put_page(page);
5145                 }
5146                 len -= bytes;
5147                 buf += bytes;
5148                 addr += bytes;
5149         }
5150         mmap_read_unlock(mm);
5151
5152         return buf - old_buf;
5153 }
5154
5155 /**
5156  * access_remote_vm - access another process' address space
5157  * @mm:         the mm_struct of the target address space
5158  * @addr:       start address to access
5159  * @buf:        source or destination buffer
5160  * @len:        number of bytes to transfer
5161  * @gup_flags:  flags modifying lookup behaviour
5162  *
5163  * The caller must hold a reference on @mm.
5164  *
5165  * Return: number of bytes copied from source to destination.
5166  */
5167 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
5168                 void *buf, int len, unsigned int gup_flags)
5169 {
5170         return __access_remote_vm(NULL, mm, addr, buf, len, gup_flags);
5171 }
5172
5173 /*
5174  * Access another process' address space.
5175  * Source/target buffer must be kernel space,
5176  * Do not walk the page table directly, use get_user_pages
5177  */
5178 int access_process_vm(struct task_struct *tsk, unsigned long addr,
5179                 void *buf, int len, unsigned int gup_flags)
5180 {
5181         struct mm_struct *mm;
5182         int ret;
5183
5184         mm = get_task_mm(tsk);
5185         if (!mm)
5186                 return 0;
5187
5188         ret = __access_remote_vm(tsk, mm, addr, buf, len, gup_flags);
5189
5190         mmput(mm);
5191
5192         return ret;
5193 }
5194 EXPORT_SYMBOL_GPL(access_process_vm);
5195
5196 /*
5197  * Print the name of a VMA.
5198  */
5199 void print_vma_addr(char *prefix, unsigned long ip)
5200 {
5201         struct mm_struct *mm = current->mm;
5202         struct vm_area_struct *vma;
5203
5204         /*
5205          * we might be running from an atomic context so we cannot sleep
5206          */
5207         if (!mmap_read_trylock(mm))
5208                 return;
5209
5210         vma = find_vma(mm, ip);
5211         if (vma && vma->vm_file) {
5212                 struct file *f = vma->vm_file;
5213                 char *buf = (char *)__get_free_page(GFP_NOWAIT);
5214                 if (buf) {
5215                         char *p;
5216
5217                         p = file_path(f, buf, PAGE_SIZE);
5218                         if (IS_ERR(p))
5219                                 p = "?";
5220                         printk("%s%s[%lx+%lx]", prefix, kbasename(p),
5221                                         vma->vm_start,
5222                                         vma->vm_end - vma->vm_start);
5223                         free_page((unsigned long)buf);
5224                 }
5225         }
5226         mmap_read_unlock(mm);
5227 }
5228
5229 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5230 void __might_fault(const char *file, int line)
5231 {
5232         /*
5233          * Some code (nfs/sunrpc) uses socket ops on kernel memory while
5234          * holding the mmap_lock, this is safe because kernel memory doesn't
5235          * get paged out, therefore we'll never actually fault, and the
5236          * below annotations will generate false positives.
5237          */
5238         if (uaccess_kernel())
5239                 return;
5240         if (pagefault_disabled())
5241                 return;
5242         __might_sleep(file, line, 0);
5243 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5244         if (current->mm)
5245                 might_lock_read(&current->mm->mmap_lock);
5246 #endif
5247 }
5248 EXPORT_SYMBOL(__might_fault);
5249 #endif
5250
5251 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
5252 /*
5253  * Process all subpages of the specified huge page with the specified
5254  * operation.  The target subpage will be processed last to keep its
5255  * cache lines hot.
5256  */
5257 static inline void process_huge_page(
5258         unsigned long addr_hint, unsigned int pages_per_huge_page,
5259         void (*process_subpage)(unsigned long addr, int idx, void *arg),
5260         void *arg)
5261 {
5262         int i, n, base, l;
5263         unsigned long addr = addr_hint &
5264                 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5265
5266         /* Process target subpage last to keep its cache lines hot */
5267         might_sleep();
5268         n = (addr_hint - addr) / PAGE_SIZE;
5269         if (2 * n <= pages_per_huge_page) {
5270                 /* If target subpage in first half of huge page */
5271                 base = 0;
5272                 l = n;
5273                 /* Process subpages at the end of huge page */
5274                 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
5275                         cond_resched();
5276                         process_subpage(addr + i * PAGE_SIZE, i, arg);
5277                 }
5278         } else {
5279                 /* If target subpage in second half of huge page */
5280                 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
5281                 l = pages_per_huge_page - n;
5282                 /* Process subpages at the begin of huge page */
5283                 for (i = 0; i < base; i++) {
5284                         cond_resched();
5285                         process_subpage(addr + i * PAGE_SIZE, i, arg);
5286                 }
5287         }
5288         /*
5289          * Process remaining subpages in left-right-left-right pattern
5290          * towards the target subpage
5291          */
5292         for (i = 0; i < l; i++) {
5293                 int left_idx = base + i;
5294                 int right_idx = base + 2 * l - 1 - i;
5295
5296                 cond_resched();
5297                 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
5298                 cond_resched();
5299                 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
5300         }
5301 }
5302
5303 static void clear_gigantic_page(struct page *page,
5304                                 unsigned long addr,
5305                                 unsigned int pages_per_huge_page)
5306 {
5307         int i;
5308         struct page *p = page;
5309
5310         might_sleep();
5311         for (i = 0; i < pages_per_huge_page;
5312              i++, p = mem_map_next(p, page, i)) {
5313                 cond_resched();
5314                 clear_user_highpage(p, addr + i * PAGE_SIZE);
5315         }
5316 }
5317
5318 static void clear_subpage(unsigned long addr, int idx, void *arg)
5319 {
5320         struct page *page = arg;
5321
5322         clear_user_highpage(page + idx, addr);
5323 }
5324
5325 void clear_huge_page(struct page *page,
5326                      unsigned long addr_hint, unsigned int pages_per_huge_page)
5327 {
5328         unsigned long addr = addr_hint &
5329                 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5330
5331         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5332                 clear_gigantic_page(page, addr, pages_per_huge_page);
5333                 return;
5334         }
5335
5336         process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
5337 }
5338
5339 static void copy_user_gigantic_page(struct page *dst, struct page *src,
5340                                     unsigned long addr,
5341                                     struct vm_area_struct *vma,
5342                                     unsigned int pages_per_huge_page)
5343 {
5344         int i;
5345         struct page *dst_base = dst;
5346         struct page *src_base = src;
5347
5348         for (i = 0; i < pages_per_huge_page; ) {
5349                 cond_resched();
5350                 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
5351
5352                 i++;
5353                 dst = mem_map_next(dst, dst_base, i);
5354                 src = mem_map_next(src, src_base, i);
5355         }
5356 }
5357
5358 struct copy_subpage_arg {
5359         struct page *dst;
5360         struct page *src;
5361         struct vm_area_struct *vma;
5362 };
5363
5364 static void copy_subpage(unsigned long addr, int idx, void *arg)
5365 {
5366         struct copy_subpage_arg *copy_arg = arg;
5367
5368         copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
5369                            addr, copy_arg->vma);
5370 }
5371
5372 void copy_user_huge_page(struct page *dst, struct page *src,
5373                          unsigned long addr_hint, struct vm_area_struct *vma,
5374                          unsigned int pages_per_huge_page)
5375 {
5376         unsigned long addr = addr_hint &
5377                 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5378         struct copy_subpage_arg arg = {
5379                 .dst = dst,
5380                 .src = src,
5381                 .vma = vma,
5382         };
5383
5384         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5385                 copy_user_gigantic_page(dst, src, addr, vma,
5386                                         pages_per_huge_page);
5387                 return;
5388         }
5389
5390         process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
5391 }
5392
5393 long copy_huge_page_from_user(struct page *dst_page,
5394                                 const void __user *usr_src,
5395                                 unsigned int pages_per_huge_page,
5396                                 bool allow_pagefault)
5397 {
5398         void *src = (void *)usr_src;
5399         void *page_kaddr;
5400         unsigned long i, rc = 0;
5401         unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
5402         struct page *subpage = dst_page;
5403
5404         for (i = 0; i < pages_per_huge_page;
5405              i++, subpage = mem_map_next(subpage, dst_page, i)) {
5406                 if (allow_pagefault)
5407                         page_kaddr = kmap(subpage);
5408                 else
5409                         page_kaddr = kmap_atomic(subpage);
5410                 rc = copy_from_user(page_kaddr,
5411                                 (const void __user *)(src + i * PAGE_SIZE),
5412                                 PAGE_SIZE);
5413                 if (allow_pagefault)
5414                         kunmap(subpage);
5415                 else
5416                         kunmap_atomic(page_kaddr);
5417
5418                 ret_val -= (PAGE_SIZE - rc);
5419                 if (rc)
5420                         break;
5421
5422                 cond_resched();
5423         }
5424         return ret_val;
5425 }
5426 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
5427
5428 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
5429
5430 static struct kmem_cache *page_ptl_cachep;
5431
5432 void __init ptlock_cache_init(void)
5433 {
5434         page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
5435                         SLAB_PANIC, NULL);
5436 }
5437
5438 bool ptlock_alloc(struct page *page)
5439 {
5440         spinlock_t *ptl;
5441
5442         ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
5443         if (!ptl)
5444                 return false;
5445         page->ptl = ptl;
5446         return true;
5447 }
5448
5449 void ptlock_free(struct page *page)
5450 {
5451         kmem_cache_free(page_ptl_cachep, page->ptl);
5452 }
5453 #endif