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