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