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