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