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