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