Merge tag 'mmc-v6.1-rc5-2' of git://git.kernel.org/pub/scm/linux/kernel/git/ulfh/mmc
[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 /* Whether we should zap all COWed (private) pages too */
1345 static inline bool should_zap_cows(struct zap_details *details)
1346 {
1347         /* By default, zap all pages */
1348         if (!details)
1349                 return true;
1350
1351         /* Or, we zap COWed pages only if the caller wants to */
1352         return details->even_cows;
1353 }
1354
1355 /* Decides whether we should zap this page with the page pointer specified */
1356 static inline bool should_zap_page(struct zap_details *details, struct page *page)
1357 {
1358         /* If we can make a decision without *page.. */
1359         if (should_zap_cows(details))
1360                 return true;
1361
1362         /* E.g. the caller passes NULL for the case of a zero page */
1363         if (!page)
1364                 return true;
1365
1366         /* Otherwise we should only zap non-anon pages */
1367         return !PageAnon(page);
1368 }
1369
1370 static inline bool zap_drop_file_uffd_wp(struct zap_details *details)
1371 {
1372         if (!details)
1373                 return false;
1374
1375         return details->zap_flags & ZAP_FLAG_DROP_MARKER;
1376 }
1377
1378 /*
1379  * This function makes sure that we'll replace the none pte with an uffd-wp
1380  * swap special pte marker when necessary. Must be with the pgtable lock held.
1381  */
1382 static inline void
1383 zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
1384                               unsigned long addr, pte_t *pte,
1385                               struct zap_details *details, pte_t pteval)
1386 {
1387 #ifdef CONFIG_PTE_MARKER_UFFD_WP
1388         if (zap_drop_file_uffd_wp(details))
1389                 return;
1390
1391         pte_install_uffd_wp_if_needed(vma, addr, pte, pteval);
1392 #endif
1393 }
1394
1395 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1396                                 struct vm_area_struct *vma, pmd_t *pmd,
1397                                 unsigned long addr, unsigned long end,
1398                                 struct zap_details *details)
1399 {
1400         struct mm_struct *mm = tlb->mm;
1401         int force_flush = 0;
1402         int rss[NR_MM_COUNTERS];
1403         spinlock_t *ptl;
1404         pte_t *start_pte;
1405         pte_t *pte;
1406         swp_entry_t entry;
1407
1408         tlb_change_page_size(tlb, PAGE_SIZE);
1409 again:
1410         init_rss_vec(rss);
1411         start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1412         pte = start_pte;
1413         flush_tlb_batched_pending(mm);
1414         arch_enter_lazy_mmu_mode();
1415         do {
1416                 pte_t ptent = *pte;
1417                 struct page *page;
1418
1419                 if (pte_none(ptent))
1420                         continue;
1421
1422                 if (need_resched())
1423                         break;
1424
1425                 if (pte_present(ptent)) {
1426                         page = vm_normal_page(vma, addr, ptent);
1427                         if (unlikely(!should_zap_page(details, page)))
1428                                 continue;
1429                         ptent = ptep_get_and_clear_full(mm, addr, pte,
1430                                                         tlb->fullmm);
1431                         tlb_remove_tlb_entry(tlb, pte, addr);
1432                         zap_install_uffd_wp_if_needed(vma, addr, pte, details,
1433                                                       ptent);
1434                         if (unlikely(!page))
1435                                 continue;
1436
1437                         if (!PageAnon(page)) {
1438                                 if (pte_dirty(ptent)) {
1439                                         force_flush = 1;
1440                                         set_page_dirty(page);
1441                                 }
1442                                 if (pte_young(ptent) &&
1443                                     likely(!(vma->vm_flags & VM_SEQ_READ)))
1444                                         mark_page_accessed(page);
1445                         }
1446                         rss[mm_counter(page)]--;
1447                         page_remove_rmap(page, vma, false);
1448                         if (unlikely(page_mapcount(page) < 0))
1449                                 print_bad_pte(vma, addr, ptent, page);
1450                         if (unlikely(__tlb_remove_page(tlb, page))) {
1451                                 force_flush = 1;
1452                                 addr += PAGE_SIZE;
1453                                 break;
1454                         }
1455                         continue;
1456                 }
1457
1458                 entry = pte_to_swp_entry(ptent);
1459                 if (is_device_private_entry(entry) ||
1460                     is_device_exclusive_entry(entry)) {
1461                         page = pfn_swap_entry_to_page(entry);
1462                         if (unlikely(!should_zap_page(details, page)))
1463                                 continue;
1464                         /*
1465                          * Both device private/exclusive mappings should only
1466                          * work with anonymous page so far, so we don't need to
1467                          * consider uffd-wp bit when zap. For more information,
1468                          * see zap_install_uffd_wp_if_needed().
1469                          */
1470                         WARN_ON_ONCE(!vma_is_anonymous(vma));
1471                         rss[mm_counter(page)]--;
1472                         if (is_device_private_entry(entry))
1473                                 page_remove_rmap(page, vma, false);
1474                         put_page(page);
1475                 } else if (!non_swap_entry(entry)) {
1476                         /* Genuine swap entry, hence a private anon page */
1477                         if (!should_zap_cows(details))
1478                                 continue;
1479                         rss[MM_SWAPENTS]--;
1480                         if (unlikely(!free_swap_and_cache(entry)))
1481                                 print_bad_pte(vma, addr, ptent, NULL);
1482                 } else if (is_migration_entry(entry)) {
1483                         page = pfn_swap_entry_to_page(entry);
1484                         if (!should_zap_page(details, page))
1485                                 continue;
1486                         rss[mm_counter(page)]--;
1487                 } else if (pte_marker_entry_uffd_wp(entry)) {
1488                         /* Only drop the uffd-wp marker if explicitly requested */
1489                         if (!zap_drop_file_uffd_wp(details))
1490                                 continue;
1491                 } else if (is_hwpoison_entry(entry) ||
1492                            is_swapin_error_entry(entry)) {
1493                         if (!should_zap_cows(details))
1494                                 continue;
1495                 } else {
1496                         /* We should have covered all the swap entry types */
1497                         WARN_ON_ONCE(1);
1498                 }
1499                 pte_clear_not_present_full(mm, addr, pte, tlb->fullmm);
1500                 zap_install_uffd_wp_if_needed(vma, addr, pte, details, ptent);
1501         } while (pte++, addr += PAGE_SIZE, addr != end);
1502
1503         add_mm_rss_vec(mm, rss);
1504         arch_leave_lazy_mmu_mode();
1505
1506         /* Do the actual TLB flush before dropping ptl */
1507         if (force_flush)
1508                 tlb_flush_mmu_tlbonly(tlb);
1509         pte_unmap_unlock(start_pte, ptl);
1510
1511         /*
1512          * If we forced a TLB flush (either due to running out of
1513          * batch buffers or because we needed to flush dirty TLB
1514          * entries before releasing the ptl), free the batched
1515          * memory too. Restart if we didn't do everything.
1516          */
1517         if (force_flush) {
1518                 force_flush = 0;
1519                 tlb_flush_mmu(tlb);
1520         }
1521
1522         if (addr != end) {
1523                 cond_resched();
1524                 goto again;
1525         }
1526
1527         return addr;
1528 }
1529
1530 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1531                                 struct vm_area_struct *vma, pud_t *pud,
1532                                 unsigned long addr, unsigned long end,
1533                                 struct zap_details *details)
1534 {
1535         pmd_t *pmd;
1536         unsigned long next;
1537
1538         pmd = pmd_offset(pud, addr);
1539         do {
1540                 next = pmd_addr_end(addr, end);
1541                 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1542                         if (next - addr != HPAGE_PMD_SIZE)
1543                                 __split_huge_pmd(vma, pmd, addr, false, NULL);
1544                         else if (zap_huge_pmd(tlb, vma, pmd, addr))
1545                                 goto next;
1546                         /* fall through */
1547                 } else if (details && details->single_folio &&
1548                            folio_test_pmd_mappable(details->single_folio) &&
1549                            next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) {
1550                         spinlock_t *ptl = pmd_lock(tlb->mm, pmd);
1551                         /*
1552                          * Take and drop THP pmd lock so that we cannot return
1553                          * prematurely, while zap_huge_pmd() has cleared *pmd,
1554                          * but not yet decremented compound_mapcount().
1555                          */
1556                         spin_unlock(ptl);
1557                 }
1558
1559                 /*
1560                  * Here there can be other concurrent MADV_DONTNEED or
1561                  * trans huge page faults running, and if the pmd is
1562                  * none or trans huge it can change under us. This is
1563                  * because MADV_DONTNEED holds the mmap_lock in read
1564                  * mode.
1565                  */
1566                 if (pmd_none_or_trans_huge_or_clear_bad(pmd))
1567                         goto next;
1568                 next = zap_pte_range(tlb, vma, pmd, addr, next, details);
1569 next:
1570                 cond_resched();
1571         } while (pmd++, addr = next, addr != end);
1572
1573         return addr;
1574 }
1575
1576 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1577                                 struct vm_area_struct *vma, p4d_t *p4d,
1578                                 unsigned long addr, unsigned long end,
1579                                 struct zap_details *details)
1580 {
1581         pud_t *pud;
1582         unsigned long next;
1583
1584         pud = pud_offset(p4d, addr);
1585         do {
1586                 next = pud_addr_end(addr, end);
1587                 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1588                         if (next - addr != HPAGE_PUD_SIZE) {
1589                                 mmap_assert_locked(tlb->mm);
1590                                 split_huge_pud(vma, pud, addr);
1591                         } else if (zap_huge_pud(tlb, vma, pud, addr))
1592                                 goto next;
1593                         /* fall through */
1594                 }
1595                 if (pud_none_or_clear_bad(pud))
1596                         continue;
1597                 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1598 next:
1599                 cond_resched();
1600         } while (pud++, addr = next, addr != end);
1601
1602         return addr;
1603 }
1604
1605 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1606                                 struct vm_area_struct *vma, pgd_t *pgd,
1607                                 unsigned long addr, unsigned long end,
1608                                 struct zap_details *details)
1609 {
1610         p4d_t *p4d;
1611         unsigned long next;
1612
1613         p4d = p4d_offset(pgd, addr);
1614         do {
1615                 next = p4d_addr_end(addr, end);
1616                 if (p4d_none_or_clear_bad(p4d))
1617                         continue;
1618                 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1619         } while (p4d++, addr = next, addr != end);
1620
1621         return addr;
1622 }
1623
1624 void unmap_page_range(struct mmu_gather *tlb,
1625                              struct vm_area_struct *vma,
1626                              unsigned long addr, unsigned long end,
1627                              struct zap_details *details)
1628 {
1629         pgd_t *pgd;
1630         unsigned long next;
1631
1632         BUG_ON(addr >= end);
1633         tlb_start_vma(tlb, vma);
1634         pgd = pgd_offset(vma->vm_mm, addr);
1635         do {
1636                 next = pgd_addr_end(addr, end);
1637                 if (pgd_none_or_clear_bad(pgd))
1638                         continue;
1639                 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1640         } while (pgd++, addr = next, addr != end);
1641         tlb_end_vma(tlb, vma);
1642 }
1643
1644
1645 static void unmap_single_vma(struct mmu_gather *tlb,
1646                 struct vm_area_struct *vma, unsigned long start_addr,
1647                 unsigned long end_addr,
1648                 struct zap_details *details)
1649 {
1650         unsigned long start = max(vma->vm_start, start_addr);
1651         unsigned long end;
1652
1653         if (start >= vma->vm_end)
1654                 return;
1655         end = min(vma->vm_end, end_addr);
1656         if (end <= vma->vm_start)
1657                 return;
1658
1659         if (vma->vm_file)
1660                 uprobe_munmap(vma, start, end);
1661
1662         if (unlikely(vma->vm_flags & VM_PFNMAP))
1663                 untrack_pfn(vma, 0, 0);
1664
1665         if (start != end) {
1666                 if (unlikely(is_vm_hugetlb_page(vma))) {
1667                         /*
1668                          * It is undesirable to test vma->vm_file as it
1669                          * should be non-null for valid hugetlb area.
1670                          * However, vm_file will be NULL in the error
1671                          * cleanup path of mmap_region. When
1672                          * hugetlbfs ->mmap method fails,
1673                          * mmap_region() nullifies vma->vm_file
1674                          * before calling this function to clean up.
1675                          * Since no pte has actually been setup, it is
1676                          * safe to do nothing in this case.
1677                          */
1678                         if (vma->vm_file) {
1679                                 zap_flags_t zap_flags = details ?
1680                                     details->zap_flags : 0;
1681                                 __unmap_hugepage_range_final(tlb, vma, start, end,
1682                                                              NULL, zap_flags);
1683                         }
1684                 } else
1685                         unmap_page_range(tlb, vma, start, end, details);
1686         }
1687 }
1688
1689 /**
1690  * unmap_vmas - unmap a range of memory covered by a list of vma's
1691  * @tlb: address of the caller's struct mmu_gather
1692  * @mt: the maple tree
1693  * @vma: the starting vma
1694  * @start_addr: virtual address at which to start unmapping
1695  * @end_addr: virtual address at which to end unmapping
1696  *
1697  * Unmap all pages in the vma list.
1698  *
1699  * Only addresses between `start' and `end' will be unmapped.
1700  *
1701  * The VMA list must be sorted in ascending virtual address order.
1702  *
1703  * unmap_vmas() assumes that the caller will flush the whole unmapped address
1704  * range after unmap_vmas() returns.  So the only responsibility here is to
1705  * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1706  * drops the lock and schedules.
1707  */
1708 void unmap_vmas(struct mmu_gather *tlb, struct maple_tree *mt,
1709                 struct vm_area_struct *vma, unsigned long start_addr,
1710                 unsigned long end_addr)
1711 {
1712         struct mmu_notifier_range range;
1713         struct zap_details details = {
1714                 .zap_flags = ZAP_FLAG_DROP_MARKER | ZAP_FLAG_UNMAP,
1715                 /* Careful - we need to zap private pages too! */
1716                 .even_cows = true,
1717         };
1718         MA_STATE(mas, mt, vma->vm_end, vma->vm_end);
1719
1720         mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma, vma->vm_mm,
1721                                 start_addr, end_addr);
1722         mmu_notifier_invalidate_range_start(&range);
1723         do {
1724                 unmap_single_vma(tlb, vma, start_addr, end_addr, &details);
1725         } while ((vma = mas_find(&mas, end_addr - 1)) != NULL);
1726         mmu_notifier_invalidate_range_end(&range);
1727 }
1728
1729 /**
1730  * zap_page_range - remove user pages in a given range
1731  * @vma: vm_area_struct holding the applicable pages
1732  * @start: starting address of pages to zap
1733  * @size: number of bytes to zap
1734  *
1735  * Caller must protect the VMA list
1736  */
1737 void zap_page_range(struct vm_area_struct *vma, unsigned long start,
1738                 unsigned long size)
1739 {
1740         struct maple_tree *mt = &vma->vm_mm->mm_mt;
1741         unsigned long end = start + size;
1742         struct mmu_notifier_range range;
1743         struct mmu_gather tlb;
1744         MA_STATE(mas, mt, vma->vm_end, vma->vm_end);
1745
1746         lru_add_drain();
1747         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1748                                 start, start + size);
1749         tlb_gather_mmu(&tlb, vma->vm_mm);
1750         update_hiwater_rss(vma->vm_mm);
1751         mmu_notifier_invalidate_range_start(&range);
1752         do {
1753                 unmap_single_vma(&tlb, vma, start, range.end, NULL);
1754         } while ((vma = mas_find(&mas, end - 1)) != NULL);
1755         mmu_notifier_invalidate_range_end(&range);
1756         tlb_finish_mmu(&tlb);
1757 }
1758
1759 /**
1760  * zap_page_range_single - remove user pages in a given range
1761  * @vma: vm_area_struct holding the applicable pages
1762  * @address: starting address of pages to zap
1763  * @size: number of bytes to zap
1764  * @details: details of shared cache invalidation
1765  *
1766  * The range must fit into one VMA.
1767  */
1768 void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
1769                 unsigned long size, struct zap_details *details)
1770 {
1771         const unsigned long end = address + size;
1772         struct mmu_notifier_range range;
1773         struct mmu_gather tlb;
1774
1775         lru_add_drain();
1776         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, vma->vm_mm,
1777                                 address, end);
1778         if (is_vm_hugetlb_page(vma))
1779                 adjust_range_if_pmd_sharing_possible(vma, &range.start,
1780                                                      &range.end);
1781         tlb_gather_mmu(&tlb, vma->vm_mm);
1782         update_hiwater_rss(vma->vm_mm);
1783         mmu_notifier_invalidate_range_start(&range);
1784         /*
1785          * unmap 'address-end' not 'range.start-range.end' as range
1786          * could have been expanded for hugetlb pmd sharing.
1787          */
1788         unmap_single_vma(&tlb, vma, address, end, details);
1789         mmu_notifier_invalidate_range_end(&range);
1790         tlb_finish_mmu(&tlb);
1791 }
1792
1793 /**
1794  * zap_vma_ptes - remove ptes mapping the vma
1795  * @vma: vm_area_struct holding ptes to be zapped
1796  * @address: starting address of pages to zap
1797  * @size: number of bytes to zap
1798  *
1799  * This function only unmaps ptes assigned to VM_PFNMAP vmas.
1800  *
1801  * The entire address range must be fully contained within the vma.
1802  *
1803  */
1804 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
1805                 unsigned long size)
1806 {
1807         if (!range_in_vma(vma, address, address + size) ||
1808                         !(vma->vm_flags & VM_PFNMAP))
1809                 return;
1810
1811         zap_page_range_single(vma, address, size, NULL);
1812 }
1813 EXPORT_SYMBOL_GPL(zap_vma_ptes);
1814
1815 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
1816 {
1817         pgd_t *pgd;
1818         p4d_t *p4d;
1819         pud_t *pud;
1820         pmd_t *pmd;
1821
1822         pgd = pgd_offset(mm, addr);
1823         p4d = p4d_alloc(mm, pgd, addr);
1824         if (!p4d)
1825                 return NULL;
1826         pud = pud_alloc(mm, p4d, addr);
1827         if (!pud)
1828                 return NULL;
1829         pmd = pmd_alloc(mm, pud, addr);
1830         if (!pmd)
1831                 return NULL;
1832
1833         VM_BUG_ON(pmd_trans_huge(*pmd));
1834         return pmd;
1835 }
1836
1837 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
1838                         spinlock_t **ptl)
1839 {
1840         pmd_t *pmd = walk_to_pmd(mm, addr);
1841
1842         if (!pmd)
1843                 return NULL;
1844         return pte_alloc_map_lock(mm, pmd, addr, ptl);
1845 }
1846
1847 static int validate_page_before_insert(struct page *page)
1848 {
1849         if (PageAnon(page) || PageSlab(page) || page_has_type(page))
1850                 return -EINVAL;
1851         flush_dcache_page(page);
1852         return 0;
1853 }
1854
1855 static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
1856                         unsigned long addr, struct page *page, pgprot_t prot)
1857 {
1858         if (!pte_none(*pte))
1859                 return -EBUSY;
1860         /* Ok, finally just insert the thing.. */
1861         get_page(page);
1862         inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
1863         page_add_file_rmap(page, vma, false);
1864         set_pte_at(vma->vm_mm, addr, pte, mk_pte(page, prot));
1865         return 0;
1866 }
1867
1868 /*
1869  * This is the old fallback for page remapping.
1870  *
1871  * For historical reasons, it only allows reserved pages. Only
1872  * old drivers should use this, and they needed to mark their
1873  * pages reserved for the old functions anyway.
1874  */
1875 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
1876                         struct page *page, pgprot_t prot)
1877 {
1878         int retval;
1879         pte_t *pte;
1880         spinlock_t *ptl;
1881
1882         retval = validate_page_before_insert(page);
1883         if (retval)
1884                 goto out;
1885         retval = -ENOMEM;
1886         pte = get_locked_pte(vma->vm_mm, addr, &ptl);
1887         if (!pte)
1888                 goto out;
1889         retval = insert_page_into_pte_locked(vma, pte, addr, page, prot);
1890         pte_unmap_unlock(pte, ptl);
1891 out:
1892         return retval;
1893 }
1894
1895 #ifdef pte_index
1896 static int insert_page_in_batch_locked(struct vm_area_struct *vma, pte_t *pte,
1897                         unsigned long addr, struct page *page, pgprot_t prot)
1898 {
1899         int err;
1900
1901         if (!page_count(page))
1902                 return -EINVAL;
1903         err = validate_page_before_insert(page);
1904         if (err)
1905                 return err;
1906         return insert_page_into_pte_locked(vma, pte, addr, page, prot);
1907 }
1908
1909 /* insert_pages() amortizes the cost of spinlock operations
1910  * when inserting pages in a loop. Arch *must* define pte_index.
1911  */
1912 static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
1913                         struct page **pages, unsigned long *num, pgprot_t prot)
1914 {
1915         pmd_t *pmd = NULL;
1916         pte_t *start_pte, *pte;
1917         spinlock_t *pte_lock;
1918         struct mm_struct *const mm = vma->vm_mm;
1919         unsigned long curr_page_idx = 0;
1920         unsigned long remaining_pages_total = *num;
1921         unsigned long pages_to_write_in_pmd;
1922         int ret;
1923 more:
1924         ret = -EFAULT;
1925         pmd = walk_to_pmd(mm, addr);
1926         if (!pmd)
1927                 goto out;
1928
1929         pages_to_write_in_pmd = min_t(unsigned long,
1930                 remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
1931
1932         /* Allocate the PTE if necessary; takes PMD lock once only. */
1933         ret = -ENOMEM;
1934         if (pte_alloc(mm, pmd))
1935                 goto out;
1936
1937         while (pages_to_write_in_pmd) {
1938                 int pte_idx = 0;
1939                 const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
1940
1941                 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
1942                 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
1943                         int err = insert_page_in_batch_locked(vma, pte,
1944                                 addr, pages[curr_page_idx], prot);
1945                         if (unlikely(err)) {
1946                                 pte_unmap_unlock(start_pte, pte_lock);
1947                                 ret = err;
1948                                 remaining_pages_total -= pte_idx;
1949                                 goto out;
1950                         }
1951                         addr += PAGE_SIZE;
1952                         ++curr_page_idx;
1953                 }
1954                 pte_unmap_unlock(start_pte, pte_lock);
1955                 pages_to_write_in_pmd -= batch_size;
1956                 remaining_pages_total -= batch_size;
1957         }
1958         if (remaining_pages_total)
1959                 goto more;
1960         ret = 0;
1961 out:
1962         *num = remaining_pages_total;
1963         return ret;
1964 }
1965 #endif  /* ifdef pte_index */
1966
1967 /**
1968  * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
1969  * @vma: user vma to map to
1970  * @addr: target start user address of these pages
1971  * @pages: source kernel pages
1972  * @num: in: number of pages to map. out: number of pages that were *not*
1973  * mapped. (0 means all pages were successfully mapped).
1974  *
1975  * Preferred over vm_insert_page() when inserting multiple pages.
1976  *
1977  * In case of error, we may have mapped a subset of the provided
1978  * pages. It is the caller's responsibility to account for this case.
1979  *
1980  * The same restrictions apply as in vm_insert_page().
1981  */
1982 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
1983                         struct page **pages, unsigned long *num)
1984 {
1985 #ifdef pte_index
1986         const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
1987
1988         if (addr < vma->vm_start || end_addr >= vma->vm_end)
1989                 return -EFAULT;
1990         if (!(vma->vm_flags & VM_MIXEDMAP)) {
1991                 BUG_ON(mmap_read_trylock(vma->vm_mm));
1992                 BUG_ON(vma->vm_flags & VM_PFNMAP);
1993                 vma->vm_flags |= VM_MIXEDMAP;
1994         }
1995         /* Defer page refcount checking till we're about to map that page. */
1996         return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
1997 #else
1998         unsigned long idx = 0, pgcount = *num;
1999         int err = -EINVAL;
2000
2001         for (; idx < pgcount; ++idx) {
2002                 err = vm_insert_page(vma, addr + (PAGE_SIZE * idx), pages[idx]);
2003                 if (err)
2004                         break;
2005         }
2006         *num = pgcount - idx;
2007         return err;
2008 #endif  /* ifdef pte_index */
2009 }
2010 EXPORT_SYMBOL(vm_insert_pages);
2011
2012 /**
2013  * vm_insert_page - insert single page into user vma
2014  * @vma: user vma to map to
2015  * @addr: target user address of this page
2016  * @page: source kernel page
2017  *
2018  * This allows drivers to insert individual pages they've allocated
2019  * into a user vma.
2020  *
2021  * The page has to be a nice clean _individual_ kernel allocation.
2022  * If you allocate a compound page, you need to have marked it as
2023  * such (__GFP_COMP), or manually just split the page up yourself
2024  * (see split_page()).
2025  *
2026  * NOTE! Traditionally this was done with "remap_pfn_range()" which
2027  * took an arbitrary page protection parameter. This doesn't allow
2028  * that. Your vma protection will have to be set up correctly, which
2029  * means that if you want a shared writable mapping, you'd better
2030  * ask for a shared writable mapping!
2031  *
2032  * The page does not need to be reserved.
2033  *
2034  * Usually this function is called from f_op->mmap() handler
2035  * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
2036  * Caller must set VM_MIXEDMAP on vma if it wants to call this
2037  * function from other places, for example from page-fault handler.
2038  *
2039  * Return: %0 on success, negative error code otherwise.
2040  */
2041 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
2042                         struct page *page)
2043 {
2044         if (addr < vma->vm_start || addr >= vma->vm_end)
2045                 return -EFAULT;
2046         if (!page_count(page))
2047                 return -EINVAL;
2048         if (!(vma->vm_flags & VM_MIXEDMAP)) {
2049                 BUG_ON(mmap_read_trylock(vma->vm_mm));
2050                 BUG_ON(vma->vm_flags & VM_PFNMAP);
2051                 vma->vm_flags |= VM_MIXEDMAP;
2052         }
2053         return insert_page(vma, addr, page, vma->vm_page_prot);
2054 }
2055 EXPORT_SYMBOL(vm_insert_page);
2056
2057 /*
2058  * __vm_map_pages - maps range of kernel pages into user vma
2059  * @vma: user vma to map to
2060  * @pages: pointer to array of source kernel pages
2061  * @num: number of pages in page array
2062  * @offset: user's requested vm_pgoff
2063  *
2064  * This allows drivers to map range of kernel pages into a user vma.
2065  *
2066  * Return: 0 on success and error code otherwise.
2067  */
2068 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2069                                 unsigned long num, unsigned long offset)
2070 {
2071         unsigned long count = vma_pages(vma);
2072         unsigned long uaddr = vma->vm_start;
2073         int ret, i;
2074
2075         /* Fail if the user requested offset is beyond the end of the object */
2076         if (offset >= num)
2077                 return -ENXIO;
2078
2079         /* Fail if the user requested size exceeds available object size */
2080         if (count > num - offset)
2081                 return -ENXIO;
2082
2083         for (i = 0; i < count; i++) {
2084                 ret = vm_insert_page(vma, uaddr, pages[offset + i]);
2085                 if (ret < 0)
2086                         return ret;
2087                 uaddr += PAGE_SIZE;
2088         }
2089
2090         return 0;
2091 }
2092
2093 /**
2094  * vm_map_pages - maps range of kernel pages starts with non zero offset
2095  * @vma: user vma to map to
2096  * @pages: pointer to array of source kernel pages
2097  * @num: number of pages in page array
2098  *
2099  * Maps an object consisting of @num pages, catering for the user's
2100  * requested vm_pgoff
2101  *
2102  * If we fail to insert any page into the vma, the function will return
2103  * immediately leaving any previously inserted pages present.  Callers
2104  * from the mmap handler may immediately return the error as their caller
2105  * will destroy the vma, removing any successfully inserted pages. Other
2106  * callers should make their own arrangements for calling unmap_region().
2107  *
2108  * Context: Process context. Called by mmap handlers.
2109  * Return: 0 on success and error code otherwise.
2110  */
2111 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2112                                 unsigned long num)
2113 {
2114         return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
2115 }
2116 EXPORT_SYMBOL(vm_map_pages);
2117
2118 /**
2119  * vm_map_pages_zero - map range of kernel pages starts with zero offset
2120  * @vma: user vma to map to
2121  * @pages: pointer to array of source kernel pages
2122  * @num: number of pages in page array
2123  *
2124  * Similar to vm_map_pages(), except that it explicitly sets the offset
2125  * to 0. This function is intended for the drivers that did not consider
2126  * vm_pgoff.
2127  *
2128  * Context: Process context. Called by mmap handlers.
2129  * Return: 0 on success and error code otherwise.
2130  */
2131 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
2132                                 unsigned long num)
2133 {
2134         return __vm_map_pages(vma, pages, num, 0);
2135 }
2136 EXPORT_SYMBOL(vm_map_pages_zero);
2137
2138 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2139                         pfn_t pfn, pgprot_t prot, bool mkwrite)
2140 {
2141         struct mm_struct *mm = vma->vm_mm;
2142         pte_t *pte, entry;
2143         spinlock_t *ptl;
2144
2145         pte = get_locked_pte(mm, addr, &ptl);
2146         if (!pte)
2147                 return VM_FAULT_OOM;
2148         if (!pte_none(*pte)) {
2149                 if (mkwrite) {
2150                         /*
2151                          * For read faults on private mappings the PFN passed
2152                          * in may not match the PFN we have mapped if the
2153                          * mapped PFN is a writeable COW page.  In the mkwrite
2154                          * case we are creating a writable PTE for a shared
2155                          * mapping and we expect the PFNs to match. If they
2156                          * don't match, we are likely racing with block
2157                          * allocation and mapping invalidation so just skip the
2158                          * update.
2159                          */
2160                         if (pte_pfn(*pte) != pfn_t_to_pfn(pfn)) {
2161                                 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(*pte)));
2162                                 goto out_unlock;
2163                         }
2164                         entry = pte_mkyoung(*pte);
2165                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2166                         if (ptep_set_access_flags(vma, addr, pte, entry, 1))
2167                                 update_mmu_cache(vma, addr, pte);
2168                 }
2169                 goto out_unlock;
2170         }
2171
2172         /* Ok, finally just insert the thing.. */
2173         if (pfn_t_devmap(pfn))
2174                 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
2175         else
2176                 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
2177
2178         if (mkwrite) {
2179                 entry = pte_mkyoung(entry);
2180                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2181         }
2182
2183         set_pte_at(mm, addr, pte, entry);
2184         update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2185
2186 out_unlock:
2187         pte_unmap_unlock(pte, ptl);
2188         return VM_FAULT_NOPAGE;
2189 }
2190
2191 /**
2192  * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
2193  * @vma: user vma to map to
2194  * @addr: target user address of this page
2195  * @pfn: source kernel pfn
2196  * @pgprot: pgprot flags for the inserted page
2197  *
2198  * This is exactly like vmf_insert_pfn(), except that it allows drivers
2199  * to override pgprot on a per-page basis.
2200  *
2201  * This only makes sense for IO mappings, and it makes no sense for
2202  * COW mappings.  In general, using multiple vmas is preferable;
2203  * vmf_insert_pfn_prot should only be used if using multiple VMAs is
2204  * impractical.
2205  *
2206  * See vmf_insert_mixed_prot() for a discussion of the implication of using
2207  * a value of @pgprot different from that of @vma->vm_page_prot.
2208  *
2209  * Context: Process context.  May allocate using %GFP_KERNEL.
2210  * Return: vm_fault_t value.
2211  */
2212 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
2213                         unsigned long pfn, pgprot_t pgprot)
2214 {
2215         /*
2216          * Technically, architectures with pte_special can avoid all these
2217          * restrictions (same for remap_pfn_range).  However we would like
2218          * consistency in testing and feature parity among all, so we should
2219          * try to keep these invariants in place for everybody.
2220          */
2221         BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2222         BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2223                                                 (VM_PFNMAP|VM_MIXEDMAP));
2224         BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2225         BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2226
2227         if (addr < vma->vm_start || addr >= vma->vm_end)
2228                 return VM_FAULT_SIGBUS;
2229
2230         if (!pfn_modify_allowed(pfn, pgprot))
2231                 return VM_FAULT_SIGBUS;
2232
2233         track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
2234
2235         return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
2236                         false);
2237 }
2238 EXPORT_SYMBOL(vmf_insert_pfn_prot);
2239
2240 /**
2241  * vmf_insert_pfn - insert single pfn into user vma
2242  * @vma: user vma to map to
2243  * @addr: target user address of this page
2244  * @pfn: source kernel pfn
2245  *
2246  * Similar to vm_insert_page, this allows drivers to insert individual pages
2247  * they've allocated into a user vma. Same comments apply.
2248  *
2249  * This function should only be called from a vm_ops->fault handler, and
2250  * in that case the handler should return the result of this function.
2251  *
2252  * vma cannot be a COW mapping.
2253  *
2254  * As this is called only for pages that do not currently exist, we
2255  * do not need to flush old virtual caches or the TLB.
2256  *
2257  * Context: Process context.  May allocate using %GFP_KERNEL.
2258  * Return: vm_fault_t value.
2259  */
2260 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2261                         unsigned long pfn)
2262 {
2263         return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
2264 }
2265 EXPORT_SYMBOL(vmf_insert_pfn);
2266
2267 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn)
2268 {
2269         /* these checks mirror the abort conditions in vm_normal_page */
2270         if (vma->vm_flags & VM_MIXEDMAP)
2271                 return true;
2272         if (pfn_t_devmap(pfn))
2273                 return true;
2274         if (pfn_t_special(pfn))
2275                 return true;
2276         if (is_zero_pfn(pfn_t_to_pfn(pfn)))
2277                 return true;
2278         return false;
2279 }
2280
2281 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
2282                 unsigned long addr, pfn_t pfn, pgprot_t pgprot,
2283                 bool mkwrite)
2284 {
2285         int err;
2286
2287         BUG_ON(!vm_mixed_ok(vma, pfn));
2288
2289         if (addr < vma->vm_start || addr >= vma->vm_end)
2290                 return VM_FAULT_SIGBUS;
2291
2292         track_pfn_insert(vma, &pgprot, pfn);
2293
2294         if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
2295                 return VM_FAULT_SIGBUS;
2296
2297         /*
2298          * If we don't have pte special, then we have to use the pfn_valid()
2299          * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2300          * refcount the page if pfn_valid is true (hence insert_page rather
2301          * than insert_pfn).  If a zero_pfn were inserted into a VM_MIXEDMAP
2302          * without pte special, it would there be refcounted as a normal page.
2303          */
2304         if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
2305             !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
2306                 struct page *page;
2307
2308                 /*
2309                  * At this point we are committed to insert_page()
2310                  * regardless of whether the caller specified flags that
2311                  * result in pfn_t_has_page() == false.
2312                  */
2313                 page = pfn_to_page(pfn_t_to_pfn(pfn));
2314                 err = insert_page(vma, addr, page, pgprot);
2315         } else {
2316                 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2317         }
2318
2319         if (err == -ENOMEM)
2320                 return VM_FAULT_OOM;
2321         if (err < 0 && err != -EBUSY)
2322                 return VM_FAULT_SIGBUS;
2323
2324         return VM_FAULT_NOPAGE;
2325 }
2326
2327 /**
2328  * vmf_insert_mixed_prot - insert single pfn into user vma with specified pgprot
2329  * @vma: user vma to map to
2330  * @addr: target user address of this page
2331  * @pfn: source kernel pfn
2332  * @pgprot: pgprot flags for the inserted page
2333  *
2334  * This is exactly like vmf_insert_mixed(), except that it allows drivers
2335  * to override pgprot on a per-page basis.
2336  *
2337  * Typically this function should be used by drivers to set caching- and
2338  * encryption bits different than those of @vma->vm_page_prot, because
2339  * the caching- or encryption mode may not be known at mmap() time.
2340  * This is ok as long as @vma->vm_page_prot is not used by the core vm
2341  * to set caching and encryption bits for those vmas (except for COW pages).
2342  * This is ensured by core vm only modifying these page table entries using
2343  * functions that don't touch caching- or encryption bits, using pte_modify()
2344  * if needed. (See for example mprotect()).
2345  * Also when new page-table entries are created, this is only done using the
2346  * fault() callback, and never using the value of vma->vm_page_prot,
2347  * except for page-table entries that point to anonymous pages as the result
2348  * of COW.
2349  *
2350  * Context: Process context.  May allocate using %GFP_KERNEL.
2351  * Return: vm_fault_t value.
2352  */
2353 vm_fault_t vmf_insert_mixed_prot(struct vm_area_struct *vma, unsigned long addr,
2354                                  pfn_t pfn, pgprot_t pgprot)
2355 {
2356         return __vm_insert_mixed(vma, addr, pfn, pgprot, false);
2357 }
2358 EXPORT_SYMBOL(vmf_insert_mixed_prot);
2359
2360 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2361                 pfn_t pfn)
2362 {
2363         return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, false);
2364 }
2365 EXPORT_SYMBOL(vmf_insert_mixed);
2366
2367 /*
2368  *  If the insertion of PTE failed because someone else already added a
2369  *  different entry in the mean time, we treat that as success as we assume
2370  *  the same entry was actually inserted.
2371  */
2372 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2373                 unsigned long addr, pfn_t pfn)
2374 {
2375         return __vm_insert_mixed(vma, addr, pfn, vma->vm_page_prot, true);
2376 }
2377 EXPORT_SYMBOL(vmf_insert_mixed_mkwrite);
2378
2379 /*
2380  * maps a range of physical memory into the requested pages. the old
2381  * mappings are removed. any references to nonexistent pages results
2382  * in null mappings (currently treated as "copy-on-access")
2383  */
2384 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2385                         unsigned long addr, unsigned long end,
2386                         unsigned long pfn, pgprot_t prot)
2387 {
2388         pte_t *pte, *mapped_pte;
2389         spinlock_t *ptl;
2390         int err = 0;
2391
2392         mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2393         if (!pte)
2394                 return -ENOMEM;
2395         arch_enter_lazy_mmu_mode();
2396         do {
2397                 BUG_ON(!pte_none(*pte));
2398                 if (!pfn_modify_allowed(pfn, prot)) {
2399                         err = -EACCES;
2400                         break;
2401                 }
2402                 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2403                 pfn++;
2404         } while (pte++, addr += PAGE_SIZE, addr != end);
2405         arch_leave_lazy_mmu_mode();
2406         pte_unmap_unlock(mapped_pte, ptl);
2407         return err;
2408 }
2409
2410 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2411                         unsigned long addr, unsigned long end,
2412                         unsigned long pfn, pgprot_t prot)
2413 {
2414         pmd_t *pmd;
2415         unsigned long next;
2416         int err;
2417
2418         pfn -= addr >> PAGE_SHIFT;
2419         pmd = pmd_alloc(mm, pud, addr);
2420         if (!pmd)
2421                 return -ENOMEM;
2422         VM_BUG_ON(pmd_trans_huge(*pmd));
2423         do {
2424                 next = pmd_addr_end(addr, end);
2425                 err = remap_pte_range(mm, pmd, addr, next,
2426                                 pfn + (addr >> PAGE_SHIFT), prot);
2427                 if (err)
2428                         return err;
2429         } while (pmd++, addr = next, addr != end);
2430         return 0;
2431 }
2432
2433 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2434                         unsigned long addr, unsigned long end,
2435                         unsigned long pfn, pgprot_t prot)
2436 {
2437         pud_t *pud;
2438         unsigned long next;
2439         int err;
2440
2441         pfn -= addr >> PAGE_SHIFT;
2442         pud = pud_alloc(mm, p4d, addr);
2443         if (!pud)
2444                 return -ENOMEM;
2445         do {
2446                 next = pud_addr_end(addr, end);
2447                 err = remap_pmd_range(mm, pud, addr, next,
2448                                 pfn + (addr >> PAGE_SHIFT), prot);
2449                 if (err)
2450                         return err;
2451         } while (pud++, addr = next, addr != end);
2452         return 0;
2453 }
2454
2455 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2456                         unsigned long addr, unsigned long end,
2457                         unsigned long pfn, pgprot_t prot)
2458 {
2459         p4d_t *p4d;
2460         unsigned long next;
2461         int err;
2462
2463         pfn -= addr >> PAGE_SHIFT;
2464         p4d = p4d_alloc(mm, pgd, addr);
2465         if (!p4d)
2466                 return -ENOMEM;
2467         do {
2468                 next = p4d_addr_end(addr, end);
2469                 err = remap_pud_range(mm, p4d, addr, next,
2470                                 pfn + (addr >> PAGE_SHIFT), prot);
2471                 if (err)
2472                         return err;
2473         } while (p4d++, addr = next, addr != end);
2474         return 0;
2475 }
2476
2477 /*
2478  * Variant of remap_pfn_range that does not call track_pfn_remap.  The caller
2479  * must have pre-validated the caching bits of the pgprot_t.
2480  */
2481 int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr,
2482                 unsigned long pfn, unsigned long size, pgprot_t prot)
2483 {
2484         pgd_t *pgd;
2485         unsigned long next;
2486         unsigned long end = addr + PAGE_ALIGN(size);
2487         struct mm_struct *mm = vma->vm_mm;
2488         int err;
2489
2490         if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
2491                 return -EINVAL;
2492
2493         /*
2494          * Physically remapped pages are special. Tell the
2495          * rest of the world about it:
2496          *   VM_IO tells people not to look at these pages
2497          *      (accesses can have side effects).
2498          *   VM_PFNMAP tells the core MM that the base pages are just
2499          *      raw PFN mappings, and do not have a "struct page" associated
2500          *      with them.
2501          *   VM_DONTEXPAND
2502          *      Disable vma merging and expanding with mremap().
2503          *   VM_DONTDUMP
2504          *      Omit vma from core dump, even when VM_IO turned off.
2505          *
2506          * There's a horrible special case to handle copy-on-write
2507          * behaviour that some programs depend on. We mark the "original"
2508          * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2509          * See vm_normal_page() for details.
2510          */
2511         if (is_cow_mapping(vma->vm_flags)) {
2512                 if (addr != vma->vm_start || end != vma->vm_end)
2513                         return -EINVAL;
2514                 vma->vm_pgoff = pfn;
2515         }
2516
2517         vma->vm_flags |= VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP;
2518
2519         BUG_ON(addr >= end);
2520         pfn -= addr >> PAGE_SHIFT;
2521         pgd = pgd_offset(mm, addr);
2522         flush_cache_range(vma, addr, end);
2523         do {
2524                 next = pgd_addr_end(addr, end);
2525                 err = remap_p4d_range(mm, pgd, addr, next,
2526                                 pfn + (addr >> PAGE_SHIFT), prot);
2527                 if (err)
2528                         return err;
2529         } while (pgd++, addr = next, addr != end);
2530
2531         return 0;
2532 }
2533
2534 /**
2535  * remap_pfn_range - remap kernel memory to userspace
2536  * @vma: user vma to map to
2537  * @addr: target page aligned user address to start at
2538  * @pfn: page frame number of kernel physical memory address
2539  * @size: size of mapping area
2540  * @prot: page protection flags for this mapping
2541  *
2542  * Note: this is only safe if the mm semaphore is held when called.
2543  *
2544  * Return: %0 on success, negative error code otherwise.
2545  */
2546 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2547                     unsigned long pfn, unsigned long size, pgprot_t prot)
2548 {
2549         int err;
2550
2551         err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2552         if (err)
2553                 return -EINVAL;
2554
2555         err = remap_pfn_range_notrack(vma, addr, pfn, size, prot);
2556         if (err)
2557                 untrack_pfn(vma, pfn, PAGE_ALIGN(size));
2558         return err;
2559 }
2560 EXPORT_SYMBOL(remap_pfn_range);
2561
2562 /**
2563  * vm_iomap_memory - remap memory to userspace
2564  * @vma: user vma to map to
2565  * @start: start of the physical memory to be mapped
2566  * @len: size of area
2567  *
2568  * This is a simplified io_remap_pfn_range() for common driver use. The
2569  * driver just needs to give us the physical memory range to be mapped,
2570  * we'll figure out the rest from the vma information.
2571  *
2572  * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2573  * whatever write-combining details or similar.
2574  *
2575  * Return: %0 on success, negative error code otherwise.
2576  */
2577 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2578 {
2579         unsigned long vm_len, pfn, pages;
2580
2581         /* Check that the physical memory area passed in looks valid */
2582         if (start + len < start)
2583                 return -EINVAL;
2584         /*
2585          * You *really* shouldn't map things that aren't page-aligned,
2586          * but we've historically allowed it because IO memory might
2587          * just have smaller alignment.
2588          */
2589         len += start & ~PAGE_MASK;
2590         pfn = start >> PAGE_SHIFT;
2591         pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2592         if (pfn + pages < pfn)
2593                 return -EINVAL;
2594
2595         /* We start the mapping 'vm_pgoff' pages into the area */
2596         if (vma->vm_pgoff > pages)
2597                 return -EINVAL;
2598         pfn += vma->vm_pgoff;
2599         pages -= vma->vm_pgoff;
2600
2601         /* Can we fit all of the mapping? */
2602         vm_len = vma->vm_end - vma->vm_start;
2603         if (vm_len >> PAGE_SHIFT > pages)
2604                 return -EINVAL;
2605
2606         /* Ok, let it rip */
2607         return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2608 }
2609 EXPORT_SYMBOL(vm_iomap_memory);
2610
2611 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2612                                      unsigned long addr, unsigned long end,
2613                                      pte_fn_t fn, void *data, bool create,
2614                                      pgtbl_mod_mask *mask)
2615 {
2616         pte_t *pte, *mapped_pte;
2617         int err = 0;
2618         spinlock_t *ptl;
2619
2620         if (create) {
2621                 mapped_pte = pte = (mm == &init_mm) ?
2622                         pte_alloc_kernel_track(pmd, addr, mask) :
2623                         pte_alloc_map_lock(mm, pmd, addr, &ptl);
2624                 if (!pte)
2625                         return -ENOMEM;
2626         } else {
2627                 mapped_pte = pte = (mm == &init_mm) ?
2628                         pte_offset_kernel(pmd, addr) :
2629                         pte_offset_map_lock(mm, pmd, addr, &ptl);
2630         }
2631
2632         BUG_ON(pmd_huge(*pmd));
2633
2634         arch_enter_lazy_mmu_mode();
2635
2636         if (fn) {
2637                 do {
2638                         if (create || !pte_none(*pte)) {
2639                                 err = fn(pte++, addr, data);
2640                                 if (err)
2641                                         break;
2642                         }
2643                 } while (addr += PAGE_SIZE, addr != end);
2644         }
2645         *mask |= PGTBL_PTE_MODIFIED;
2646
2647         arch_leave_lazy_mmu_mode();
2648
2649         if (mm != &init_mm)
2650                 pte_unmap_unlock(mapped_pte, ptl);
2651         return err;
2652 }
2653
2654 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2655                                      unsigned long addr, unsigned long end,
2656                                      pte_fn_t fn, void *data, bool create,
2657                                      pgtbl_mod_mask *mask)
2658 {
2659         pmd_t *pmd;
2660         unsigned long next;
2661         int err = 0;
2662
2663         BUG_ON(pud_huge(*pud));
2664
2665         if (create) {
2666                 pmd = pmd_alloc_track(mm, pud, addr, mask);
2667                 if (!pmd)
2668                         return -ENOMEM;
2669         } else {
2670                 pmd = pmd_offset(pud, addr);
2671         }
2672         do {
2673                 next = pmd_addr_end(addr, end);
2674                 if (pmd_none(*pmd) && !create)
2675                         continue;
2676                 if (WARN_ON_ONCE(pmd_leaf(*pmd)))
2677                         return -EINVAL;
2678                 if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) {
2679                         if (!create)
2680                                 continue;
2681                         pmd_clear_bad(pmd);
2682                 }
2683                 err = apply_to_pte_range(mm, pmd, addr, next,
2684                                          fn, data, create, mask);
2685                 if (err)
2686                         break;
2687         } while (pmd++, addr = next, addr != end);
2688
2689         return err;
2690 }
2691
2692 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2693                                      unsigned long addr, unsigned long end,
2694                                      pte_fn_t fn, void *data, bool create,
2695                                      pgtbl_mod_mask *mask)
2696 {
2697         pud_t *pud;
2698         unsigned long next;
2699         int err = 0;
2700
2701         if (create) {
2702                 pud = pud_alloc_track(mm, p4d, addr, mask);
2703                 if (!pud)
2704                         return -ENOMEM;
2705         } else {
2706                 pud = pud_offset(p4d, addr);
2707         }
2708         do {
2709                 next = pud_addr_end(addr, end);
2710                 if (pud_none(*pud) && !create)
2711                         continue;
2712                 if (WARN_ON_ONCE(pud_leaf(*pud)))
2713                         return -EINVAL;
2714                 if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) {
2715                         if (!create)
2716                                 continue;
2717                         pud_clear_bad(pud);
2718                 }
2719                 err = apply_to_pmd_range(mm, pud, addr, next,
2720                                          fn, data, create, mask);
2721                 if (err)
2722                         break;
2723         } while (pud++, addr = next, addr != end);
2724
2725         return err;
2726 }
2727
2728 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2729                                      unsigned long addr, unsigned long end,
2730                                      pte_fn_t fn, void *data, bool create,
2731                                      pgtbl_mod_mask *mask)
2732 {
2733         p4d_t *p4d;
2734         unsigned long next;
2735         int err = 0;
2736
2737         if (create) {
2738                 p4d = p4d_alloc_track(mm, pgd, addr, mask);
2739                 if (!p4d)
2740                         return -ENOMEM;
2741         } else {
2742                 p4d = p4d_offset(pgd, addr);
2743         }
2744         do {
2745                 next = p4d_addr_end(addr, end);
2746                 if (p4d_none(*p4d) && !create)
2747                         continue;
2748                 if (WARN_ON_ONCE(p4d_leaf(*p4d)))
2749                         return -EINVAL;
2750                 if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) {
2751                         if (!create)
2752                                 continue;
2753                         p4d_clear_bad(p4d);
2754                 }
2755                 err = apply_to_pud_range(mm, p4d, addr, next,
2756                                          fn, data, create, mask);
2757                 if (err)
2758                         break;
2759         } while (p4d++, addr = next, addr != end);
2760
2761         return err;
2762 }
2763
2764 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2765                                  unsigned long size, pte_fn_t fn,
2766                                  void *data, bool create)
2767 {
2768         pgd_t *pgd;
2769         unsigned long start = addr, next;
2770         unsigned long end = addr + size;
2771         pgtbl_mod_mask mask = 0;
2772         int err = 0;
2773
2774         if (WARN_ON(addr >= end))
2775                 return -EINVAL;
2776
2777         pgd = pgd_offset(mm, addr);
2778         do {
2779                 next = pgd_addr_end(addr, end);
2780                 if (pgd_none(*pgd) && !create)
2781                         continue;
2782                 if (WARN_ON_ONCE(pgd_leaf(*pgd)))
2783                         return -EINVAL;
2784                 if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) {
2785                         if (!create)
2786                                 continue;
2787                         pgd_clear_bad(pgd);
2788                 }
2789                 err = apply_to_p4d_range(mm, pgd, addr, next,
2790                                          fn, data, create, &mask);
2791                 if (err)
2792                         break;
2793         } while (pgd++, addr = next, addr != end);
2794
2795         if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
2796                 arch_sync_kernel_mappings(start, start + size);
2797
2798         return err;
2799 }
2800
2801 /*
2802  * Scan a region of virtual memory, filling in page tables as necessary
2803  * and calling a provided function on each leaf page table.
2804  */
2805 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
2806                         unsigned long size, pte_fn_t fn, void *data)
2807 {
2808         return __apply_to_page_range(mm, addr, size, fn, data, true);
2809 }
2810 EXPORT_SYMBOL_GPL(apply_to_page_range);
2811
2812 /*
2813  * Scan a region of virtual memory, calling a provided function on
2814  * each leaf page table where it exists.
2815  *
2816  * Unlike apply_to_page_range, this does _not_ fill in page tables
2817  * where they are absent.
2818  */
2819 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
2820                                  unsigned long size, pte_fn_t fn, void *data)
2821 {
2822         return __apply_to_page_range(mm, addr, size, fn, data, false);
2823 }
2824 EXPORT_SYMBOL_GPL(apply_to_existing_page_range);
2825
2826 /*
2827  * handle_pte_fault chooses page fault handler according to an entry which was
2828  * read non-atomically.  Before making any commitment, on those architectures
2829  * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
2830  * parts, do_swap_page must check under lock before unmapping the pte and
2831  * proceeding (but do_wp_page is only called after already making such a check;
2832  * and do_anonymous_page can safely check later on).
2833  */
2834 static inline int pte_unmap_same(struct vm_fault *vmf)
2835 {
2836         int same = 1;
2837 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
2838         if (sizeof(pte_t) > sizeof(unsigned long)) {
2839                 spinlock_t *ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
2840                 spin_lock(ptl);
2841                 same = pte_same(*vmf->pte, vmf->orig_pte);
2842                 spin_unlock(ptl);
2843         }
2844 #endif
2845         pte_unmap(vmf->pte);
2846         vmf->pte = NULL;
2847         return same;
2848 }
2849
2850 static inline bool __wp_page_copy_user(struct page *dst, struct page *src,
2851                                        struct vm_fault *vmf)
2852 {
2853         bool ret;
2854         void *kaddr;
2855         void __user *uaddr;
2856         bool locked = false;
2857         struct vm_area_struct *vma = vmf->vma;
2858         struct mm_struct *mm = vma->vm_mm;
2859         unsigned long addr = vmf->address;
2860
2861         if (likely(src)) {
2862                 copy_user_highpage(dst, src, addr, vma);
2863                 return true;
2864         }
2865
2866         /*
2867          * If the source page was a PFN mapping, we don't have
2868          * a "struct page" for it. We do a best-effort copy by
2869          * just copying from the original user address. If that
2870          * fails, we just zero-fill it. Live with it.
2871          */
2872         kaddr = kmap_atomic(dst);
2873         uaddr = (void __user *)(addr & PAGE_MASK);
2874
2875         /*
2876          * On architectures with software "accessed" bits, we would
2877          * take a double page fault, so mark it accessed here.
2878          */
2879         if (!arch_has_hw_pte_young() && !pte_young(vmf->orig_pte)) {
2880                 pte_t entry;
2881
2882                 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2883                 locked = true;
2884                 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2885                         /*
2886                          * Other thread has already handled the fault
2887                          * and update local tlb only
2888                          */
2889                         update_mmu_tlb(vma, addr, vmf->pte);
2890                         ret = false;
2891                         goto pte_unlock;
2892                 }
2893
2894                 entry = pte_mkyoung(vmf->orig_pte);
2895                 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
2896                         update_mmu_cache(vma, addr, vmf->pte);
2897         }
2898
2899         /*
2900          * This really shouldn't fail, because the page is there
2901          * in the page tables. But it might just be unreadable,
2902          * in which case we just give up and fill the result with
2903          * zeroes.
2904          */
2905         if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2906                 if (locked)
2907                         goto warn;
2908
2909                 /* Re-validate under PTL if the page is still mapped */
2910                 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
2911                 locked = true;
2912                 if (!likely(pte_same(*vmf->pte, vmf->orig_pte))) {
2913                         /* The PTE changed under us, update local tlb */
2914                         update_mmu_tlb(vma, addr, vmf->pte);
2915                         ret = false;
2916                         goto pte_unlock;
2917                 }
2918
2919                 /*
2920                  * The same page can be mapped back since last copy attempt.
2921                  * Try to copy again under PTL.
2922                  */
2923                 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
2924                         /*
2925                          * Give a warn in case there can be some obscure
2926                          * use-case
2927                          */
2928 warn:
2929                         WARN_ON_ONCE(1);
2930                         clear_page(kaddr);
2931                 }
2932         }
2933
2934         ret = true;
2935
2936 pte_unlock:
2937         if (locked)
2938                 pte_unmap_unlock(vmf->pte, vmf->ptl);
2939         kunmap_atomic(kaddr);
2940         flush_dcache_page(dst);
2941
2942         return ret;
2943 }
2944
2945 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
2946 {
2947         struct file *vm_file = vma->vm_file;
2948
2949         if (vm_file)
2950                 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
2951
2952         /*
2953          * Special mappings (e.g. VDSO) do not have any file so fake
2954          * a default GFP_KERNEL for them.
2955          */
2956         return GFP_KERNEL;
2957 }
2958
2959 /*
2960  * Notify the address space that the page is about to become writable so that
2961  * it can prohibit this or wait for the page to get into an appropriate state.
2962  *
2963  * We do this without the lock held, so that it can sleep if it needs to.
2964  */
2965 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf)
2966 {
2967         vm_fault_t ret;
2968         struct page *page = vmf->page;
2969         unsigned int old_flags = vmf->flags;
2970
2971         vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
2972
2973         if (vmf->vma->vm_file &&
2974             IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
2975                 return VM_FAULT_SIGBUS;
2976
2977         ret = vmf->vma->vm_ops->page_mkwrite(vmf);
2978         /* Restore original flags so that caller is not surprised */
2979         vmf->flags = old_flags;
2980         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
2981                 return ret;
2982         if (unlikely(!(ret & VM_FAULT_LOCKED))) {
2983                 lock_page(page);
2984                 if (!page->mapping) {
2985                         unlock_page(page);
2986                         return 0; /* retry */
2987                 }
2988                 ret |= VM_FAULT_LOCKED;
2989         } else
2990                 VM_BUG_ON_PAGE(!PageLocked(page), page);
2991         return ret;
2992 }
2993
2994 /*
2995  * Handle dirtying of a page in shared file mapping on a write fault.
2996  *
2997  * The function expects the page to be locked and unlocks it.
2998  */
2999 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
3000 {
3001         struct vm_area_struct *vma = vmf->vma;
3002         struct address_space *mapping;
3003         struct page *page = vmf->page;
3004         bool dirtied;
3005         bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
3006
3007         dirtied = set_page_dirty(page);
3008         VM_BUG_ON_PAGE(PageAnon(page), page);
3009         /*
3010          * Take a local copy of the address_space - page.mapping may be zeroed
3011          * by truncate after unlock_page().   The address_space itself remains
3012          * pinned by vma->vm_file's reference.  We rely on unlock_page()'s
3013          * release semantics to prevent the compiler from undoing this copying.
3014          */
3015         mapping = page_rmapping(page);
3016         unlock_page(page);
3017
3018         if (!page_mkwrite)
3019                 file_update_time(vma->vm_file);
3020
3021         /*
3022          * Throttle page dirtying rate down to writeback speed.
3023          *
3024          * mapping may be NULL here because some device drivers do not
3025          * set page.mapping but still dirty their pages
3026          *
3027          * Drop the mmap_lock before waiting on IO, if we can. The file
3028          * is pinning the mapping, as per above.
3029          */
3030         if ((dirtied || page_mkwrite) && mapping) {
3031                 struct file *fpin;
3032
3033                 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
3034                 balance_dirty_pages_ratelimited(mapping);
3035                 if (fpin) {
3036                         fput(fpin);
3037                         return VM_FAULT_COMPLETED;
3038                 }
3039         }
3040
3041         return 0;
3042 }
3043
3044 /*
3045  * Handle write page faults for pages that can be reused in the current vma
3046  *
3047  * This can happen either due to the mapping being with the VM_SHARED flag,
3048  * or due to us being the last reference standing to the page. In either
3049  * case, all we need to do here is to mark the page as writable and update
3050  * any related book-keeping.
3051  */
3052 static inline void wp_page_reuse(struct vm_fault *vmf)
3053         __releases(vmf->ptl)
3054 {
3055         struct vm_area_struct *vma = vmf->vma;
3056         struct page *page = vmf->page;
3057         pte_t entry;
3058
3059         VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE));
3060         VM_BUG_ON(page && PageAnon(page) && !PageAnonExclusive(page));
3061
3062         /*
3063          * Clear the pages cpupid information as the existing
3064          * information potentially belongs to a now completely
3065          * unrelated process.
3066          */
3067         if (page)
3068                 page_cpupid_xchg_last(page, (1 << LAST_CPUPID_SHIFT) - 1);
3069
3070         flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3071         entry = pte_mkyoung(vmf->orig_pte);
3072         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3073         if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
3074                 update_mmu_cache(vma, vmf->address, vmf->pte);
3075         pte_unmap_unlock(vmf->pte, vmf->ptl);
3076         count_vm_event(PGREUSE);
3077 }
3078
3079 /*
3080  * Handle the case of a page which we actually need to copy to a new page,
3081  * either due to COW or unsharing.
3082  *
3083  * Called with mmap_lock locked and the old page referenced, but
3084  * without the ptl held.
3085  *
3086  * High level logic flow:
3087  *
3088  * - Allocate a page, copy the content of the old page to the new one.
3089  * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
3090  * - Take the PTL. If the pte changed, bail out and release the allocated page
3091  * - If the pte is still the way we remember it, update the page table and all
3092  *   relevant references. This includes dropping the reference the page-table
3093  *   held to the old page, as well as updating the rmap.
3094  * - In any case, unlock the PTL and drop the reference we took to the old page.
3095  */
3096 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
3097 {
3098         const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3099         struct vm_area_struct *vma = vmf->vma;
3100         struct mm_struct *mm = vma->vm_mm;
3101         struct page *old_page = vmf->page;
3102         struct page *new_page = NULL;
3103         pte_t entry;
3104         int page_copied = 0;
3105         struct mmu_notifier_range range;
3106
3107         delayacct_wpcopy_start();
3108
3109         if (unlikely(anon_vma_prepare(vma)))
3110                 goto oom;
3111
3112         if (is_zero_pfn(pte_pfn(vmf->orig_pte))) {
3113                 new_page = alloc_zeroed_user_highpage_movable(vma,
3114                                                               vmf->address);
3115                 if (!new_page)
3116                         goto oom;
3117         } else {
3118                 new_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma,
3119                                 vmf->address);
3120                 if (!new_page)
3121                         goto oom;
3122
3123                 if (!__wp_page_copy_user(new_page, old_page, vmf)) {
3124                         /*
3125                          * COW failed, if the fault was solved by other,
3126                          * it's fine. If not, userspace would re-fault on
3127                          * the same address and we will handle the fault
3128                          * from the second attempt.
3129                          */
3130                         put_page(new_page);
3131                         if (old_page)
3132                                 put_page(old_page);
3133
3134                         delayacct_wpcopy_end();
3135                         return 0;
3136                 }
3137                 kmsan_copy_page_meta(new_page, old_page);
3138         }
3139
3140         if (mem_cgroup_charge(page_folio(new_page), mm, GFP_KERNEL))
3141                 goto oom_free_new;
3142         cgroup_throttle_swaprate(new_page, GFP_KERNEL);
3143
3144         __SetPageUptodate(new_page);
3145
3146         mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma, mm,
3147                                 vmf->address & PAGE_MASK,
3148                                 (vmf->address & PAGE_MASK) + PAGE_SIZE);
3149         mmu_notifier_invalidate_range_start(&range);
3150
3151         /*
3152          * Re-check the pte - we dropped the lock
3153          */
3154         vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
3155         if (likely(pte_same(*vmf->pte, vmf->orig_pte))) {
3156                 if (old_page) {
3157                         if (!PageAnon(old_page)) {
3158                                 dec_mm_counter_fast(mm,
3159                                                 mm_counter_file(old_page));
3160                                 inc_mm_counter_fast(mm, MM_ANONPAGES);
3161                         }
3162                 } else {
3163                         inc_mm_counter_fast(mm, MM_ANONPAGES);
3164                 }
3165                 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3166                 entry = mk_pte(new_page, vma->vm_page_prot);
3167                 entry = pte_sw_mkyoung(entry);
3168                 if (unlikely(unshare)) {
3169                         if (pte_soft_dirty(vmf->orig_pte))
3170                                 entry = pte_mksoft_dirty(entry);
3171                         if (pte_uffd_wp(vmf->orig_pte))
3172                                 entry = pte_mkuffd_wp(entry);
3173                 } else {
3174                         entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3175                 }
3176
3177                 /*
3178                  * Clear the pte entry and flush it first, before updating the
3179                  * pte with the new entry, to keep TLBs on different CPUs in
3180                  * sync. This code used to set the new PTE then flush TLBs, but
3181                  * that left a window where the new PTE could be loaded into
3182                  * some TLBs while the old PTE remains in others.
3183                  */
3184                 ptep_clear_flush_notify(vma, vmf->address, vmf->pte);
3185                 page_add_new_anon_rmap(new_page, vma, vmf->address);
3186                 lru_cache_add_inactive_or_unevictable(new_page, vma);
3187                 /*
3188                  * We call the notify macro here because, when using secondary
3189                  * mmu page tables (such as kvm shadow page tables), we want the
3190                  * new page to be mapped directly into the secondary page table.
3191                  */
3192                 BUG_ON(unshare && pte_write(entry));
3193                 set_pte_at_notify(mm, vmf->address, vmf->pte, entry);
3194                 update_mmu_cache(vma, vmf->address, vmf->pte);
3195                 if (old_page) {
3196                         /*
3197                          * Only after switching the pte to the new page may
3198                          * we remove the mapcount here. Otherwise another
3199                          * process may come and find the rmap count decremented
3200                          * before the pte is switched to the new page, and
3201                          * "reuse" the old page writing into it while our pte
3202                          * here still points into it and can be read by other
3203                          * threads.
3204                          *
3205                          * The critical issue is to order this
3206                          * page_remove_rmap with the ptp_clear_flush above.
3207                          * Those stores are ordered by (if nothing else,)
3208                          * the barrier present in the atomic_add_negative
3209                          * in page_remove_rmap.
3210                          *
3211                          * Then the TLB flush in ptep_clear_flush ensures that
3212                          * no process can access the old page before the
3213                          * decremented mapcount is visible. And the old page
3214                          * cannot be reused until after the decremented
3215                          * mapcount is visible. So transitively, TLBs to
3216                          * old page will be flushed before it can be reused.
3217                          */
3218                         page_remove_rmap(old_page, vma, false);
3219                 }
3220
3221                 /* Free the old page.. */
3222                 new_page = old_page;
3223                 page_copied = 1;
3224         } else {
3225                 update_mmu_tlb(vma, vmf->address, vmf->pte);
3226         }
3227
3228         if (new_page)
3229                 put_page(new_page);
3230
3231         pte_unmap_unlock(vmf->pte, vmf->ptl);
3232         /*
3233          * No need to double call mmu_notifier->invalidate_range() callback as
3234          * the above ptep_clear_flush_notify() did already call it.
3235          */
3236         mmu_notifier_invalidate_range_only_end(&range);
3237         if (old_page) {
3238                 if (page_copied)
3239                         free_swap_cache(old_page);
3240                 put_page(old_page);
3241         }
3242
3243         delayacct_wpcopy_end();
3244         return (page_copied && !unshare) ? VM_FAULT_WRITE : 0;
3245 oom_free_new:
3246         put_page(new_page);
3247 oom:
3248         if (old_page)
3249                 put_page(old_page);
3250
3251         delayacct_wpcopy_end();
3252         return VM_FAULT_OOM;
3253 }
3254
3255 /**
3256  * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
3257  *                        writeable once the page is prepared
3258  *
3259  * @vmf: structure describing the fault
3260  *
3261  * This function handles all that is needed to finish a write page fault in a
3262  * shared mapping due to PTE being read-only once the mapped page is prepared.
3263  * It handles locking of PTE and modifying it.
3264  *
3265  * The function expects the page to be locked or other protection against
3266  * concurrent faults / writeback (such as DAX radix tree locks).
3267  *
3268  * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before
3269  * we acquired PTE lock.
3270  */
3271 vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf)
3272 {
3273         WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
3274         vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
3275                                        &vmf->ptl);
3276         /*
3277          * We might have raced with another page fault while we released the
3278          * pte_offset_map_lock.
3279          */
3280         if (!pte_same(*vmf->pte, vmf->orig_pte)) {
3281                 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
3282                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3283                 return VM_FAULT_NOPAGE;
3284         }
3285         wp_page_reuse(vmf);
3286         return 0;
3287 }
3288
3289 /*
3290  * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
3291  * mapping
3292  */
3293 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
3294 {
3295         struct vm_area_struct *vma = vmf->vma;
3296
3297         if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
3298                 vm_fault_t ret;
3299
3300                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3301                 vmf->flags |= FAULT_FLAG_MKWRITE;
3302                 ret = vma->vm_ops->pfn_mkwrite(vmf);
3303                 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
3304                         return ret;
3305                 return finish_mkwrite_fault(vmf);
3306         }
3307         wp_page_reuse(vmf);
3308         return VM_FAULT_WRITE;
3309 }
3310
3311 static vm_fault_t wp_page_shared(struct vm_fault *vmf)
3312         __releases(vmf->ptl)
3313 {
3314         struct vm_area_struct *vma = vmf->vma;
3315         vm_fault_t ret = VM_FAULT_WRITE;
3316
3317         get_page(vmf->page);
3318
3319         if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
3320                 vm_fault_t tmp;
3321
3322                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3323                 tmp = do_page_mkwrite(vmf);
3324                 if (unlikely(!tmp || (tmp &
3325                                       (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3326                         put_page(vmf->page);
3327                         return tmp;
3328                 }
3329                 tmp = finish_mkwrite_fault(vmf);
3330                 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3331                         unlock_page(vmf->page);
3332                         put_page(vmf->page);
3333                         return tmp;
3334                 }
3335         } else {
3336                 wp_page_reuse(vmf);
3337                 lock_page(vmf->page);
3338         }
3339         ret |= fault_dirty_shared_page(vmf);
3340         put_page(vmf->page);
3341
3342         return ret;
3343 }
3344
3345 /*
3346  * This routine handles present pages, when
3347  * * users try to write to a shared page (FAULT_FLAG_WRITE)
3348  * * GUP wants to take a R/O pin on a possibly shared anonymous page
3349  *   (FAULT_FLAG_UNSHARE)
3350  *
3351  * It is done by copying the page to a new address and decrementing the
3352  * shared-page counter for the old page.
3353  *
3354  * Note that this routine assumes that the protection checks have been
3355  * done by the caller (the low-level page fault routine in most cases).
3356  * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've
3357  * done any necessary COW.
3358  *
3359  * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even
3360  * though the page will change only once the write actually happens. This
3361  * avoids a few races, and potentially makes it more efficient.
3362  *
3363  * We enter with non-exclusive mmap_lock (to exclude vma changes,
3364  * but allow concurrent faults), with pte both mapped and locked.
3365  * We return with mmap_lock still held, but pte unmapped and unlocked.
3366  */
3367 static vm_fault_t do_wp_page(struct vm_fault *vmf)
3368         __releases(vmf->ptl)
3369 {
3370         const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3371         struct vm_area_struct *vma = vmf->vma;
3372         struct folio *folio;
3373
3374         VM_BUG_ON(unshare && (vmf->flags & FAULT_FLAG_WRITE));
3375         VM_BUG_ON(!unshare && !(vmf->flags & FAULT_FLAG_WRITE));
3376
3377         if (likely(!unshare)) {
3378                 if (userfaultfd_pte_wp(vma, *vmf->pte)) {
3379                         pte_unmap_unlock(vmf->pte, vmf->ptl);
3380                         return handle_userfault(vmf, VM_UFFD_WP);
3381                 }
3382
3383                 /*
3384                  * Userfaultfd write-protect can defer flushes. Ensure the TLB
3385                  * is flushed in this case before copying.
3386                  */
3387                 if (unlikely(userfaultfd_wp(vmf->vma) &&
3388                              mm_tlb_flush_pending(vmf->vma->vm_mm)))
3389                         flush_tlb_page(vmf->vma, vmf->address);
3390         }
3391
3392         vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
3393         if (!vmf->page) {
3394                 if (unlikely(unshare)) {
3395                         /* No anonymous page -> nothing to do. */
3396                         pte_unmap_unlock(vmf->pte, vmf->ptl);
3397                         return 0;
3398                 }
3399
3400                 /*
3401                  * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
3402                  * VM_PFNMAP VMA.
3403                  *
3404                  * We should not cow pages in a shared writeable mapping.
3405                  * Just mark the pages writable and/or call ops->pfn_mkwrite.
3406                  */
3407                 if ((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3408                                      (VM_WRITE|VM_SHARED))
3409                         return wp_pfn_shared(vmf);
3410
3411                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3412                 return wp_page_copy(vmf);
3413         }
3414
3415         /*
3416          * Take out anonymous pages first, anonymous shared vmas are
3417          * not dirty accountable.
3418          */
3419         folio = page_folio(vmf->page);
3420         if (folio_test_anon(folio)) {
3421                 /*
3422                  * If the page is exclusive to this process we must reuse the
3423                  * page without further checks.
3424                  */
3425                 if (PageAnonExclusive(vmf->page))
3426                         goto reuse;
3427
3428                 /*
3429                  * We have to verify under folio lock: these early checks are
3430                  * just an optimization to avoid locking the folio and freeing
3431                  * the swapcache if there is little hope that we can reuse.
3432                  *
3433                  * KSM doesn't necessarily raise the folio refcount.
3434                  */
3435                 if (folio_test_ksm(folio) || folio_ref_count(folio) > 3)
3436                         goto copy;
3437                 if (!folio_test_lru(folio))
3438                         /*
3439                          * Note: We cannot easily detect+handle references from
3440                          * remote LRU pagevecs or references to LRU folios.
3441                          */
3442                         lru_add_drain();
3443                 if (folio_ref_count(folio) > 1 + folio_test_swapcache(folio))
3444                         goto copy;
3445                 if (!folio_trylock(folio))
3446                         goto copy;
3447                 if (folio_test_swapcache(folio))
3448                         folio_free_swap(folio);
3449                 if (folio_test_ksm(folio) || folio_ref_count(folio) != 1) {
3450                         folio_unlock(folio);
3451                         goto copy;
3452                 }
3453                 /*
3454                  * Ok, we've got the only folio reference from our mapping
3455                  * and the folio is locked, it's dark out, and we're wearing
3456                  * sunglasses. Hit it.
3457                  */
3458                 page_move_anon_rmap(vmf->page, vma);
3459                 folio_unlock(folio);
3460 reuse:
3461                 if (unlikely(unshare)) {
3462                         pte_unmap_unlock(vmf->pte, vmf->ptl);
3463                         return 0;
3464                 }
3465                 wp_page_reuse(vmf);
3466                 return VM_FAULT_WRITE;
3467         } else if (unshare) {
3468                 /* No anonymous page -> nothing to do. */
3469                 pte_unmap_unlock(vmf->pte, vmf->ptl);
3470                 return 0;
3471         } else if (unlikely((vma->vm_flags & (VM_WRITE|VM_SHARED)) ==
3472                                         (VM_WRITE|VM_SHARED))) {
3473                 return wp_page_shared(vmf);
3474         }
3475 copy:
3476         /*
3477          * Ok, we need to copy. Oh, well..
3478          */
3479         get_page(vmf->page);
3480
3481         pte_unmap_unlock(vmf->pte, vmf->ptl);
3482 #ifdef CONFIG_KSM
3483         if (PageKsm(vmf->page))
3484                 count_vm_event(COW_KSM);
3485 #endif
3486         return wp_page_copy(vmf);
3487 }
3488
3489 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
3490                 unsigned long start_addr, unsigned long end_addr,
3491                 struct zap_details *details)
3492 {
3493         zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
3494 }
3495
3496 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
3497                                             pgoff_t first_index,
3498                                             pgoff_t last_index,
3499                                             struct zap_details *details)
3500 {
3501         struct vm_area_struct *vma;
3502         pgoff_t vba, vea, zba, zea;
3503
3504         vma_interval_tree_foreach(vma, root, first_index, last_index) {
3505                 vba = vma->vm_pgoff;
3506                 vea = vba + vma_pages(vma) - 1;
3507                 zba = max(first_index, vba);
3508                 zea = min(last_index, vea);
3509
3510                 unmap_mapping_range_vma(vma,
3511                         ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
3512                         ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3513                                 details);
3514         }
3515 }
3516
3517 /**
3518  * unmap_mapping_folio() - Unmap single folio from processes.
3519  * @folio: The locked folio to be unmapped.
3520  *
3521  * Unmap this folio from any userspace process which still has it mmaped.
3522  * Typically, for efficiency, the range of nearby pages has already been
3523  * unmapped by unmap_mapping_pages() or unmap_mapping_range().  But once
3524  * truncation or invalidation holds the lock on a folio, it may find that
3525  * the page has been remapped again: and then uses unmap_mapping_folio()
3526  * to unmap it finally.
3527  */
3528 void unmap_mapping_folio(struct folio *folio)
3529 {
3530         struct address_space *mapping = folio->mapping;
3531         struct zap_details details = { };
3532         pgoff_t first_index;
3533         pgoff_t last_index;
3534
3535         VM_BUG_ON(!folio_test_locked(folio));
3536
3537         first_index = folio->index;
3538         last_index = folio->index + folio_nr_pages(folio) - 1;
3539
3540         details.even_cows = false;
3541         details.single_folio = folio;
3542         details.zap_flags = ZAP_FLAG_DROP_MARKER;
3543
3544         i_mmap_lock_read(mapping);
3545         if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3546                 unmap_mapping_range_tree(&mapping->i_mmap, first_index,
3547                                          last_index, &details);
3548         i_mmap_unlock_read(mapping);
3549 }
3550
3551 /**
3552  * unmap_mapping_pages() - Unmap pages from processes.
3553  * @mapping: The address space containing pages to be unmapped.
3554  * @start: Index of first page to be unmapped.
3555  * @nr: Number of pages to be unmapped.  0 to unmap to end of file.
3556  * @even_cows: Whether to unmap even private COWed pages.
3557  *
3558  * Unmap the pages in this address space from any userspace process which
3559  * has them mmaped.  Generally, you want to remove COWed pages as well when
3560  * a file is being truncated, but not when invalidating pages from the page
3561  * cache.
3562  */
3563 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
3564                 pgoff_t nr, bool even_cows)
3565 {
3566         struct zap_details details = { };
3567         pgoff_t first_index = start;
3568         pgoff_t last_index = start + nr - 1;
3569
3570         details.even_cows = even_cows;
3571         if (last_index < first_index)
3572                 last_index = ULONG_MAX;
3573
3574         i_mmap_lock_read(mapping);
3575         if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3576                 unmap_mapping_range_tree(&mapping->i_mmap, first_index,
3577                                          last_index, &details);
3578         i_mmap_unlock_read(mapping);
3579 }
3580 EXPORT_SYMBOL_GPL(unmap_mapping_pages);
3581
3582 /**
3583  * unmap_mapping_range - unmap the portion of all mmaps in the specified
3584  * address_space corresponding to the specified byte range in the underlying
3585  * file.
3586  *
3587  * @mapping: the address space containing mmaps to be unmapped.
3588  * @holebegin: byte in first page to unmap, relative to the start of
3589  * the underlying file.  This will be rounded down to a PAGE_SIZE
3590  * boundary.  Note that this is different from truncate_pagecache(), which
3591  * must keep the partial page.  In contrast, we must get rid of
3592  * partial pages.
3593  * @holelen: size of prospective hole in bytes.  This will be rounded
3594  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
3595  * end of the file.
3596  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
3597  * but 0 when invalidating pagecache, don't throw away private data.
3598  */
3599 void unmap_mapping_range(struct address_space *mapping,
3600                 loff_t const holebegin, loff_t const holelen, int even_cows)
3601 {
3602         pgoff_t hba = holebegin >> PAGE_SHIFT;
3603         pgoff_t hlen = (holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3604
3605         /* Check for overflow. */
3606         if (sizeof(holelen) > sizeof(hlen)) {
3607                 long long holeend =
3608                         (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
3609                 if (holeend & ~(long long)ULONG_MAX)
3610                         hlen = ULONG_MAX - hba + 1;
3611         }
3612
3613         unmap_mapping_pages(mapping, hba, hlen, even_cows);
3614 }
3615 EXPORT_SYMBOL(unmap_mapping_range);
3616
3617 /*
3618  * Restore a potential device exclusive pte to a working pte entry
3619  */
3620 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf)
3621 {
3622         struct folio *folio = page_folio(vmf->page);
3623         struct vm_area_struct *vma = vmf->vma;
3624         struct mmu_notifier_range range;
3625
3626         if (!folio_lock_or_retry(folio, vma->vm_mm, vmf->flags))
3627                 return VM_FAULT_RETRY;
3628         mmu_notifier_range_init_owner(&range, MMU_NOTIFY_EXCLUSIVE, 0, vma,
3629                                 vma->vm_mm, vmf->address & PAGE_MASK,
3630                                 (vmf->address & PAGE_MASK) + PAGE_SIZE, NULL);
3631         mmu_notifier_invalidate_range_start(&range);
3632
3633         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3634                                 &vmf->ptl);
3635         if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3636                 restore_exclusive_pte(vma, vmf->page, vmf->address, vmf->pte);
3637
3638         pte_unmap_unlock(vmf->pte, vmf->ptl);
3639         folio_unlock(folio);
3640
3641         mmu_notifier_invalidate_range_end(&range);
3642         return 0;
3643 }
3644
3645 static inline bool should_try_to_free_swap(struct folio *folio,
3646                                            struct vm_area_struct *vma,
3647                                            unsigned int fault_flags)
3648 {
3649         if (!folio_test_swapcache(folio))
3650                 return false;
3651         if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
3652             folio_test_mlocked(folio))
3653                 return true;
3654         /*
3655          * If we want to map a page that's in the swapcache writable, we
3656          * have to detect via the refcount if we're really the exclusive
3657          * user. Try freeing the swapcache to get rid of the swapcache
3658          * reference only in case it's likely that we'll be the exlusive user.
3659          */
3660         return (fault_flags & FAULT_FLAG_WRITE) && !folio_test_ksm(folio) &&
3661                 folio_ref_count(folio) == 2;
3662 }
3663
3664 static vm_fault_t pte_marker_clear(struct vm_fault *vmf)
3665 {
3666         vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
3667                                        vmf->address, &vmf->ptl);
3668         /*
3669          * Be careful so that we will only recover a special uffd-wp pte into a
3670          * none pte.  Otherwise it means the pte could have changed, so retry.
3671          */
3672         if (is_pte_marker(*vmf->pte))
3673                 pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte);
3674         pte_unmap_unlock(vmf->pte, vmf->ptl);
3675         return 0;
3676 }
3677
3678 /*
3679  * This is actually a page-missing access, but with uffd-wp special pte
3680  * installed.  It means this pte was wr-protected before being unmapped.
3681  */
3682 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf)
3683 {
3684         /*
3685          * Just in case there're leftover special ptes even after the region
3686          * got unregistered - we can simply clear them.  We can also do that
3687          * proactively when e.g. when we do UFFDIO_UNREGISTER upon some uffd-wp
3688          * ranges, but it should be more efficient to be done lazily here.
3689          */
3690         if (unlikely(!userfaultfd_wp(vmf->vma) || vma_is_anonymous(vmf->vma)))
3691                 return pte_marker_clear(vmf);
3692
3693         /* do_fault() can handle pte markers too like none pte */
3694         return do_fault(vmf);
3695 }
3696
3697 static vm_fault_t handle_pte_marker(struct vm_fault *vmf)
3698 {
3699         swp_entry_t entry = pte_to_swp_entry(vmf->orig_pte);
3700         unsigned long marker = pte_marker_get(entry);
3701
3702         /*
3703          * PTE markers should always be with file-backed memories, and the
3704          * marker should never be empty.  If anything weird happened, the best
3705          * thing to do is to kill the process along with its mm.
3706          */
3707         if (WARN_ON_ONCE(vma_is_anonymous(vmf->vma) || !marker))
3708                 return VM_FAULT_SIGBUS;
3709
3710         if (pte_marker_entry_uffd_wp(entry))
3711                 return pte_marker_handle_uffd_wp(vmf);
3712
3713         /* This is an unknown pte marker */
3714         return VM_FAULT_SIGBUS;
3715 }
3716
3717 /*
3718  * We enter with non-exclusive mmap_lock (to exclude vma changes,
3719  * but allow concurrent faults), and pte mapped but not yet locked.
3720  * We return with pte unmapped and unlocked.
3721  *
3722  * We return with the mmap_lock locked or unlocked in the same cases
3723  * as does filemap_fault().
3724  */
3725 vm_fault_t do_swap_page(struct vm_fault *vmf)
3726 {
3727         struct vm_area_struct *vma = vmf->vma;
3728         struct folio *swapcache, *folio = NULL;
3729         struct page *page;
3730         struct swap_info_struct *si = NULL;
3731         rmap_t rmap_flags = RMAP_NONE;
3732         bool exclusive = false;
3733         swp_entry_t entry;
3734         pte_t pte;
3735         int locked;
3736         vm_fault_t ret = 0;
3737         void *shadow = NULL;
3738
3739         if (!pte_unmap_same(vmf))
3740                 goto out;
3741
3742         entry = pte_to_swp_entry(vmf->orig_pte);
3743         if (unlikely(non_swap_entry(entry))) {
3744                 if (is_migration_entry(entry)) {
3745                         migration_entry_wait(vma->vm_mm, vmf->pmd,
3746                                              vmf->address);
3747                 } else if (is_device_exclusive_entry(entry)) {
3748                         vmf->page = pfn_swap_entry_to_page(entry);
3749                         ret = remove_device_exclusive_entry(vmf);
3750                 } else if (is_device_private_entry(entry)) {
3751                         vmf->page = pfn_swap_entry_to_page(entry);
3752                         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3753                                         vmf->address, &vmf->ptl);
3754                         if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
3755                                 spin_unlock(vmf->ptl);
3756                                 goto out;
3757                         }
3758
3759                         /*
3760                          * Get a page reference while we know the page can't be
3761                          * freed.
3762                          */
3763                         get_page(vmf->page);
3764                         pte_unmap_unlock(vmf->pte, vmf->ptl);
3765                         ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
3766                         put_page(vmf->page);
3767                 } else if (is_hwpoison_entry(entry)) {
3768                         ret = VM_FAULT_HWPOISON;
3769                 } else if (is_swapin_error_entry(entry)) {
3770                         ret = VM_FAULT_SIGBUS;
3771                 } else if (is_pte_marker_entry(entry)) {
3772                         ret = handle_pte_marker(vmf);
3773                 } else {
3774                         print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
3775                         ret = VM_FAULT_SIGBUS;
3776                 }
3777                 goto out;
3778         }
3779
3780         /* Prevent swapoff from happening to us. */
3781         si = get_swap_device(entry);
3782         if (unlikely(!si))
3783                 goto out;
3784
3785         folio = swap_cache_get_folio(entry, vma, vmf->address);
3786         if (folio)
3787                 page = folio_file_page(folio, swp_offset(entry));
3788         swapcache = folio;
3789
3790         if (!folio) {
3791                 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
3792                     __swap_count(entry) == 1) {
3793                         /* skip swapcache */
3794                         folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0,
3795                                                 vma, vmf->address, false);
3796                         page = &folio->page;
3797                         if (folio) {
3798                                 __folio_set_locked(folio);
3799                                 __folio_set_swapbacked(folio);
3800
3801                                 if (mem_cgroup_swapin_charge_folio(folio,
3802                                                         vma->vm_mm, GFP_KERNEL,
3803                                                         entry)) {
3804                                         ret = VM_FAULT_OOM;
3805                                         goto out_page;
3806                                 }
3807                                 mem_cgroup_swapin_uncharge_swap(entry);
3808
3809                                 shadow = get_shadow_from_swap_cache(entry);
3810                                 if (shadow)
3811                                         workingset_refault(folio, shadow);
3812
3813                                 folio_add_lru(folio);
3814
3815                                 /* To provide entry to swap_readpage() */
3816                                 folio_set_swap_entry(folio, entry);
3817                                 swap_readpage(page, true, NULL);
3818                                 folio->private = NULL;
3819                         }
3820                 } else {
3821                         page = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
3822                                                 vmf);
3823                         if (page)
3824                                 folio = page_folio(page);
3825                         swapcache = folio;
3826                 }
3827
3828                 if (!folio) {
3829                         /*
3830                          * Back out if somebody else faulted in this pte
3831                          * while we released the pte lock.
3832                          */
3833                         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
3834                                         vmf->address, &vmf->ptl);
3835                         if (likely(pte_same(*vmf->pte, vmf->orig_pte)))
3836                                 ret = VM_FAULT_OOM;
3837                         goto unlock;
3838                 }
3839
3840                 /* Had to read the page from swap area: Major fault */
3841                 ret = VM_FAULT_MAJOR;
3842                 count_vm_event(PGMAJFAULT);
3843                 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
3844         } else if (PageHWPoison(page)) {
3845                 /*
3846                  * hwpoisoned dirty swapcache pages are kept for killing
3847                  * owner processes (which may be unknown at hwpoison time)
3848                  */
3849                 ret = VM_FAULT_HWPOISON;
3850                 goto out_release;
3851         }
3852
3853         locked = folio_lock_or_retry(folio, vma->vm_mm, vmf->flags);
3854
3855         if (!locked) {
3856                 ret |= VM_FAULT_RETRY;
3857                 goto out_release;
3858         }
3859
3860         if (swapcache) {
3861                 /*
3862                  * Make sure folio_free_swap() or swapoff did not release the
3863                  * swapcache from under us.  The page pin, and pte_same test
3864                  * below, are not enough to exclude that.  Even if it is still
3865                  * swapcache, we need to check that the page's swap has not
3866                  * changed.
3867                  */
3868                 if (unlikely(!folio_test_swapcache(folio) ||
3869                              page_private(page) != entry.val))
3870                         goto out_page;
3871
3872                 /*
3873                  * KSM sometimes has to copy on read faults, for example, if
3874                  * page->index of !PageKSM() pages would be nonlinear inside the
3875                  * anon VMA -- PageKSM() is lost on actual swapout.
3876                  */
3877                 page = ksm_might_need_to_copy(page, vma, vmf->address);
3878                 if (unlikely(!page)) {
3879                         ret = VM_FAULT_OOM;
3880                         goto out_page;
3881                 }
3882                 folio = page_folio(page);
3883
3884                 /*
3885                  * If we want to map a page that's in the swapcache writable, we
3886                  * have to detect via the refcount if we're really the exclusive
3887                  * owner. Try removing the extra reference from the local LRU
3888                  * pagevecs if required.
3889                  */
3890                 if ((vmf->flags & FAULT_FLAG_WRITE) && folio == swapcache &&
3891                     !folio_test_ksm(folio) && !folio_test_lru(folio))
3892                         lru_add_drain();
3893         }
3894
3895         cgroup_throttle_swaprate(page, GFP_KERNEL);
3896
3897         /*
3898          * Back out if somebody else already faulted in this pte.
3899          */
3900         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
3901                         &vmf->ptl);
3902         if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte)))
3903                 goto out_nomap;
3904
3905         if (unlikely(!folio_test_uptodate(folio))) {
3906                 ret = VM_FAULT_SIGBUS;
3907                 goto out_nomap;
3908         }
3909
3910         /*
3911          * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte
3912          * must never point at an anonymous page in the swapcache that is
3913          * PG_anon_exclusive. Sanity check that this holds and especially, that
3914          * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity
3915          * check after taking the PT lock and making sure that nobody
3916          * concurrently faulted in this page and set PG_anon_exclusive.
3917          */
3918         BUG_ON(!folio_test_anon(folio) && folio_test_mappedtodisk(folio));
3919         BUG_ON(folio_test_anon(folio) && PageAnonExclusive(page));
3920
3921         /*
3922          * Check under PT lock (to protect against concurrent fork() sharing
3923          * the swap entry concurrently) for certainly exclusive pages.
3924          */
3925         if (!folio_test_ksm(folio)) {
3926                 /*
3927                  * Note that pte_swp_exclusive() == false for architectures
3928                  * without __HAVE_ARCH_PTE_SWP_EXCLUSIVE.
3929                  */
3930                 exclusive = pte_swp_exclusive(vmf->orig_pte);
3931                 if (folio != swapcache) {
3932                         /*
3933                          * We have a fresh page that is not exposed to the
3934                          * swapcache -> certainly exclusive.
3935                          */
3936                         exclusive = true;
3937                 } else if (exclusive && folio_test_writeback(folio) &&
3938                           data_race(si->flags & SWP_STABLE_WRITES)) {
3939                         /*
3940                          * This is tricky: not all swap backends support
3941                          * concurrent page modifications while under writeback.
3942                          *
3943                          * So if we stumble over such a page in the swapcache
3944                          * we must not set the page exclusive, otherwise we can
3945                          * map it writable without further checks and modify it
3946                          * while still under writeback.
3947                          *
3948                          * For these problematic swap backends, simply drop the
3949                          * exclusive marker: this is perfectly fine as we start
3950                          * writeback only if we fully unmapped the page and
3951                          * there are no unexpected references on the page after
3952                          * unmapping succeeded. After fully unmapped, no
3953                          * further GUP references (FOLL_GET and FOLL_PIN) can
3954                          * appear, so dropping the exclusive marker and mapping
3955                          * it only R/O is fine.
3956                          */
3957                         exclusive = false;
3958                 }
3959         }
3960
3961         /*
3962          * Remove the swap entry and conditionally try to free up the swapcache.
3963          * We're already holding a reference on the page but haven't mapped it
3964          * yet.
3965          */
3966         swap_free(entry);
3967         if (should_try_to_free_swap(folio, vma, vmf->flags))
3968                 folio_free_swap(folio);
3969
3970         inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
3971         dec_mm_counter_fast(vma->vm_mm, MM_SWAPENTS);
3972         pte = mk_pte(page, vma->vm_page_prot);
3973
3974         /*
3975          * Same logic as in do_wp_page(); however, optimize for pages that are
3976          * certainly not shared either because we just allocated them without
3977          * exposing them to the swapcache or because the swap entry indicates
3978          * exclusivity.
3979          */
3980         if (!folio_test_ksm(folio) &&
3981             (exclusive || folio_ref_count(folio) == 1)) {
3982                 if (vmf->flags & FAULT_FLAG_WRITE) {
3983                         pte = maybe_mkwrite(pte_mkdirty(pte), vma);
3984                         vmf->flags &= ~FAULT_FLAG_WRITE;
3985                         ret |= VM_FAULT_WRITE;
3986                 }
3987                 rmap_flags |= RMAP_EXCLUSIVE;
3988         }
3989         flush_icache_page(vma, page);
3990         if (pte_swp_soft_dirty(vmf->orig_pte))
3991                 pte = pte_mksoft_dirty(pte);
3992         if (pte_swp_uffd_wp(vmf->orig_pte)) {
3993                 pte = pte_mkuffd_wp(pte);
3994                 pte = pte_wrprotect(pte);
3995         }
3996         vmf->orig_pte = pte;
3997
3998         /* ksm created a completely new copy */
3999         if (unlikely(folio != swapcache && swapcache)) {
4000                 page_add_new_anon_rmap(page, vma, vmf->address);
4001                 folio_add_lru_vma(folio, vma);
4002         } else {
4003                 page_add_anon_rmap(page, vma, vmf->address, rmap_flags);
4004         }
4005
4006         VM_BUG_ON(!folio_test_anon(folio) ||
4007                         (pte_write(pte) && !PageAnonExclusive(page)));
4008         set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
4009         arch_do_swap_page(vma->vm_mm, vma, vmf->address, pte, vmf->orig_pte);
4010
4011         folio_unlock(folio);
4012         if (folio != swapcache && swapcache) {
4013                 /*
4014                  * Hold the lock to avoid the swap entry to be reused
4015                  * until we take the PT lock for the pte_same() check
4016                  * (to avoid false positives from pte_same). For
4017                  * further safety release the lock after the swap_free
4018                  * so that the swap count won't change under a
4019                  * parallel locked swapcache.
4020                  */
4021                 folio_unlock(swapcache);
4022                 folio_put(swapcache);
4023         }
4024
4025         if (vmf->flags & FAULT_FLAG_WRITE) {
4026                 ret |= do_wp_page(vmf);
4027                 if (ret & VM_FAULT_ERROR)
4028                         ret &= VM_FAULT_ERROR;
4029                 goto out;
4030         }
4031
4032         /* No need to invalidate - it was non-present before */
4033         update_mmu_cache(vma, vmf->address, vmf->pte);
4034 unlock:
4035         pte_unmap_unlock(vmf->pte, vmf->ptl);
4036 out:
4037         if (si)
4038                 put_swap_device(si);
4039         return ret;
4040 out_nomap:
4041         pte_unmap_unlock(vmf->pte, vmf->ptl);
4042 out_page:
4043         folio_unlock(folio);
4044 out_release:
4045         folio_put(folio);
4046         if (folio != swapcache && swapcache) {
4047                 folio_unlock(swapcache);
4048                 folio_put(swapcache);
4049         }
4050         if (si)
4051                 put_swap_device(si);
4052         return ret;
4053 }
4054
4055 /*
4056  * We enter with non-exclusive mmap_lock (to exclude vma changes,
4057  * but allow concurrent faults), and pte mapped but not yet locked.
4058  * We return with mmap_lock still held, but pte unmapped and unlocked.
4059  */
4060 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
4061 {
4062         struct vm_area_struct *vma = vmf->vma;
4063         struct page *page;
4064         vm_fault_t ret = 0;
4065         pte_t entry;
4066
4067         /* File mapping without ->vm_ops ? */
4068         if (vma->vm_flags & VM_SHARED)
4069                 return VM_FAULT_SIGBUS;
4070
4071         /*
4072          * Use pte_alloc() instead of pte_alloc_map().  We can't run
4073          * pte_offset_map() on pmds where a huge pmd might be created
4074          * from a different thread.
4075          *
4076          * pte_alloc_map() is safe to use under mmap_write_lock(mm) or when
4077          * parallel threads are excluded by other means.
4078          *
4079          * Here we only have mmap_read_lock(mm).
4080          */
4081         if (pte_alloc(vma->vm_mm, vmf->pmd))
4082                 return VM_FAULT_OOM;
4083
4084         /* See comment in handle_pte_fault() */
4085         if (unlikely(pmd_trans_unstable(vmf->pmd)))
4086                 return 0;
4087
4088         /* Use the zero-page for reads */
4089         if (!(vmf->flags & FAULT_FLAG_WRITE) &&
4090                         !mm_forbids_zeropage(vma->vm_mm)) {
4091                 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
4092                                                 vma->vm_page_prot));
4093                 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4094                                 vmf->address, &vmf->ptl);
4095                 if (!pte_none(*vmf->pte)) {
4096                         update_mmu_tlb(vma, vmf->address, vmf->pte);
4097                         goto unlock;
4098                 }
4099                 ret = check_stable_address_space(vma->vm_mm);
4100                 if (ret)
4101                         goto unlock;
4102                 /* Deliver the page fault to userland, check inside PT lock */
4103                 if (userfaultfd_missing(vma)) {
4104                         pte_unmap_unlock(vmf->pte, vmf->ptl);
4105                         return handle_userfault(vmf, VM_UFFD_MISSING);
4106                 }
4107                 goto setpte;
4108         }
4109
4110         /* Allocate our own private page. */
4111         if (unlikely(anon_vma_prepare(vma)))
4112                 goto oom;
4113         page = alloc_zeroed_user_highpage_movable(vma, vmf->address);
4114         if (!page)
4115                 goto oom;
4116
4117         if (mem_cgroup_charge(page_folio(page), vma->vm_mm, GFP_KERNEL))
4118                 goto oom_free_page;
4119         cgroup_throttle_swaprate(page, GFP_KERNEL);
4120
4121         /*
4122          * The memory barrier inside __SetPageUptodate makes sure that
4123          * preceding stores to the page contents become visible before
4124          * the set_pte_at() write.
4125          */
4126         __SetPageUptodate(page);
4127
4128         entry = mk_pte(page, vma->vm_page_prot);
4129         entry = pte_sw_mkyoung(entry);
4130         if (vma->vm_flags & VM_WRITE)
4131                 entry = pte_mkwrite(pte_mkdirty(entry));
4132
4133         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
4134                         &vmf->ptl);
4135         if (!pte_none(*vmf->pte)) {
4136                 update_mmu_tlb(vma, vmf->address, vmf->pte);
4137                 goto release;
4138         }
4139
4140         ret = check_stable_address_space(vma->vm_mm);
4141         if (ret)
4142                 goto release;
4143
4144         /* Deliver the page fault to userland, check inside PT lock */
4145         if (userfaultfd_missing(vma)) {
4146                 pte_unmap_unlock(vmf->pte, vmf->ptl);
4147                 put_page(page);
4148                 return handle_userfault(vmf, VM_UFFD_MISSING);
4149         }
4150
4151         inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
4152         page_add_new_anon_rmap(page, vma, vmf->address);
4153         lru_cache_add_inactive_or_unevictable(page, vma);
4154 setpte:
4155         set_pte_at(vma->vm_mm, vmf->address, vmf->pte, entry);
4156
4157         /* No need to invalidate - it was non-present before */
4158         update_mmu_cache(vma, vmf->address, vmf->pte);
4159 unlock:
4160         pte_unmap_unlock(vmf->pte, vmf->ptl);
4161         return ret;
4162 release:
4163         put_page(page);
4164         goto unlock;
4165 oom_free_page:
4166         put_page(page);
4167 oom:
4168         return VM_FAULT_OOM;
4169 }
4170
4171 /*
4172  * The mmap_lock must have been held on entry, and may have been
4173  * released depending on flags and vma->vm_ops->fault() return value.
4174  * See filemap_fault() and __lock_page_retry().
4175  */
4176 static vm_fault_t __do_fault(struct vm_fault *vmf)
4177 {
4178         struct vm_area_struct *vma = vmf->vma;
4179         vm_fault_t ret;
4180
4181         /*
4182          * Preallocate pte before we take page_lock because this might lead to
4183          * deadlocks for memcg reclaim which waits for pages under writeback:
4184          *                              lock_page(A)
4185          *                              SetPageWriteback(A)
4186          *                              unlock_page(A)
4187          * lock_page(B)
4188          *                              lock_page(B)
4189          * pte_alloc_one
4190          *   shrink_page_list
4191          *     wait_on_page_writeback(A)
4192          *                              SetPageWriteback(B)
4193          *                              unlock_page(B)
4194          *                              # flush A, B to clear the writeback
4195          */
4196         if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
4197                 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
4198                 if (!vmf->prealloc_pte)
4199                         return VM_FAULT_OOM;
4200         }
4201
4202         ret = vma->vm_ops->fault(vmf);
4203         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
4204                             VM_FAULT_DONE_COW)))
4205                 return ret;
4206
4207         if (unlikely(PageHWPoison(vmf->page))) {
4208                 struct page *page = vmf->page;
4209                 vm_fault_t poisonret = VM_FAULT_HWPOISON;
4210                 if (ret & VM_FAULT_LOCKED) {
4211                         if (page_mapped(page))
4212                                 unmap_mapping_pages(page_mapping(page),
4213                                                     page->index, 1, false);
4214                         /* Retry if a clean page was removed from the cache. */
4215                         if (invalidate_inode_page(page))
4216                                 poisonret = VM_FAULT_NOPAGE;
4217                         unlock_page(page);
4218                 }
4219                 put_page(page);
4220                 vmf->page = NULL;
4221                 return poisonret;
4222         }
4223
4224         if (unlikely(!(ret & VM_FAULT_LOCKED)))
4225                 lock_page(vmf->page);
4226         else
4227                 VM_BUG_ON_PAGE(!PageLocked(vmf->page), vmf->page);
4228
4229         return ret;
4230 }
4231
4232 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4233 static void deposit_prealloc_pte(struct vm_fault *vmf)
4234 {
4235         struct vm_area_struct *vma = vmf->vma;
4236
4237         pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
4238         /*
4239          * We are going to consume the prealloc table,
4240          * count that as nr_ptes.
4241          */
4242         mm_inc_nr_ptes(vma->vm_mm);
4243         vmf->prealloc_pte = NULL;
4244 }
4245
4246 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
4247 {
4248         struct vm_area_struct *vma = vmf->vma;
4249         bool write = vmf->flags & FAULT_FLAG_WRITE;
4250         unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
4251         pmd_t entry;
4252         int i;
4253         vm_fault_t ret = VM_FAULT_FALLBACK;
4254
4255         if (!transhuge_vma_suitable(vma, haddr))
4256                 return ret;
4257
4258         page = compound_head(page);
4259         if (compound_order(page) != HPAGE_PMD_ORDER)
4260                 return ret;
4261
4262         /*
4263          * Just backoff if any subpage of a THP is corrupted otherwise
4264          * the corrupted page may mapped by PMD silently to escape the
4265          * check.  This kind of THP just can be PTE mapped.  Access to
4266          * the corrupted subpage should trigger SIGBUS as expected.
4267          */
4268         if (unlikely(PageHasHWPoisoned(page)))
4269                 return ret;
4270
4271         /*
4272          * Archs like ppc64 need additional space to store information
4273          * related to pte entry. Use the preallocated table for that.
4274          */
4275         if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
4276                 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
4277                 if (!vmf->prealloc_pte)
4278                         return VM_FAULT_OOM;
4279         }
4280
4281         vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
4282         if (unlikely(!pmd_none(*vmf->pmd)))
4283                 goto out;
4284
4285         for (i = 0; i < HPAGE_PMD_NR; i++)
4286                 flush_icache_page(vma, page + i);
4287
4288         entry = mk_huge_pmd(page, vma->vm_page_prot);
4289         if (write)
4290                 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
4291
4292         add_mm_counter(vma->vm_mm, mm_counter_file(page), HPAGE_PMD_NR);
4293         page_add_file_rmap(page, vma, true);
4294
4295         /*
4296          * deposit and withdraw with pmd lock held
4297          */
4298         if (arch_needs_pgtable_deposit())
4299                 deposit_prealloc_pte(vmf);
4300
4301         set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
4302
4303         update_mmu_cache_pmd(vma, haddr, vmf->pmd);
4304
4305         /* fault is handled */
4306         ret = 0;
4307         count_vm_event(THP_FILE_MAPPED);
4308 out:
4309         spin_unlock(vmf->ptl);
4310         return ret;
4311 }
4312 #else
4313 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
4314 {
4315         return VM_FAULT_FALLBACK;
4316 }
4317 #endif
4318
4319 void do_set_pte(struct vm_fault *vmf, struct page *page, unsigned long addr)
4320 {
4321         struct vm_area_struct *vma = vmf->vma;
4322         bool uffd_wp = pte_marker_uffd_wp(vmf->orig_pte);
4323         bool write = vmf->flags & FAULT_FLAG_WRITE;
4324         bool prefault = vmf->address != addr;
4325         pte_t entry;
4326
4327         flush_icache_page(vma, page);
4328         entry = mk_pte(page, vma->vm_page_prot);
4329
4330         if (prefault && arch_wants_old_prefaulted_pte())
4331                 entry = pte_mkold(entry);
4332         else
4333                 entry = pte_sw_mkyoung(entry);
4334
4335         if (write)
4336                 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
4337         if (unlikely(uffd_wp))
4338                 entry = pte_mkuffd_wp(pte_wrprotect(entry));
4339         /* copy-on-write page */
4340         if (write && !(vma->vm_flags & VM_SHARED)) {
4341                 inc_mm_counter_fast(vma->vm_mm, MM_ANONPAGES);
4342                 page_add_new_anon_rmap(page, vma, addr);
4343                 lru_cache_add_inactive_or_unevictable(page, vma);
4344         } else {
4345                 inc_mm_counter_fast(vma->vm_mm, mm_counter_file(page));
4346                 page_add_file_rmap(page, vma, false);
4347         }
4348         set_pte_at(vma->vm_mm, addr, vmf->pte, entry);
4349 }
4350
4351 static bool vmf_pte_changed(struct vm_fault *vmf)
4352 {
4353         if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)
4354                 return !pte_same(*vmf->pte, vmf->orig_pte);
4355
4356         return !pte_none(*vmf->pte);
4357 }
4358
4359 /**
4360  * finish_fault - finish page fault once we have prepared the page to fault
4361  *
4362  * @vmf: structure describing the fault
4363  *
4364  * This function handles all that is needed to finish a page fault once the
4365  * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
4366  * given page, adds reverse page mapping, handles memcg charges and LRU
4367  * addition.
4368  *
4369  * The function expects the page to be locked and on success it consumes a
4370  * reference of a page being mapped (for the PTE which maps it).
4371  *
4372  * Return: %0 on success, %VM_FAULT_ code in case of error.
4373  */
4374 vm_fault_t finish_fault(struct vm_fault *vmf)
4375 {
4376         struct vm_area_struct *vma = vmf->vma;
4377         struct page *page;
4378         vm_fault_t ret;
4379
4380         /* Did we COW the page? */
4381         if ((vmf->flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED))
4382                 page = vmf->cow_page;
4383         else
4384                 page = vmf->page;
4385
4386         /*
4387          * check even for read faults because we might have lost our CoWed
4388          * page
4389          */
4390         if (!(vma->vm_flags & VM_SHARED)) {
4391                 ret = check_stable_address_space(vma->vm_mm);
4392                 if (ret)
4393                         return ret;
4394         }
4395
4396         if (pmd_none(*vmf->pmd)) {
4397                 if (PageTransCompound(page)) {
4398                         ret = do_set_pmd(vmf, page);
4399                         if (ret != VM_FAULT_FALLBACK)
4400                                 return ret;
4401                 }
4402
4403                 if (vmf->prealloc_pte)
4404                         pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte);
4405                 else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd)))
4406                         return VM_FAULT_OOM;
4407         }
4408
4409         /*
4410          * See comment in handle_pte_fault() for how this scenario happens, we
4411          * need to return NOPAGE so that we drop this page.
4412          */
4413         if (pmd_devmap_trans_unstable(vmf->pmd))
4414                 return VM_FAULT_NOPAGE;
4415
4416         vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4417                                       vmf->address, &vmf->ptl);
4418
4419         /* Re-check under ptl */
4420         if (likely(!vmf_pte_changed(vmf))) {
4421                 do_set_pte(vmf, page, vmf->address);
4422
4423                 /* no need to invalidate: a not-present page won't be cached */
4424                 update_mmu_cache(vma, vmf->address, vmf->pte);
4425
4426                 ret = 0;
4427         } else {
4428                 update_mmu_tlb(vma, vmf->address, vmf->pte);
4429                 ret = VM_FAULT_NOPAGE;
4430         }
4431
4432         pte_unmap_unlock(vmf->pte, vmf->ptl);
4433         return ret;
4434 }
4435
4436 static unsigned long fault_around_bytes __read_mostly =
4437         rounddown_pow_of_two(65536);
4438
4439 #ifdef CONFIG_DEBUG_FS
4440 static int fault_around_bytes_get(void *data, u64 *val)
4441 {
4442         *val = fault_around_bytes;
4443         return 0;
4444 }
4445
4446 /*
4447  * fault_around_bytes must be rounded down to the nearest page order as it's
4448  * what do_fault_around() expects to see.
4449  */
4450 static int fault_around_bytes_set(void *data, u64 val)
4451 {
4452         if (val / PAGE_SIZE > PTRS_PER_PTE)
4453                 return -EINVAL;
4454         if (val > PAGE_SIZE)
4455                 fault_around_bytes = rounddown_pow_of_two(val);
4456         else
4457                 fault_around_bytes = PAGE_SIZE; /* rounddown_pow_of_two(0) is undefined */
4458         return 0;
4459 }
4460 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
4461                 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
4462
4463 static int __init fault_around_debugfs(void)
4464 {
4465         debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
4466                                    &fault_around_bytes_fops);
4467         return 0;
4468 }
4469 late_initcall(fault_around_debugfs);
4470 #endif
4471
4472 /*
4473  * do_fault_around() tries to map few pages around the fault address. The hope
4474  * is that the pages will be needed soon and this will lower the number of
4475  * faults to handle.
4476  *
4477  * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
4478  * not ready to be mapped: not up-to-date, locked, etc.
4479  *
4480  * This function doesn't cross the VMA boundaries, in order to call map_pages()
4481  * only once.
4482  *
4483  * fault_around_bytes defines how many bytes we'll try to map.
4484  * do_fault_around() expects it to be set to a power of two less than or equal
4485  * to PTRS_PER_PTE.
4486  *
4487  * The virtual address of the area that we map is naturally aligned to
4488  * fault_around_bytes rounded down to the machine page size
4489  * (and therefore to page order).  This way it's easier to guarantee
4490  * that we don't cross page table boundaries.
4491  */
4492 static vm_fault_t do_fault_around(struct vm_fault *vmf)
4493 {
4494         unsigned long address = vmf->address, nr_pages, mask;
4495         pgoff_t start_pgoff = vmf->pgoff;
4496         pgoff_t end_pgoff;
4497         int off;
4498
4499         nr_pages = READ_ONCE(fault_around_bytes) >> PAGE_SHIFT;
4500         mask = ~(nr_pages * PAGE_SIZE - 1) & PAGE_MASK;
4501
4502         address = max(address & mask, vmf->vma->vm_start);
4503         off = ((vmf->address - address) >> PAGE_SHIFT) & (PTRS_PER_PTE - 1);
4504         start_pgoff -= off;
4505
4506         /*
4507          *  end_pgoff is either the end of the page table, the end of
4508          *  the vma or nr_pages from start_pgoff, depending what is nearest.
4509          */
4510         end_pgoff = start_pgoff -
4511                 ((address >> PAGE_SHIFT) & (PTRS_PER_PTE - 1)) +
4512                 PTRS_PER_PTE - 1;
4513         end_pgoff = min3(end_pgoff, vma_pages(vmf->vma) + vmf->vma->vm_pgoff - 1,
4514                         start_pgoff + nr_pages - 1);
4515
4516         if (pmd_none(*vmf->pmd)) {
4517                 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
4518                 if (!vmf->prealloc_pte)
4519                         return VM_FAULT_OOM;
4520         }
4521
4522         return vmf->vma->vm_ops->map_pages(vmf, start_pgoff, end_pgoff);
4523 }
4524
4525 /* Return true if we should do read fault-around, false otherwise */
4526 static inline bool should_fault_around(struct vm_fault *vmf)
4527 {
4528         /* No ->map_pages?  No way to fault around... */
4529         if (!vmf->vma->vm_ops->map_pages)
4530                 return false;
4531
4532         if (uffd_disable_fault_around(vmf->vma))
4533                 return false;
4534
4535         return fault_around_bytes >> PAGE_SHIFT > 1;
4536 }
4537
4538 static vm_fault_t do_read_fault(struct vm_fault *vmf)
4539 {
4540         vm_fault_t ret = 0;
4541
4542         /*
4543          * Let's call ->map_pages() first and use ->fault() as fallback
4544          * if page by the offset is not ready to be mapped (cold cache or
4545          * something).
4546          */
4547         if (should_fault_around(vmf)) {
4548                 ret = do_fault_around(vmf);
4549                 if (ret)
4550                         return ret;
4551         }
4552
4553         ret = __do_fault(vmf);
4554         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4555                 return ret;
4556
4557         ret |= finish_fault(vmf);
4558         unlock_page(vmf->page);
4559         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4560                 put_page(vmf->page);
4561         return ret;
4562 }
4563
4564 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
4565 {
4566         struct vm_area_struct *vma = vmf->vma;
4567         vm_fault_t ret;
4568
4569         if (unlikely(anon_vma_prepare(vma)))
4570                 return VM_FAULT_OOM;
4571
4572         vmf->cow_page = alloc_page_vma(GFP_HIGHUSER_MOVABLE, vma, vmf->address);
4573         if (!vmf->cow_page)
4574                 return VM_FAULT_OOM;
4575
4576         if (mem_cgroup_charge(page_folio(vmf->cow_page), vma->vm_mm,
4577                                 GFP_KERNEL)) {
4578                 put_page(vmf->cow_page);
4579                 return VM_FAULT_OOM;
4580         }
4581         cgroup_throttle_swaprate(vmf->cow_page, GFP_KERNEL);
4582
4583         ret = __do_fault(vmf);
4584         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4585                 goto uncharge_out;
4586         if (ret & VM_FAULT_DONE_COW)
4587                 return ret;
4588
4589         copy_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma);
4590         __SetPageUptodate(vmf->cow_page);
4591
4592         ret |= finish_fault(vmf);
4593         unlock_page(vmf->page);
4594         put_page(vmf->page);
4595         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4596                 goto uncharge_out;
4597         return ret;
4598 uncharge_out:
4599         put_page(vmf->cow_page);
4600         return ret;
4601 }
4602
4603 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
4604 {
4605         struct vm_area_struct *vma = vmf->vma;
4606         vm_fault_t ret, tmp;
4607
4608         ret = __do_fault(vmf);
4609         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
4610                 return ret;
4611
4612         /*
4613          * Check if the backing address space wants to know that the page is
4614          * about to become writable
4615          */
4616         if (vma->vm_ops->page_mkwrite) {
4617                 unlock_page(vmf->page);
4618                 tmp = do_page_mkwrite(vmf);
4619                 if (unlikely(!tmp ||
4620                                 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
4621                         put_page(vmf->page);
4622                         return tmp;
4623                 }
4624         }
4625
4626         ret |= finish_fault(vmf);
4627         if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
4628                                         VM_FAULT_RETRY))) {
4629                 unlock_page(vmf->page);
4630                 put_page(vmf->page);
4631                 return ret;
4632         }
4633
4634         ret |= fault_dirty_shared_page(vmf);
4635         return ret;
4636 }
4637
4638 /*
4639  * We enter with non-exclusive mmap_lock (to exclude vma changes,
4640  * but allow concurrent faults).
4641  * The mmap_lock may have been released depending on flags and our
4642  * return value.  See filemap_fault() and __folio_lock_or_retry().
4643  * If mmap_lock is released, vma may become invalid (for example
4644  * by other thread calling munmap()).
4645  */
4646 static vm_fault_t do_fault(struct vm_fault *vmf)
4647 {
4648         struct vm_area_struct *vma = vmf->vma;
4649         struct mm_struct *vm_mm = vma->vm_mm;
4650         vm_fault_t ret;
4651
4652         /*
4653          * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
4654          */
4655         if (!vma->vm_ops->fault) {
4656                 /*
4657                  * If we find a migration pmd entry or a none pmd entry, which
4658                  * should never happen, return SIGBUS
4659                  */
4660                 if (unlikely(!pmd_present(*vmf->pmd)))
4661                         ret = VM_FAULT_SIGBUS;
4662                 else {
4663                         vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm,
4664                                                        vmf->pmd,
4665                                                        vmf->address,
4666                                                        &vmf->ptl);
4667                         /*
4668                          * Make sure this is not a temporary clearing of pte
4669                          * by holding ptl and checking again. A R/M/W update
4670                          * of pte involves: take ptl, clearing the pte so that
4671                          * we don't have concurrent modification by hardware
4672                          * followed by an update.
4673                          */
4674                         if (unlikely(pte_none(*vmf->pte)))
4675                                 ret = VM_FAULT_SIGBUS;
4676                         else
4677                                 ret = VM_FAULT_NOPAGE;
4678
4679                         pte_unmap_unlock(vmf->pte, vmf->ptl);
4680                 }
4681         } else if (!(vmf->flags & FAULT_FLAG_WRITE))
4682                 ret = do_read_fault(vmf);
4683         else if (!(vma->vm_flags & VM_SHARED))
4684                 ret = do_cow_fault(vmf);
4685         else
4686                 ret = do_shared_fault(vmf);
4687
4688         /* preallocated pagetable is unused: free it */
4689         if (vmf->prealloc_pte) {
4690                 pte_free(vm_mm, vmf->prealloc_pte);
4691                 vmf->prealloc_pte = NULL;
4692         }
4693         return ret;
4694 }
4695
4696 int numa_migrate_prep(struct page *page, struct vm_area_struct *vma,
4697                       unsigned long addr, int page_nid, int *flags)
4698 {
4699         get_page(page);
4700
4701         count_vm_numa_event(NUMA_HINT_FAULTS);
4702         if (page_nid == numa_node_id()) {
4703                 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
4704                 *flags |= TNF_FAULT_LOCAL;
4705         }
4706
4707         return mpol_misplaced(page, vma, addr);
4708 }
4709
4710 static vm_fault_t do_numa_page(struct vm_fault *vmf)
4711 {
4712         struct vm_area_struct *vma = vmf->vma;
4713         struct page *page = NULL;
4714         int page_nid = NUMA_NO_NODE;
4715         int last_cpupid;
4716         int target_nid;
4717         pte_t pte, old_pte;
4718         bool was_writable = pte_savedwrite(vmf->orig_pte);
4719         int flags = 0;
4720
4721         /*
4722          * The "pte" at this point cannot be used safely without
4723          * validation through pte_unmap_same(). It's of NUMA type but
4724          * the pfn may be screwed if the read is non atomic.
4725          */
4726         vmf->ptl = pte_lockptr(vma->vm_mm, vmf->pmd);
4727         spin_lock(vmf->ptl);
4728         if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4729                 pte_unmap_unlock(vmf->pte, vmf->ptl);
4730                 goto out;
4731         }
4732
4733         /* Get the normal PTE  */
4734         old_pte = ptep_get(vmf->pte);
4735         pte = pte_modify(old_pte, vma->vm_page_prot);
4736
4737         page = vm_normal_page(vma, vmf->address, pte);
4738         if (!page || is_zone_device_page(page))
4739                 goto out_map;
4740
4741         /* TODO: handle PTE-mapped THP */
4742         if (PageCompound(page))
4743                 goto out_map;
4744
4745         /*
4746          * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
4747          * much anyway since they can be in shared cache state. This misses
4748          * the case where a mapping is writable but the process never writes
4749          * to it but pte_write gets cleared during protection updates and
4750          * pte_dirty has unpredictable behaviour between PTE scan updates,
4751          * background writeback, dirty balancing and application behaviour.
4752          */
4753         if (!was_writable)
4754                 flags |= TNF_NO_GROUP;
4755
4756         /*
4757          * Flag if the page is shared between multiple address spaces. This
4758          * is later used when determining whether to group tasks together
4759          */
4760         if (page_mapcount(page) > 1 && (vma->vm_flags & VM_SHARED))
4761                 flags |= TNF_SHARED;
4762
4763         page_nid = page_to_nid(page);
4764         /*
4765          * For memory tiering mode, cpupid of slow memory page is used
4766          * to record page access time.  So use default value.
4767          */
4768         if ((sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
4769             !node_is_toptier(page_nid))
4770                 last_cpupid = (-1 & LAST_CPUPID_MASK);
4771         else
4772                 last_cpupid = page_cpupid_last(page);
4773         target_nid = numa_migrate_prep(page, vma, vmf->address, page_nid,
4774                         &flags);
4775         if (target_nid == NUMA_NO_NODE) {
4776                 put_page(page);
4777                 goto out_map;
4778         }
4779         pte_unmap_unlock(vmf->pte, vmf->ptl);
4780
4781         /* Migrate to the requested node */
4782         if (migrate_misplaced_page(page, vma, target_nid)) {
4783                 page_nid = target_nid;
4784                 flags |= TNF_MIGRATED;
4785         } else {
4786                 flags |= TNF_MIGRATE_FAIL;
4787                 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4788                 spin_lock(vmf->ptl);
4789                 if (unlikely(!pte_same(*vmf->pte, vmf->orig_pte))) {
4790                         pte_unmap_unlock(vmf->pte, vmf->ptl);
4791                         goto out;
4792                 }
4793                 goto out_map;
4794         }
4795
4796 out:
4797         if (page_nid != NUMA_NO_NODE)
4798                 task_numa_fault(last_cpupid, page_nid, 1, flags);
4799         return 0;
4800 out_map:
4801         /*
4802          * Make it present again, depending on how arch implements
4803          * non-accessible ptes, some can allow access by kernel mode.
4804          */
4805         old_pte = ptep_modify_prot_start(vma, vmf->address, vmf->pte);
4806         pte = pte_modify(old_pte, vma->vm_page_prot);
4807         pte = pte_mkyoung(pte);
4808         if (was_writable)
4809                 pte = pte_mkwrite(pte);
4810         ptep_modify_prot_commit(vma, vmf->address, vmf->pte, old_pte, pte);
4811         update_mmu_cache(vma, vmf->address, vmf->pte);
4812         pte_unmap_unlock(vmf->pte, vmf->ptl);
4813         goto out;
4814 }
4815
4816 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
4817 {
4818         if (vma_is_anonymous(vmf->vma))
4819                 return do_huge_pmd_anonymous_page(vmf);
4820         if (vmf->vma->vm_ops->huge_fault)
4821                 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4822         return VM_FAULT_FALLBACK;
4823 }
4824
4825 /* `inline' is required to avoid gcc 4.1.2 build error */
4826 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf)
4827 {
4828         const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
4829
4830         if (vma_is_anonymous(vmf->vma)) {
4831                 if (likely(!unshare) &&
4832                     userfaultfd_huge_pmd_wp(vmf->vma, vmf->orig_pmd))
4833                         return handle_userfault(vmf, VM_UFFD_WP);
4834                 return do_huge_pmd_wp_page(vmf);
4835         }
4836         if (vmf->vma->vm_ops->huge_fault) {
4837                 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PMD);
4838
4839                 if (!(ret & VM_FAULT_FALLBACK))
4840                         return ret;
4841         }
4842
4843         /* COW or write-notify handled on pte level: split pmd. */
4844         __split_huge_pmd(vmf->vma, vmf->pmd, vmf->address, false, NULL);
4845
4846         return VM_FAULT_FALLBACK;
4847 }
4848
4849 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
4850 {
4851 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) &&                     \
4852         defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4853         /* No support for anonymous transparent PUD pages yet */
4854         if (vma_is_anonymous(vmf->vma))
4855                 return VM_FAULT_FALLBACK;
4856         if (vmf->vma->vm_ops->huge_fault)
4857                 return vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4858 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4859         return VM_FAULT_FALLBACK;
4860 }
4861
4862 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
4863 {
4864 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) &&                     \
4865         defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
4866         /* No support for anonymous transparent PUD pages yet */
4867         if (vma_is_anonymous(vmf->vma))
4868                 goto split;
4869         if (vmf->vma->vm_ops->huge_fault) {
4870                 vm_fault_t ret = vmf->vma->vm_ops->huge_fault(vmf, PE_SIZE_PUD);
4871
4872                 if (!(ret & VM_FAULT_FALLBACK))
4873                         return ret;
4874         }
4875 split:
4876         /* COW or write-notify not handled on PUD level: split pud.*/
4877         __split_huge_pud(vmf->vma, vmf->pud, vmf->address);
4878 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
4879         return VM_FAULT_FALLBACK;
4880 }
4881
4882 /*
4883  * These routines also need to handle stuff like marking pages dirty
4884  * and/or accessed for architectures that don't do it in hardware (most
4885  * RISC architectures).  The early dirtying is also good on the i386.
4886  *
4887  * There is also a hook called "update_mmu_cache()" that architectures
4888  * with external mmu caches can use to update those (ie the Sparc or
4889  * PowerPC hashed page tables that act as extended TLBs).
4890  *
4891  * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
4892  * concurrent faults).
4893  *
4894  * The mmap_lock may have been released depending on flags and our return value.
4895  * See filemap_fault() and __folio_lock_or_retry().
4896  */
4897 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
4898 {
4899         pte_t entry;
4900
4901         if (unlikely(pmd_none(*vmf->pmd))) {
4902                 /*
4903                  * Leave __pte_alloc() until later: because vm_ops->fault may
4904                  * want to allocate huge page, and if we expose page table
4905                  * for an instant, it will be difficult to retract from
4906                  * concurrent faults and from rmap lookups.
4907                  */
4908                 vmf->pte = NULL;
4909                 vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID;
4910         } else {
4911                 /*
4912                  * If a huge pmd materialized under us just retry later.  Use
4913                  * pmd_trans_unstable() via pmd_devmap_trans_unstable() instead
4914                  * of pmd_trans_huge() to ensure the pmd didn't become
4915                  * pmd_trans_huge under us and then back to pmd_none, as a
4916                  * result of MADV_DONTNEED running immediately after a huge pmd
4917                  * fault in a different thread of this mm, in turn leading to a
4918                  * misleading pmd_trans_huge() retval. All we have to ensure is
4919                  * that it is a regular pmd that we can walk with
4920                  * pte_offset_map() and we can do that through an atomic read
4921                  * in C, which is what pmd_trans_unstable() provides.
4922                  */
4923                 if (pmd_devmap_trans_unstable(vmf->pmd))
4924                         return 0;
4925                 /*
4926                  * A regular pmd is established and it can't morph into a huge
4927                  * pmd from under us anymore at this point because we hold the
4928                  * mmap_lock read mode and khugepaged takes it in write mode.
4929                  * So now it's safe to run pte_offset_map().
4930                  */
4931                 vmf->pte = pte_offset_map(vmf->pmd, vmf->address);
4932                 vmf->orig_pte = *vmf->pte;
4933                 vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID;
4934
4935                 /*
4936                  * some architectures can have larger ptes than wordsize,
4937                  * e.g.ppc44x-defconfig has CONFIG_PTE_64BIT=y and
4938                  * CONFIG_32BIT=y, so READ_ONCE cannot guarantee atomic
4939                  * accesses.  The code below just needs a consistent view
4940                  * for the ifs and we later double check anyway with the
4941                  * ptl lock held. So here a barrier will do.
4942                  */
4943                 barrier();
4944                 if (pte_none(vmf->orig_pte)) {
4945                         pte_unmap(vmf->pte);
4946                         vmf->pte = NULL;
4947                 }
4948         }
4949
4950         if (!vmf->pte) {
4951                 if (vma_is_anonymous(vmf->vma))
4952                         return do_anonymous_page(vmf);
4953                 else
4954                         return do_fault(vmf);
4955         }
4956
4957         if (!pte_present(vmf->orig_pte))
4958                 return do_swap_page(vmf);
4959
4960         if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
4961                 return do_numa_page(vmf);
4962
4963         vmf->ptl = pte_lockptr(vmf->vma->vm_mm, vmf->pmd);
4964         spin_lock(vmf->ptl);
4965         entry = vmf->orig_pte;
4966         if (unlikely(!pte_same(*vmf->pte, entry))) {
4967                 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
4968                 goto unlock;
4969         }
4970         if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
4971                 if (!pte_write(entry))
4972                         return do_wp_page(vmf);
4973                 else if (likely(vmf->flags & FAULT_FLAG_WRITE))
4974                         entry = pte_mkdirty(entry);
4975         }
4976         entry = pte_mkyoung(entry);
4977         if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
4978                                 vmf->flags & FAULT_FLAG_WRITE)) {
4979                 update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
4980         } else {
4981                 /* Skip spurious TLB flush for retried page fault */
4982                 if (vmf->flags & FAULT_FLAG_TRIED)
4983                         goto unlock;
4984                 /*
4985                  * This is needed only for protection faults but the arch code
4986                  * is not yet telling us if this is a protection fault or not.
4987                  * This still avoids useless tlb flushes for .text page faults
4988                  * with threads.
4989                  */
4990                 if (vmf->flags & FAULT_FLAG_WRITE)
4991                         flush_tlb_fix_spurious_fault(vmf->vma, vmf->address);
4992         }
4993 unlock:
4994         pte_unmap_unlock(vmf->pte, vmf->ptl);
4995         return 0;
4996 }
4997
4998 /*
4999  * By the time we get here, we already hold the mm semaphore
5000  *
5001  * The mmap_lock may have been released depending on flags and our
5002  * return value.  See filemap_fault() and __folio_lock_or_retry().
5003  */
5004 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
5005                 unsigned long address, unsigned int flags)
5006 {
5007         struct vm_fault vmf = {
5008                 .vma = vma,
5009                 .address = address & PAGE_MASK,
5010                 .real_address = address,
5011                 .flags = flags,
5012                 .pgoff = linear_page_index(vma, address),
5013                 .gfp_mask = __get_fault_gfp_mask(vma),
5014         };
5015         struct mm_struct *mm = vma->vm_mm;
5016         unsigned long vm_flags = vma->vm_flags;
5017         pgd_t *pgd;
5018         p4d_t *p4d;
5019         vm_fault_t ret;
5020
5021         pgd = pgd_offset(mm, address);
5022         p4d = p4d_alloc(mm, pgd, address);
5023         if (!p4d)
5024                 return VM_FAULT_OOM;
5025
5026         vmf.pud = pud_alloc(mm, p4d, address);
5027         if (!vmf.pud)
5028                 return VM_FAULT_OOM;
5029 retry_pud:
5030         if (pud_none(*vmf.pud) &&
5031             hugepage_vma_check(vma, vm_flags, false, true, true)) {
5032                 ret = create_huge_pud(&vmf);
5033                 if (!(ret & VM_FAULT_FALLBACK))
5034                         return ret;
5035         } else {
5036                 pud_t orig_pud = *vmf.pud;
5037
5038                 barrier();
5039                 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
5040
5041                         /*
5042                          * TODO once we support anonymous PUDs: NUMA case and
5043                          * FAULT_FLAG_UNSHARE handling.
5044                          */
5045                         if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) {
5046                                 ret = wp_huge_pud(&vmf, orig_pud);
5047                                 if (!(ret & VM_FAULT_FALLBACK))
5048                                         return ret;
5049                         } else {
5050                                 huge_pud_set_accessed(&vmf, orig_pud);
5051                                 return 0;
5052                         }
5053                 }
5054         }
5055
5056         vmf.pmd = pmd_alloc(mm, vmf.pud, address);
5057         if (!vmf.pmd)
5058                 return VM_FAULT_OOM;
5059
5060         /* Huge pud page fault raced with pmd_alloc? */
5061         if (pud_trans_unstable(vmf.pud))
5062                 goto retry_pud;
5063
5064         if (pmd_none(*vmf.pmd) &&
5065             hugepage_vma_check(vma, vm_flags, false, true, true)) {
5066                 ret = create_huge_pmd(&vmf);
5067                 if (!(ret & VM_FAULT_FALLBACK))
5068                         return ret;
5069         } else {
5070                 vmf.orig_pmd = *vmf.pmd;
5071
5072                 barrier();
5073                 if (unlikely(is_swap_pmd(vmf.orig_pmd))) {
5074                         VM_BUG_ON(thp_migration_supported() &&
5075                                           !is_pmd_migration_entry(vmf.orig_pmd));
5076                         if (is_pmd_migration_entry(vmf.orig_pmd))
5077                                 pmd_migration_entry_wait(mm, vmf.pmd);
5078                         return 0;
5079                 }
5080                 if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) {
5081                         if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma))
5082                                 return do_huge_pmd_numa_page(&vmf);
5083
5084                         if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
5085                             !pmd_write(vmf.orig_pmd)) {
5086                                 ret = wp_huge_pmd(&vmf);
5087                                 if (!(ret & VM_FAULT_FALLBACK))
5088                                         return ret;
5089                         } else {
5090                                 huge_pmd_set_accessed(&vmf);
5091                                 return 0;
5092                         }
5093                 }
5094         }
5095
5096         return handle_pte_fault(&vmf);
5097 }
5098
5099 /**
5100  * mm_account_fault - Do page fault accounting
5101  *
5102  * @regs: the pt_regs struct pointer.  When set to NULL, will skip accounting
5103  *        of perf event counters, but we'll still do the per-task accounting to
5104  *        the task who triggered this page fault.
5105  * @address: the faulted address.
5106  * @flags: the fault flags.
5107  * @ret: the fault retcode.
5108  *
5109  * This will take care of most of the page fault accounting.  Meanwhile, it
5110  * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
5111  * updates.  However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
5112  * still be in per-arch page fault handlers at the entry of page fault.
5113  */
5114 static inline void mm_account_fault(struct pt_regs *regs,
5115                                     unsigned long address, unsigned int flags,
5116                                     vm_fault_t ret)
5117 {
5118         bool major;
5119
5120         /*
5121          * We don't do accounting for some specific faults:
5122          *
5123          * - Unsuccessful faults (e.g. when the address wasn't valid).  That
5124          *   includes arch_vma_access_permitted() failing before reaching here.
5125          *   So this is not a "this many hardware page faults" counter.  We
5126          *   should use the hw profiling for that.
5127          *
5128          * - Incomplete faults (VM_FAULT_RETRY).  They will only be counted
5129          *   once they're completed.
5130          */
5131         if (ret & (VM_FAULT_ERROR | VM_FAULT_RETRY))
5132                 return;
5133
5134         /*
5135          * We define the fault as a major fault when the final successful fault
5136          * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
5137          * handle it immediately previously).
5138          */
5139         major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
5140
5141         if (major)
5142                 current->maj_flt++;
5143         else
5144                 current->min_flt++;
5145
5146         /*
5147          * If the fault is done for GUP, regs will be NULL.  We only do the
5148          * accounting for the per thread fault counters who triggered the
5149          * fault, and we skip the perf event updates.
5150          */
5151         if (!regs)
5152                 return;
5153
5154         if (major)
5155                 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
5156         else
5157                 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
5158 }
5159
5160 #ifdef CONFIG_LRU_GEN
5161 static void lru_gen_enter_fault(struct vm_area_struct *vma)
5162 {
5163         /* the LRU algorithm doesn't apply to sequential or random reads */
5164         current->in_lru_fault = !(vma->vm_flags & (VM_SEQ_READ | VM_RAND_READ));
5165 }
5166
5167 static void lru_gen_exit_fault(void)
5168 {
5169         current->in_lru_fault = false;
5170 }
5171 #else
5172 static void lru_gen_enter_fault(struct vm_area_struct *vma)
5173 {
5174 }
5175
5176 static void lru_gen_exit_fault(void)
5177 {
5178 }
5179 #endif /* CONFIG_LRU_GEN */
5180
5181 /*
5182  * By the time we get here, we already hold the mm semaphore
5183  *
5184  * The mmap_lock may have been released depending on flags and our
5185  * return value.  See filemap_fault() and __folio_lock_or_retry().
5186  */
5187 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
5188                            unsigned int flags, struct pt_regs *regs)
5189 {
5190         vm_fault_t ret;
5191
5192         __set_current_state(TASK_RUNNING);
5193
5194         count_vm_event(PGFAULT);
5195         count_memcg_event_mm(vma->vm_mm, PGFAULT);
5196
5197         /* do counter updates before entering really critical section. */
5198         check_sync_rss_stat(current);
5199
5200         if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
5201                                             flags & FAULT_FLAG_INSTRUCTION,
5202                                             flags & FAULT_FLAG_REMOTE))
5203                 return VM_FAULT_SIGSEGV;
5204
5205         /*
5206          * Enable the memcg OOM handling for faults triggered in user
5207          * space.  Kernel faults are handled more gracefully.
5208          */
5209         if (flags & FAULT_FLAG_USER)
5210                 mem_cgroup_enter_user_fault();
5211
5212         lru_gen_enter_fault(vma);
5213
5214         if (unlikely(is_vm_hugetlb_page(vma)))
5215                 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
5216         else
5217                 ret = __handle_mm_fault(vma, address, flags);
5218
5219         lru_gen_exit_fault();
5220
5221         if (flags & FAULT_FLAG_USER) {
5222                 mem_cgroup_exit_user_fault();
5223                 /*
5224                  * The task may have entered a memcg OOM situation but
5225                  * if the allocation error was handled gracefully (no
5226                  * VM_FAULT_OOM), there is no need to kill anything.
5227                  * Just clean up the OOM state peacefully.
5228                  */
5229                 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
5230                         mem_cgroup_oom_synchronize(false);
5231         }
5232
5233         mm_account_fault(regs, address, flags, ret);
5234
5235         return ret;
5236 }
5237 EXPORT_SYMBOL_GPL(handle_mm_fault);
5238
5239 #ifndef __PAGETABLE_P4D_FOLDED
5240 /*
5241  * Allocate p4d page table.
5242  * We've already handled the fast-path in-line.
5243  */
5244 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
5245 {
5246         p4d_t *new = p4d_alloc_one(mm, address);
5247         if (!new)
5248                 return -ENOMEM;
5249
5250         spin_lock(&mm->page_table_lock);
5251         if (pgd_present(*pgd)) {        /* Another has populated it */
5252                 p4d_free(mm, new);
5253         } else {
5254                 smp_wmb(); /* See comment in pmd_install() */
5255                 pgd_populate(mm, pgd, new);
5256         }
5257         spin_unlock(&mm->page_table_lock);
5258         return 0;
5259 }
5260 #endif /* __PAGETABLE_P4D_FOLDED */
5261
5262 #ifndef __PAGETABLE_PUD_FOLDED
5263 /*
5264  * Allocate page upper directory.
5265  * We've already handled the fast-path in-line.
5266  */
5267 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
5268 {
5269         pud_t *new = pud_alloc_one(mm, address);
5270         if (!new)
5271                 return -ENOMEM;
5272
5273         spin_lock(&mm->page_table_lock);
5274         if (!p4d_present(*p4d)) {
5275                 mm_inc_nr_puds(mm);
5276                 smp_wmb(); /* See comment in pmd_install() */
5277                 p4d_populate(mm, p4d, new);
5278         } else  /* Another has populated it */
5279                 pud_free(mm, new);
5280         spin_unlock(&mm->page_table_lock);
5281         return 0;
5282 }
5283 #endif /* __PAGETABLE_PUD_FOLDED */
5284
5285 #ifndef __PAGETABLE_PMD_FOLDED
5286 /*
5287  * Allocate page middle directory.
5288  * We've already handled the fast-path in-line.
5289  */
5290 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
5291 {
5292         spinlock_t *ptl;
5293         pmd_t *new = pmd_alloc_one(mm, address);
5294         if (!new)
5295                 return -ENOMEM;
5296
5297         ptl = pud_lock(mm, pud);
5298         if (!pud_present(*pud)) {
5299                 mm_inc_nr_pmds(mm);
5300                 smp_wmb(); /* See comment in pmd_install() */
5301                 pud_populate(mm, pud, new);
5302         } else {        /* Another has populated it */
5303                 pmd_free(mm, new);
5304         }
5305         spin_unlock(ptl);
5306         return 0;
5307 }
5308 #endif /* __PAGETABLE_PMD_FOLDED */
5309
5310 /**
5311  * follow_pte - look up PTE at a user virtual address
5312  * @mm: the mm_struct of the target address space
5313  * @address: user virtual address
5314  * @ptepp: location to store found PTE
5315  * @ptlp: location to store the lock for the PTE
5316  *
5317  * On a successful return, the pointer to the PTE is stored in @ptepp;
5318  * the corresponding lock is taken and its location is stored in @ptlp.
5319  * The contents of the PTE are only stable until @ptlp is released;
5320  * any further use, if any, must be protected against invalidation
5321  * with MMU notifiers.
5322  *
5323  * Only IO mappings and raw PFN mappings are allowed.  The mmap semaphore
5324  * should be taken for read.
5325  *
5326  * KVM uses this function.  While it is arguably less bad than ``follow_pfn``,
5327  * it is not a good general-purpose API.
5328  *
5329  * Return: zero on success, -ve otherwise.
5330  */
5331 int follow_pte(struct mm_struct *mm, unsigned long address,
5332                pte_t **ptepp, spinlock_t **ptlp)
5333 {
5334         pgd_t *pgd;
5335         p4d_t *p4d;
5336         pud_t *pud;
5337         pmd_t *pmd;
5338         pte_t *ptep;
5339
5340         pgd = pgd_offset(mm, address);
5341         if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
5342                 goto out;
5343
5344         p4d = p4d_offset(pgd, address);
5345         if (p4d_none(*p4d) || unlikely(p4d_bad(*p4d)))
5346                 goto out;
5347
5348         pud = pud_offset(p4d, address);
5349         if (pud_none(*pud) || unlikely(pud_bad(*pud)))
5350                 goto out;
5351
5352         pmd = pmd_offset(pud, address);
5353         VM_BUG_ON(pmd_trans_huge(*pmd));
5354
5355         if (pmd_none(*pmd) || unlikely(pmd_bad(*pmd)))
5356                 goto out;
5357
5358         ptep = pte_offset_map_lock(mm, pmd, address, ptlp);
5359         if (!pte_present(*ptep))
5360                 goto unlock;
5361         *ptepp = ptep;
5362         return 0;
5363 unlock:
5364         pte_unmap_unlock(ptep, *ptlp);
5365 out:
5366         return -EINVAL;
5367 }
5368 EXPORT_SYMBOL_GPL(follow_pte);
5369
5370 /**
5371  * follow_pfn - look up PFN at a user virtual address
5372  * @vma: memory mapping
5373  * @address: user virtual address
5374  * @pfn: location to store found PFN
5375  *
5376  * Only IO mappings and raw PFN mappings are allowed.
5377  *
5378  * This function does not allow the caller to read the permissions
5379  * of the PTE.  Do not use it.
5380  *
5381  * Return: zero and the pfn at @pfn on success, -ve otherwise.
5382  */
5383 int follow_pfn(struct vm_area_struct *vma, unsigned long address,
5384         unsigned long *pfn)
5385 {
5386         int ret = -EINVAL;
5387         spinlock_t *ptl;
5388         pte_t *ptep;
5389
5390         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5391                 return ret;
5392
5393         ret = follow_pte(vma->vm_mm, address, &ptep, &ptl);
5394         if (ret)
5395                 return ret;
5396         *pfn = pte_pfn(*ptep);
5397         pte_unmap_unlock(ptep, ptl);
5398         return 0;
5399 }
5400 EXPORT_SYMBOL(follow_pfn);
5401
5402 #ifdef CONFIG_HAVE_IOREMAP_PROT
5403 int follow_phys(struct vm_area_struct *vma,
5404                 unsigned long address, unsigned int flags,
5405                 unsigned long *prot, resource_size_t *phys)
5406 {
5407         int ret = -EINVAL;
5408         pte_t *ptep, pte;
5409         spinlock_t *ptl;
5410
5411         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5412                 goto out;
5413
5414         if (follow_pte(vma->vm_mm, address, &ptep, &ptl))
5415                 goto out;
5416         pte = *ptep;
5417
5418         if ((flags & FOLL_WRITE) && !pte_write(pte))
5419                 goto unlock;
5420
5421         *prot = pgprot_val(pte_pgprot(pte));
5422         *phys = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5423
5424         ret = 0;
5425 unlock:
5426         pte_unmap_unlock(ptep, ptl);
5427 out:
5428         return ret;
5429 }
5430
5431 /**
5432  * generic_access_phys - generic implementation for iomem mmap access
5433  * @vma: the vma to access
5434  * @addr: userspace address, not relative offset within @vma
5435  * @buf: buffer to read/write
5436  * @len: length of transfer
5437  * @write: set to FOLL_WRITE when writing, otherwise reading
5438  *
5439  * This is a generic implementation for &vm_operations_struct.access for an
5440  * iomem mapping. This callback is used by access_process_vm() when the @vma is
5441  * not page based.
5442  */
5443 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
5444                         void *buf, int len, int write)
5445 {
5446         resource_size_t phys_addr;
5447         unsigned long prot = 0;
5448         void __iomem *maddr;
5449         pte_t *ptep, pte;
5450         spinlock_t *ptl;
5451         int offset = offset_in_page(addr);
5452         int ret = -EINVAL;
5453
5454         if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
5455                 return -EINVAL;
5456
5457 retry:
5458         if (follow_pte(vma->vm_mm, addr, &ptep, &ptl))
5459                 return -EINVAL;
5460         pte = *ptep;
5461         pte_unmap_unlock(ptep, ptl);
5462
5463         prot = pgprot_val(pte_pgprot(pte));
5464         phys_addr = (resource_size_t)pte_pfn(pte) << PAGE_SHIFT;
5465
5466         if ((write & FOLL_WRITE) && !pte_write(pte))
5467                 return -EINVAL;
5468
5469         maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
5470         if (!maddr)
5471                 return -ENOMEM;
5472
5473         if (follow_pte(vma->vm_mm, addr, &ptep, &ptl))
5474                 goto out_unmap;
5475
5476         if (!pte_same(pte, *ptep)) {
5477                 pte_unmap_unlock(ptep, ptl);
5478                 iounmap(maddr);
5479
5480                 goto retry;
5481         }
5482
5483         if (write)
5484                 memcpy_toio(maddr + offset, buf, len);
5485         else
5486                 memcpy_fromio(buf, maddr + offset, len);
5487         ret = len;
5488         pte_unmap_unlock(ptep, ptl);
5489 out_unmap:
5490         iounmap(maddr);
5491
5492         return ret;
5493 }
5494 EXPORT_SYMBOL_GPL(generic_access_phys);
5495 #endif
5496
5497 /*
5498  * Access another process' address space as given in mm.
5499  */
5500 int __access_remote_vm(struct mm_struct *mm, unsigned long addr, void *buf,
5501                        int len, unsigned int gup_flags)
5502 {
5503         struct vm_area_struct *vma;
5504         void *old_buf = buf;
5505         int write = gup_flags & FOLL_WRITE;
5506
5507         if (mmap_read_lock_killable(mm))
5508                 return 0;
5509
5510         /* ignore errors, just check how much was successfully transferred */
5511         while (len) {
5512                 int bytes, ret, offset;
5513                 void *maddr;
5514                 struct page *page = NULL;
5515
5516                 ret = get_user_pages_remote(mm, addr, 1,
5517                                 gup_flags, &page, &vma, NULL);
5518                 if (ret <= 0) {
5519 #ifndef CONFIG_HAVE_IOREMAP_PROT
5520                         break;
5521 #else
5522                         /*
5523                          * Check if this is a VM_IO | VM_PFNMAP VMA, which
5524                          * we can access using slightly different code.
5525                          */
5526                         vma = vma_lookup(mm, addr);
5527                         if (!vma)
5528                                 break;
5529                         if (vma->vm_ops && vma->vm_ops->access)
5530                                 ret = vma->vm_ops->access(vma, addr, buf,
5531                                                           len, write);
5532                         if (ret <= 0)
5533                                 break;
5534                         bytes = ret;
5535 #endif
5536                 } else {
5537                         bytes = len;
5538                         offset = addr & (PAGE_SIZE-1);
5539                         if (bytes > PAGE_SIZE-offset)
5540                                 bytes = PAGE_SIZE-offset;
5541
5542                         maddr = kmap(page);
5543                         if (write) {
5544                                 copy_to_user_page(vma, page, addr,
5545                                                   maddr + offset, buf, bytes);
5546                                 set_page_dirty_lock(page);
5547                         } else {
5548                                 copy_from_user_page(vma, page, addr,
5549                                                     buf, maddr + offset, bytes);
5550                         }
5551                         kunmap(page);
5552                         put_page(page);
5553                 }
5554                 len -= bytes;
5555                 buf += bytes;
5556                 addr += bytes;
5557         }
5558         mmap_read_unlock(mm);
5559
5560         return buf - old_buf;
5561 }
5562
5563 /**
5564  * access_remote_vm - access another process' address space
5565  * @mm:         the mm_struct of the target address space
5566  * @addr:       start address to access
5567  * @buf:        source or destination buffer
5568  * @len:        number of bytes to transfer
5569  * @gup_flags:  flags modifying lookup behaviour
5570  *
5571  * The caller must hold a reference on @mm.
5572  *
5573  * Return: number of bytes copied from source to destination.
5574  */
5575 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
5576                 void *buf, int len, unsigned int gup_flags)
5577 {
5578         return __access_remote_vm(mm, addr, buf, len, gup_flags);
5579 }
5580
5581 /*
5582  * Access another process' address space.
5583  * Source/target buffer must be kernel space,
5584  * Do not walk the page table directly, use get_user_pages
5585  */
5586 int access_process_vm(struct task_struct *tsk, unsigned long addr,
5587                 void *buf, int len, unsigned int gup_flags)
5588 {
5589         struct mm_struct *mm;
5590         int ret;
5591
5592         mm = get_task_mm(tsk);
5593         if (!mm)
5594                 return 0;
5595
5596         ret = __access_remote_vm(mm, addr, buf, len, gup_flags);
5597
5598         mmput(mm);
5599
5600         return ret;
5601 }
5602 EXPORT_SYMBOL_GPL(access_process_vm);
5603
5604 /*
5605  * Print the name of a VMA.
5606  */
5607 void print_vma_addr(char *prefix, unsigned long ip)
5608 {
5609         struct mm_struct *mm = current->mm;
5610         struct vm_area_struct *vma;
5611
5612         /*
5613          * we might be running from an atomic context so we cannot sleep
5614          */
5615         if (!mmap_read_trylock(mm))
5616                 return;
5617
5618         vma = find_vma(mm, ip);
5619         if (vma && vma->vm_file) {
5620                 struct file *f = vma->vm_file;
5621                 char *buf = (char *)__get_free_page(GFP_NOWAIT);
5622                 if (buf) {
5623                         char *p;
5624
5625                         p = file_path(f, buf, PAGE_SIZE);
5626                         if (IS_ERR(p))
5627                                 p = "?";
5628                         printk("%s%s[%lx+%lx]", prefix, kbasename(p),
5629                                         vma->vm_start,
5630                                         vma->vm_end - vma->vm_start);
5631                         free_page((unsigned long)buf);
5632                 }
5633         }
5634         mmap_read_unlock(mm);
5635 }
5636
5637 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5638 void __might_fault(const char *file, int line)
5639 {
5640         if (pagefault_disabled())
5641                 return;
5642         __might_sleep(file, line);
5643 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP)
5644         if (current->mm)
5645                 might_lock_read(&current->mm->mmap_lock);
5646 #endif
5647 }
5648 EXPORT_SYMBOL(__might_fault);
5649 #endif
5650
5651 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
5652 /*
5653  * Process all subpages of the specified huge page with the specified
5654  * operation.  The target subpage will be processed last to keep its
5655  * cache lines hot.
5656  */
5657 static inline void process_huge_page(
5658         unsigned long addr_hint, unsigned int pages_per_huge_page,
5659         void (*process_subpage)(unsigned long addr, int idx, void *arg),
5660         void *arg)
5661 {
5662         int i, n, base, l;
5663         unsigned long addr = addr_hint &
5664                 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5665
5666         /* Process target subpage last to keep its cache lines hot */
5667         might_sleep();
5668         n = (addr_hint - addr) / PAGE_SIZE;
5669         if (2 * n <= pages_per_huge_page) {
5670                 /* If target subpage in first half of huge page */
5671                 base = 0;
5672                 l = n;
5673                 /* Process subpages at the end of huge page */
5674                 for (i = pages_per_huge_page - 1; i >= 2 * n; i--) {
5675                         cond_resched();
5676                         process_subpage(addr + i * PAGE_SIZE, i, arg);
5677                 }
5678         } else {
5679                 /* If target subpage in second half of huge page */
5680                 base = pages_per_huge_page - 2 * (pages_per_huge_page - n);
5681                 l = pages_per_huge_page - n;
5682                 /* Process subpages at the begin of huge page */
5683                 for (i = 0; i < base; i++) {
5684                         cond_resched();
5685                         process_subpage(addr + i * PAGE_SIZE, i, arg);
5686                 }
5687         }
5688         /*
5689          * Process remaining subpages in left-right-left-right pattern
5690          * towards the target subpage
5691          */
5692         for (i = 0; i < l; i++) {
5693                 int left_idx = base + i;
5694                 int right_idx = base + 2 * l - 1 - i;
5695
5696                 cond_resched();
5697                 process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
5698                 cond_resched();
5699                 process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
5700         }
5701 }
5702
5703 static void clear_gigantic_page(struct page *page,
5704                                 unsigned long addr,
5705                                 unsigned int pages_per_huge_page)
5706 {
5707         int i;
5708         struct page *p;
5709
5710         might_sleep();
5711         for (i = 0; i < pages_per_huge_page; i++) {
5712                 p = nth_page(page, i);
5713                 cond_resched();
5714                 clear_user_highpage(p, addr + i * PAGE_SIZE);
5715         }
5716 }
5717
5718 static void clear_subpage(unsigned long addr, int idx, void *arg)
5719 {
5720         struct page *page = arg;
5721
5722         clear_user_highpage(page + idx, addr);
5723 }
5724
5725 void clear_huge_page(struct page *page,
5726                      unsigned long addr_hint, unsigned int pages_per_huge_page)
5727 {
5728         unsigned long addr = addr_hint &
5729                 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5730
5731         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5732                 clear_gigantic_page(page, addr, pages_per_huge_page);
5733                 return;
5734         }
5735
5736         process_huge_page(addr_hint, pages_per_huge_page, clear_subpage, page);
5737 }
5738
5739 static void copy_user_gigantic_page(struct page *dst, struct page *src,
5740                                     unsigned long addr,
5741                                     struct vm_area_struct *vma,
5742                                     unsigned int pages_per_huge_page)
5743 {
5744         int i;
5745         struct page *dst_base = dst;
5746         struct page *src_base = src;
5747
5748         for (i = 0; i < pages_per_huge_page; i++) {
5749                 dst = nth_page(dst_base, i);
5750                 src = nth_page(src_base, i);
5751
5752                 cond_resched();
5753                 copy_user_highpage(dst, src, addr + i*PAGE_SIZE, vma);
5754         }
5755 }
5756
5757 struct copy_subpage_arg {
5758         struct page *dst;
5759         struct page *src;
5760         struct vm_area_struct *vma;
5761 };
5762
5763 static void copy_subpage(unsigned long addr, int idx, void *arg)
5764 {
5765         struct copy_subpage_arg *copy_arg = arg;
5766
5767         copy_user_highpage(copy_arg->dst + idx, copy_arg->src + idx,
5768                            addr, copy_arg->vma);
5769 }
5770
5771 void copy_user_huge_page(struct page *dst, struct page *src,
5772                          unsigned long addr_hint, struct vm_area_struct *vma,
5773                          unsigned int pages_per_huge_page)
5774 {
5775         unsigned long addr = addr_hint &
5776                 ~(((unsigned long)pages_per_huge_page << PAGE_SHIFT) - 1);
5777         struct copy_subpage_arg arg = {
5778                 .dst = dst,
5779                 .src = src,
5780                 .vma = vma,
5781         };
5782
5783         if (unlikely(pages_per_huge_page > MAX_ORDER_NR_PAGES)) {
5784                 copy_user_gigantic_page(dst, src, addr, vma,
5785                                         pages_per_huge_page);
5786                 return;
5787         }
5788
5789         process_huge_page(addr_hint, pages_per_huge_page, copy_subpage, &arg);
5790 }
5791
5792 long copy_huge_page_from_user(struct page *dst_page,
5793                                 const void __user *usr_src,
5794                                 unsigned int pages_per_huge_page,
5795                                 bool allow_pagefault)
5796 {
5797         void *page_kaddr;
5798         unsigned long i, rc = 0;
5799         unsigned long ret_val = pages_per_huge_page * PAGE_SIZE;
5800         struct page *subpage;
5801
5802         for (i = 0; i < pages_per_huge_page; i++) {
5803                 subpage = nth_page(dst_page, i);
5804                 if (allow_pagefault)
5805                         page_kaddr = kmap(subpage);
5806                 else
5807                         page_kaddr = kmap_atomic(subpage);
5808                 rc = copy_from_user(page_kaddr,
5809                                 usr_src + i * PAGE_SIZE, PAGE_SIZE);
5810                 if (allow_pagefault)
5811                         kunmap(subpage);
5812                 else
5813                         kunmap_atomic(page_kaddr);
5814
5815                 ret_val -= (PAGE_SIZE - rc);
5816                 if (rc)
5817                         break;
5818
5819                 flush_dcache_page(subpage);
5820
5821                 cond_resched();
5822         }
5823         return ret_val;
5824 }
5825 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
5826
5827 #if USE_SPLIT_PTE_PTLOCKS && ALLOC_SPLIT_PTLOCKS
5828
5829 static struct kmem_cache *page_ptl_cachep;
5830
5831 void __init ptlock_cache_init(void)
5832 {
5833         page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
5834                         SLAB_PANIC, NULL);
5835 }
5836
5837 bool ptlock_alloc(struct page *page)
5838 {
5839         spinlock_t *ptl;
5840
5841         ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
5842         if (!ptl)
5843                 return false;
5844         page->ptl = ptl;
5845         return true;
5846 }
5847
5848 void ptlock_free(struct page *page)
5849 {
5850         kmem_cache_free(page_ptl_cachep, page->ptl);
5851 }
5852 #endif