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/numa_balancing.h>
47 #include <linux/sched/task.h>
48 #include <linux/hugetlb.h>
49 #include <linux/mman.h>
50 #include <linux/swap.h>
51 #include <linux/highmem.h>
52 #include <linux/pagemap.h>
53 #include <linux/memremap.h>
54 #include <linux/kmsan.h>
55 #include <linux/ksm.h>
56 #include <linux/rmap.h>
57 #include <linux/export.h>
58 #include <linux/delayacct.h>
59 #include <linux/init.h>
60 #include <linux/pfn_t.h>
61 #include <linux/writeback.h>
62 #include <linux/memcontrol.h>
63 #include <linux/mmu_notifier.h>
64 #include <linux/swapops.h>
65 #include <linux/elf.h>
66 #include <linux/gfp.h>
67 #include <linux/migrate.h>
68 #include <linux/string.h>
69 #include <linux/memory-tiers.h>
70 #include <linux/debugfs.h>
71 #include <linux/userfaultfd_k.h>
72 #include <linux/dax.h>
73 #include <linux/oom.h>
74 #include <linux/numa.h>
75 #include <linux/perf_event.h>
76 #include <linux/ptrace.h>
77 #include <linux/vmalloc.h>
78 #include <linux/sched/sysctl.h>
79
80 #include <trace/events/kmem.h>
81
82 #include <asm/io.h>
83 #include <asm/mmu_context.h>
84 #include <asm/pgalloc.h>
85 #include <linux/uaccess.h>
86 #include <asm/tlb.h>
87 #include <asm/tlbflush.h>
88
89 #include "pgalloc-track.h"
90 #include "internal.h"
91 #include "swap.h"
92
93 #if defined(LAST_CPUPID_NOT_IN_PAGE_FLAGS) && !defined(CONFIG_COMPILE_TEST)
94 #warning Unfortunate NUMA and NUMA Balancing config, growing page-frame for last_cpupid.
95 #endif
96
97 static vm_fault_t do_fault(struct vm_fault *vmf);
98 static vm_fault_t do_anonymous_page(struct vm_fault *vmf);
99 static bool vmf_pte_changed(struct vm_fault *vmf);
100
101 /*
102 * Return true if the original pte was a uffd-wp pte marker (so the pte was
103 * wr-protected).
104 */
vmf_orig_pte_uffd_wp(struct vm_fault * vmf)105 static __always_inline bool vmf_orig_pte_uffd_wp(struct vm_fault *vmf)
106 {
107 if (!userfaultfd_wp(vmf->vma))
108 return false;
109 if (!(vmf->flags & FAULT_FLAG_ORIG_PTE_VALID))
110 return false;
111
112 return pte_marker_uffd_wp(vmf->orig_pte);
113 }
114
115 /*
116 * Randomize the address space (stacks, mmaps, brk, etc.).
117 *
118 * ( When CONFIG_COMPAT_BRK=y we exclude brk from randomization,
119 * as ancient (libc5 based) binaries can segfault. )
120 */
121 int randomize_va_space __read_mostly =
122 #ifdef CONFIG_COMPAT_BRK
123 1;
124 #else
125 2;
126 #endif
127
128 #ifndef arch_wants_old_prefaulted_pte
arch_wants_old_prefaulted_pte(void)129 static inline bool arch_wants_old_prefaulted_pte(void)
130 {
131 /*
132 * Transitioning a PTE from 'old' to 'young' can be expensive on
133 * some architectures, even if it's performed in hardware. By
134 * default, "false" means prefaulted entries will be 'young'.
135 */
136 return false;
137 }
138 #endif
139
disable_randmaps(char * s)140 static int __init disable_randmaps(char *s)
141 {
142 randomize_va_space = 0;
143 return 1;
144 }
145 __setup("norandmaps", disable_randmaps);
146
147 unsigned long zero_pfn __read_mostly;
148 EXPORT_SYMBOL(zero_pfn);
149
150 unsigned long highest_memmap_pfn __read_mostly;
151
152 /*
153 * CONFIG_MMU architectures set up ZERO_PAGE in their paging_init()
154 */
init_zero_pfn(void)155 static int __init init_zero_pfn(void)
156 {
157 zero_pfn = page_to_pfn(ZERO_PAGE(0));
158 return 0;
159 }
160 early_initcall(init_zero_pfn);
161
mm_trace_rss_stat(struct mm_struct * mm,int member)162 void mm_trace_rss_stat(struct mm_struct *mm, int member)
163 {
164 trace_rss_stat(mm, member);
165 }
166
167 /*
168 * Note: this doesn't free the actual pages themselves. That
169 * has been handled earlier when unmapping all the memory regions.
170 */
free_pte_range(struct mmu_gather * tlb,pmd_t * pmd,unsigned long addr)171 static void free_pte_range(struct mmu_gather *tlb, pmd_t *pmd,
172 unsigned long addr)
173 {
174 pgtable_t token = pmd_pgtable(*pmd);
175 pmd_clear(pmd);
176 pte_free_tlb(tlb, token, addr);
177 mm_dec_nr_ptes(tlb->mm);
178 }
179
free_pmd_range(struct mmu_gather * tlb,pud_t * pud,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)180 static inline void free_pmd_range(struct mmu_gather *tlb, pud_t *pud,
181 unsigned long addr, unsigned long end,
182 unsigned long floor, unsigned long ceiling)
183 {
184 pmd_t *pmd;
185 unsigned long next;
186 unsigned long start;
187
188 start = addr;
189 pmd = pmd_offset(pud, addr);
190 do {
191 next = pmd_addr_end(addr, end);
192 if (pmd_none_or_clear_bad(pmd))
193 continue;
194 free_pte_range(tlb, pmd, addr);
195 } while (pmd++, addr = next, addr != end);
196
197 start &= PUD_MASK;
198 if (start < floor)
199 return;
200 if (ceiling) {
201 ceiling &= PUD_MASK;
202 if (!ceiling)
203 return;
204 }
205 if (end - 1 > ceiling - 1)
206 return;
207
208 pmd = pmd_offset(pud, start);
209 pud_clear(pud);
210 pmd_free_tlb(tlb, pmd, start);
211 mm_dec_nr_pmds(tlb->mm);
212 }
213
free_pud_range(struct mmu_gather * tlb,p4d_t * p4d,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)214 static inline void free_pud_range(struct mmu_gather *tlb, p4d_t *p4d,
215 unsigned long addr, unsigned long end,
216 unsigned long floor, unsigned long ceiling)
217 {
218 pud_t *pud;
219 unsigned long next;
220 unsigned long start;
221
222 start = addr;
223 pud = pud_offset(p4d, addr);
224 do {
225 next = pud_addr_end(addr, end);
226 if (pud_none_or_clear_bad(pud))
227 continue;
228 free_pmd_range(tlb, pud, addr, next, floor, ceiling);
229 } while (pud++, addr = next, addr != end);
230
231 start &= P4D_MASK;
232 if (start < floor)
233 return;
234 if (ceiling) {
235 ceiling &= P4D_MASK;
236 if (!ceiling)
237 return;
238 }
239 if (end - 1 > ceiling - 1)
240 return;
241
242 pud = pud_offset(p4d, start);
243 p4d_clear(p4d);
244 pud_free_tlb(tlb, pud, start);
245 mm_dec_nr_puds(tlb->mm);
246 }
247
free_p4d_range(struct mmu_gather * tlb,pgd_t * pgd,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)248 static inline void free_p4d_range(struct mmu_gather *tlb, pgd_t *pgd,
249 unsigned long addr, unsigned long end,
250 unsigned long floor, unsigned long ceiling)
251 {
252 p4d_t *p4d;
253 unsigned long next;
254 unsigned long start;
255
256 start = addr;
257 p4d = p4d_offset(pgd, addr);
258 do {
259 next = p4d_addr_end(addr, end);
260 if (p4d_none_or_clear_bad(p4d))
261 continue;
262 free_pud_range(tlb, p4d, addr, next, floor, ceiling);
263 } while (p4d++, addr = next, addr != end);
264
265 start &= PGDIR_MASK;
266 if (start < floor)
267 return;
268 if (ceiling) {
269 ceiling &= PGDIR_MASK;
270 if (!ceiling)
271 return;
272 }
273 if (end - 1 > ceiling - 1)
274 return;
275
276 p4d = p4d_offset(pgd, start);
277 pgd_clear(pgd);
278 p4d_free_tlb(tlb, p4d, start);
279 }
280
281 /*
282 * This function frees user-level page tables of a process.
283 */
free_pgd_range(struct mmu_gather * tlb,unsigned long addr,unsigned long end,unsigned long floor,unsigned long ceiling)284 void free_pgd_range(struct mmu_gather *tlb,
285 unsigned long addr, unsigned long end,
286 unsigned long floor, unsigned long ceiling)
287 {
288 pgd_t *pgd;
289 unsigned long next;
290
291 /*
292 * The next few lines have given us lots of grief...
293 *
294 * Why are we testing PMD* at this top level? Because often
295 * there will be no work to do at all, and we'd prefer not to
296 * go all the way down to the bottom just to discover that.
297 *
298 * Why all these "- 1"s? Because 0 represents both the bottom
299 * of the address space and the top of it (using -1 for the
300 * top wouldn't help much: the masks would do the wrong thing).
301 * The rule is that addr 0 and floor 0 refer to the bottom of
302 * the address space, but end 0 and ceiling 0 refer to the top
303 * Comparisons need to use "end - 1" and "ceiling - 1" (though
304 * that end 0 case should be mythical).
305 *
306 * Wherever addr is brought up or ceiling brought down, we must
307 * be careful to reject "the opposite 0" before it confuses the
308 * subsequent tests. But what about where end is brought down
309 * by PMD_SIZE below? no, end can't go down to 0 there.
310 *
311 * Whereas we round start (addr) and ceiling down, by different
312 * masks at different levels, in order to test whether a table
313 * now has no other vmas using it, so can be freed, we don't
314 * bother to round floor or end up - the tests don't need that.
315 */
316
317 addr &= PMD_MASK;
318 if (addr < floor) {
319 addr += PMD_SIZE;
320 if (!addr)
321 return;
322 }
323 if (ceiling) {
324 ceiling &= PMD_MASK;
325 if (!ceiling)
326 return;
327 }
328 if (end - 1 > ceiling - 1)
329 end -= PMD_SIZE;
330 if (addr > end - 1)
331 return;
332 /*
333 * We add page table cache pages with PAGE_SIZE,
334 * (see pte_free_tlb()), flush the tlb if we need
335 */
336 tlb_change_page_size(tlb, PAGE_SIZE);
337 pgd = pgd_offset(tlb->mm, addr);
338 do {
339 next = pgd_addr_end(addr, end);
340 if (pgd_none_or_clear_bad(pgd))
341 continue;
342 free_p4d_range(tlb, pgd, addr, next, floor, ceiling);
343 } while (pgd++, addr = next, addr != end);
344 }
345
free_pgtables(struct mmu_gather * tlb,struct ma_state * mas,struct vm_area_struct * vma,unsigned long floor,unsigned long ceiling,bool mm_wr_locked)346 void free_pgtables(struct mmu_gather *tlb, struct ma_state *mas,
347 struct vm_area_struct *vma, unsigned long floor,
348 unsigned long ceiling, bool mm_wr_locked)
349 {
350 struct unlink_vma_file_batch vb;
351
352 do {
353 unsigned long addr = vma->vm_start;
354 struct vm_area_struct *next;
355
356 /*
357 * Note: USER_PGTABLES_CEILING may be passed as ceiling and may
358 * be 0. This will underflow and is okay.
359 */
360 next = mas_find(mas, ceiling - 1);
361 if (unlikely(xa_is_zero(next)))
362 next = NULL;
363
364 /*
365 * Hide vma from rmap and truncate_pagecache before freeing
366 * pgtables
367 */
368 if (mm_wr_locked)
369 vma_start_write(vma);
370 unlink_anon_vmas(vma);
371
372 if (is_vm_hugetlb_page(vma)) {
373 unlink_file_vma(vma);
374 hugetlb_free_pgd_range(tlb, addr, vma->vm_end,
375 floor, next ? next->vm_start : ceiling);
376 } else {
377 unlink_file_vma_batch_init(&vb);
378 unlink_file_vma_batch_add(&vb, vma);
379
380 /*
381 * Optimization: gather nearby vmas into one call down
382 */
383 while (next && next->vm_start <= vma->vm_end + PMD_SIZE
384 && !is_vm_hugetlb_page(next)) {
385 vma = next;
386 next = mas_find(mas, ceiling - 1);
387 if (unlikely(xa_is_zero(next)))
388 next = NULL;
389 if (mm_wr_locked)
390 vma_start_write(vma);
391 unlink_anon_vmas(vma);
392 unlink_file_vma_batch_add(&vb, vma);
393 }
394 unlink_file_vma_batch_final(&vb);
395 free_pgd_range(tlb, addr, vma->vm_end,
396 floor, next ? next->vm_start : ceiling);
397 }
398 vma = next;
399 } while (vma);
400 }
401
pmd_install(struct mm_struct * mm,pmd_t * pmd,pgtable_t * pte)402 void pmd_install(struct mm_struct *mm, pmd_t *pmd, pgtable_t *pte)
403 {
404 spinlock_t *ptl = pmd_lock(mm, pmd);
405
406 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
407 mm_inc_nr_ptes(mm);
408 /*
409 * Ensure all pte setup (eg. pte page lock and page clearing) are
410 * visible before the pte is made visible to other CPUs by being
411 * put into page tables.
412 *
413 * The other side of the story is the pointer chasing in the page
414 * table walking code (when walking the page table without locking;
415 * ie. most of the time). Fortunately, these data accesses consist
416 * of a chain of data-dependent loads, meaning most CPUs (alpha
417 * being the notable exception) will already guarantee loads are
418 * seen in-order. See the alpha page table accessors for the
419 * smp_rmb() barriers in page table walking code.
420 */
421 smp_wmb(); /* Could be smp_wmb__xxx(before|after)_spin_lock */
422 pmd_populate(mm, pmd, *pte);
423 *pte = NULL;
424 }
425 spin_unlock(ptl);
426 }
427
__pte_alloc(struct mm_struct * mm,pmd_t * pmd)428 int __pte_alloc(struct mm_struct *mm, pmd_t *pmd)
429 {
430 pgtable_t new = pte_alloc_one(mm);
431 if (!new)
432 return -ENOMEM;
433
434 pmd_install(mm, pmd, &new);
435 if (new)
436 pte_free(mm, new);
437 return 0;
438 }
439
__pte_alloc_kernel(pmd_t * pmd)440 int __pte_alloc_kernel(pmd_t *pmd)
441 {
442 pte_t *new = pte_alloc_one_kernel(&init_mm);
443 if (!new)
444 return -ENOMEM;
445
446 spin_lock(&init_mm.page_table_lock);
447 if (likely(pmd_none(*pmd))) { /* Has another populated it ? */
448 smp_wmb(); /* See comment in pmd_install() */
449 pmd_populate_kernel(&init_mm, pmd, new);
450 new = NULL;
451 }
452 spin_unlock(&init_mm.page_table_lock);
453 if (new)
454 pte_free_kernel(&init_mm, new);
455 return 0;
456 }
457
init_rss_vec(int * rss)458 static inline void init_rss_vec(int *rss)
459 {
460 memset(rss, 0, sizeof(int) * NR_MM_COUNTERS);
461 }
462
add_mm_rss_vec(struct mm_struct * mm,int * rss)463 static inline void add_mm_rss_vec(struct mm_struct *mm, int *rss)
464 {
465 int i;
466
467 for (i = 0; i < NR_MM_COUNTERS; i++)
468 if (rss[i])
469 add_mm_counter(mm, i, rss[i]);
470 }
471
472 /*
473 * This function is called to print an error when a bad pte
474 * is found. For example, we might have a PFN-mapped pte in
475 * a region that doesn't allow it.
476 *
477 * The calling function must still handle the error.
478 */
print_bad_pte(struct vm_area_struct * vma,unsigned long addr,pte_t pte,struct page * page)479 static void print_bad_pte(struct vm_area_struct *vma, unsigned long addr,
480 pte_t pte, struct page *page)
481 {
482 pgd_t *pgd = pgd_offset(vma->vm_mm, addr);
483 p4d_t *p4d = p4d_offset(pgd, addr);
484 pud_t *pud = pud_offset(p4d, addr);
485 pmd_t *pmd = pmd_offset(pud, addr);
486 struct address_space *mapping;
487 pgoff_t index;
488 static unsigned long resume;
489 static unsigned long nr_shown;
490 static unsigned long nr_unshown;
491
492 /*
493 * Allow a burst of 60 reports, then keep quiet for that minute;
494 * or allow a steady drip of one report per second.
495 */
496 if (nr_shown == 60) {
497 if (time_before(jiffies, resume)) {
498 nr_unshown++;
499 return;
500 }
501 if (nr_unshown) {
502 pr_alert("BUG: Bad page map: %lu messages suppressed\n",
503 nr_unshown);
504 nr_unshown = 0;
505 }
506 nr_shown = 0;
507 }
508 if (nr_shown++ == 0)
509 resume = jiffies + 60 * HZ;
510
511 mapping = vma->vm_file ? vma->vm_file->f_mapping : NULL;
512 index = linear_page_index(vma, addr);
513
514 pr_alert("BUG: Bad page map in process %s pte:%08llx pmd:%08llx\n",
515 current->comm,
516 (long long)pte_val(pte), (long long)pmd_val(*pmd));
517 if (page)
518 dump_page(page, "bad pte");
519 pr_alert("addr:%px vm_flags:%08lx anon_vma:%px mapping:%px index:%lx\n",
520 (void *)addr, vma->vm_flags, vma->anon_vma, mapping, index);
521 pr_alert("file:%pD fault:%ps mmap:%ps read_folio:%ps\n",
522 vma->vm_file,
523 vma->vm_ops ? vma->vm_ops->fault : NULL,
524 vma->vm_file ? vma->vm_file->f_op->mmap : NULL,
525 mapping ? mapping->a_ops->read_folio : NULL);
526 dump_stack();
527 add_taint(TAINT_BAD_PAGE, LOCKDEP_NOW_UNRELIABLE);
528 }
529
530 /*
531 * vm_normal_page -- This function gets the "struct page" associated with a pte.
532 *
533 * "Special" mappings do not wish to be associated with a "struct page" (either
534 * it doesn't exist, or it exists but they don't want to touch it). In this
535 * case, NULL is returned here. "Normal" mappings do have a struct page.
536 *
537 * There are 2 broad cases. Firstly, an architecture may define a pte_special()
538 * pte bit, in which case this function is trivial. Secondly, an architecture
539 * may not have a spare pte bit, which requires a more complicated scheme,
540 * described below.
541 *
542 * A raw VM_PFNMAP mapping (ie. one that is not COWed) is always considered a
543 * special mapping (even if there are underlying and valid "struct pages").
544 * COWed pages of a VM_PFNMAP are always normal.
545 *
546 * The way we recognize COWed pages within VM_PFNMAP mappings is through the
547 * rules set up by "remap_pfn_range()": the vma will have the VM_PFNMAP bit
548 * set, and the vm_pgoff will point to the first PFN mapped: thus every special
549 * mapping will always honor the rule
550 *
551 * pfn_of_page == vma->vm_pgoff + ((addr - vma->vm_start) >> PAGE_SHIFT)
552 *
553 * And for normal mappings this is false.
554 *
555 * This restricts such mappings to be a linear translation from virtual address
556 * to pfn. To get around this restriction, we allow arbitrary mappings so long
557 * as the vma is not a COW mapping; in that case, we know that all ptes are
558 * special (because none can have been COWed).
559 *
560 *
561 * In order to support COW of arbitrary special mappings, we have VM_MIXEDMAP.
562 *
563 * VM_MIXEDMAP mappings can likewise contain memory with or without "struct
564 * page" backing, however the difference is that _all_ pages with a struct
565 * page (that is, those where pfn_valid is true) are refcounted and considered
566 * normal pages by the VM. The only exception are zeropages, which are
567 * *never* refcounted.
568 *
569 * The disadvantage is that pages are refcounted (which can be slower and
570 * simply not an option for some PFNMAP users). The advantage is that we
571 * don't have to follow the strict linearity rule of PFNMAP mappings in
572 * order to support COWable mappings.
573 *
574 */
vm_normal_page(struct vm_area_struct * vma,unsigned long addr,pte_t pte)575 struct page *vm_normal_page(struct vm_area_struct *vma, unsigned long addr,
576 pte_t pte)
577 {
578 unsigned long pfn = pte_pfn(pte);
579
580 if (IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL)) {
581 if (likely(!pte_special(pte)))
582 goto check_pfn;
583 if (vma->vm_ops && vma->vm_ops->find_special_page)
584 return vma->vm_ops->find_special_page(vma, addr);
585 if (vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
586 return NULL;
587 if (is_zero_pfn(pfn))
588 return NULL;
589 if (pte_devmap(pte))
590 /*
591 * NOTE: New users of ZONE_DEVICE will not set pte_devmap()
592 * and will have refcounts incremented on their struct pages
593 * when they are inserted into PTEs, thus they are safe to
594 * return here. Legacy ZONE_DEVICE pages that set pte_devmap()
595 * do not have refcounts. Example of legacy ZONE_DEVICE is
596 * MEMORY_DEVICE_FS_DAX type in pmem or virtio_fs drivers.
597 */
598 return NULL;
599
600 print_bad_pte(vma, addr, pte, NULL);
601 return NULL;
602 }
603
604 /* !CONFIG_ARCH_HAS_PTE_SPECIAL case follows: */
605
606 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
607 if (vma->vm_flags & VM_MIXEDMAP) {
608 if (!pfn_valid(pfn))
609 return NULL;
610 if (is_zero_pfn(pfn))
611 return NULL;
612 goto out;
613 } else {
614 unsigned long off;
615 off = (addr - vma->vm_start) >> PAGE_SHIFT;
616 if (pfn == vma->vm_pgoff + off)
617 return NULL;
618 if (!is_cow_mapping(vma->vm_flags))
619 return NULL;
620 }
621 }
622
623 if (is_zero_pfn(pfn))
624 return NULL;
625
626 check_pfn:
627 if (unlikely(pfn > highest_memmap_pfn)) {
628 print_bad_pte(vma, addr, pte, NULL);
629 return NULL;
630 }
631
632 /*
633 * NOTE! We still have PageReserved() pages in the page tables.
634 * eg. VDSO mappings can cause them to exist.
635 */
636 out:
637 VM_WARN_ON_ONCE(is_zero_pfn(pfn));
638 return pfn_to_page(pfn);
639 }
640
vm_normal_folio(struct vm_area_struct * vma,unsigned long addr,pte_t pte)641 struct folio *vm_normal_folio(struct vm_area_struct *vma, unsigned long addr,
642 pte_t pte)
643 {
644 struct page *page = vm_normal_page(vma, addr, pte);
645
646 if (page)
647 return page_folio(page);
648 return NULL;
649 }
650
651 #ifdef CONFIG_PGTABLE_HAS_HUGE_LEAVES
vm_normal_page_pmd(struct vm_area_struct * vma,unsigned long addr,pmd_t pmd)652 struct page *vm_normal_page_pmd(struct vm_area_struct *vma, unsigned long addr,
653 pmd_t pmd)
654 {
655 unsigned long pfn = pmd_pfn(pmd);
656
657 /* Currently it's only used for huge pfnmaps */
658 if (unlikely(pmd_special(pmd)))
659 return NULL;
660
661 if (unlikely(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP))) {
662 if (vma->vm_flags & VM_MIXEDMAP) {
663 if (!pfn_valid(pfn))
664 return NULL;
665 goto out;
666 } else {
667 unsigned long off;
668 off = (addr - vma->vm_start) >> PAGE_SHIFT;
669 if (pfn == vma->vm_pgoff + off)
670 return NULL;
671 if (!is_cow_mapping(vma->vm_flags))
672 return NULL;
673 }
674 }
675
676 if (pmd_devmap(pmd))
677 return NULL;
678 if (is_huge_zero_pmd(pmd))
679 return NULL;
680 if (unlikely(pfn > highest_memmap_pfn))
681 return NULL;
682
683 /*
684 * NOTE! We still have PageReserved() pages in the page tables.
685 * eg. VDSO mappings can cause them to exist.
686 */
687 out:
688 return pfn_to_page(pfn);
689 }
690
vm_normal_folio_pmd(struct vm_area_struct * vma,unsigned long addr,pmd_t pmd)691 struct folio *vm_normal_folio_pmd(struct vm_area_struct *vma,
692 unsigned long addr, pmd_t pmd)
693 {
694 struct page *page = vm_normal_page_pmd(vma, addr, pmd);
695
696 if (page)
697 return page_folio(page);
698 return NULL;
699 }
700 #endif
701
702 /**
703 * restore_exclusive_pte - Restore a device-exclusive entry
704 * @vma: VMA covering @address
705 * @folio: the mapped folio
706 * @page: the mapped folio page
707 * @address: the virtual address
708 * @ptep: pte pointer into the locked page table mapping the folio page
709 * @orig_pte: pte value at @ptep
710 *
711 * Restore a device-exclusive non-swap entry to an ordinary present pte.
712 *
713 * The folio and the page table must be locked, and MMU notifiers must have
714 * been called to invalidate any (exclusive) device mappings.
715 *
716 * Locking the folio makes sure that anybody who just converted the pte to
717 * a device-exclusive entry can map it into the device to make forward
718 * progress without others converting it back until the folio was unlocked.
719 *
720 * If the folio lock ever becomes an issue, we can stop relying on the folio
721 * lock; it might make some scenarios with heavy thrashing less likely to
722 * make forward progress, but these scenarios might not be valid use cases.
723 *
724 * Note that the folio lock does not protect against all cases of concurrent
725 * page table modifications (e.g., MADV_DONTNEED, mprotect), so device drivers
726 * must use MMU notifiers to sync against any concurrent changes.
727 */
restore_exclusive_pte(struct vm_area_struct * vma,struct folio * folio,struct page * page,unsigned long address,pte_t * ptep,pte_t orig_pte)728 static void restore_exclusive_pte(struct vm_area_struct *vma,
729 struct folio *folio, struct page *page, unsigned long address,
730 pte_t *ptep, pte_t orig_pte)
731 {
732 pte_t pte;
733
734 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
735
736 pte = pte_mkold(mk_pte(page, READ_ONCE(vma->vm_page_prot)));
737 if (pte_swp_soft_dirty(orig_pte))
738 pte = pte_mksoft_dirty(pte);
739
740 if (pte_swp_uffd_wp(orig_pte))
741 pte = pte_mkuffd_wp(pte);
742
743 if ((vma->vm_flags & VM_WRITE) &&
744 can_change_pte_writable(vma, address, pte)) {
745 if (folio_test_dirty(folio))
746 pte = pte_mkdirty(pte);
747 pte = pte_mkwrite(pte, vma);
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 */
try_restore_exclusive_pte(struct vm_area_struct * vma,unsigned long addr,pte_t * ptep,pte_t orig_pte)762 static int try_restore_exclusive_pte(struct vm_area_struct *vma,
763 unsigned long addr, pte_t *ptep, pte_t orig_pte)
764 {
765 struct page *page = pfn_swap_entry_to_page(pte_to_swp_entry(orig_pte));
766 struct folio *folio = page_folio(page);
767
768 if (folio_trylock(folio)) {
769 restore_exclusive_pte(vma, folio, page, addr, ptep, orig_pte);
770 folio_unlock(folio);
771 return 0;
772 }
773
774 return -EBUSY;
775 }
776
777 /*
778 * copy one vm_area from one task to the other. Assumes the page tables
779 * already present in the new task to be cleared in the whole range
780 * covered by this vma.
781 */
782
783 static unsigned long
copy_nonpresent_pte(struct mm_struct * dst_mm,struct mm_struct * src_mm,pte_t * dst_pte,pte_t * src_pte,struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,unsigned long addr,int * rss)784 copy_nonpresent_pte(struct mm_struct *dst_mm, struct mm_struct *src_mm,
785 pte_t *dst_pte, pte_t *src_pte, struct vm_area_struct *dst_vma,
786 struct vm_area_struct *src_vma, unsigned long addr, int *rss)
787 {
788 unsigned long vm_flags = dst_vma->vm_flags;
789 pte_t orig_pte = ptep_get(src_pte);
790 pte_t pte = orig_pte;
791 struct folio *folio;
792 struct page *page;
793 swp_entry_t entry = pte_to_swp_entry(orig_pte);
794
795 if (likely(!non_swap_entry(entry))) {
796 if (swap_duplicate(entry) < 0)
797 return -EIO;
798
799 /* make sure dst_mm is on swapoff's mmlist. */
800 if (unlikely(list_empty(&dst_mm->mmlist))) {
801 spin_lock(&mmlist_lock);
802 if (list_empty(&dst_mm->mmlist))
803 list_add(&dst_mm->mmlist,
804 &src_mm->mmlist);
805 spin_unlock(&mmlist_lock);
806 }
807 /* Mark the swap entry as shared. */
808 if (pte_swp_exclusive(orig_pte)) {
809 pte = pte_swp_clear_exclusive(orig_pte);
810 set_pte_at(src_mm, addr, src_pte, pte);
811 }
812 rss[MM_SWAPENTS]++;
813 } else if (is_migration_entry(entry)) {
814 folio = pfn_swap_entry_folio(entry);
815
816 rss[mm_counter(folio)]++;
817
818 if (!is_readable_migration_entry(entry) &&
819 is_cow_mapping(vm_flags)) {
820 /*
821 * COW mappings require pages in both parent and child
822 * to be set to read. A previously exclusive entry is
823 * now shared.
824 */
825 entry = make_readable_migration_entry(
826 swp_offset(entry));
827 pte = swp_entry_to_pte(entry);
828 if (pte_swp_soft_dirty(orig_pte))
829 pte = pte_swp_mksoft_dirty(pte);
830 if (pte_swp_uffd_wp(orig_pte))
831 pte = pte_swp_mkuffd_wp(pte);
832 set_pte_at(src_mm, addr, src_pte, pte);
833 }
834 } else if (is_device_private_entry(entry)) {
835 page = pfn_swap_entry_to_page(entry);
836 folio = page_folio(page);
837
838 /*
839 * Update rss count even for unaddressable pages, as
840 * they should treated just like normal pages in this
841 * respect.
842 *
843 * We will likely want to have some new rss counters
844 * for unaddressable pages, at some point. But for now
845 * keep things as they are.
846 */
847 folio_get(folio);
848 rss[mm_counter(folio)]++;
849 /* Cannot fail as these pages cannot get pinned. */
850 folio_try_dup_anon_rmap_pte(folio, page, dst_vma, src_vma);
851
852 /*
853 * We do not preserve soft-dirty information, because so
854 * far, checkpoint/restore is the only feature that
855 * requires that. And checkpoint/restore does not work
856 * when a device driver is involved (you cannot easily
857 * save and restore device driver state).
858 */
859 if (is_writable_device_private_entry(entry) &&
860 is_cow_mapping(vm_flags)) {
861 entry = make_readable_device_private_entry(
862 swp_offset(entry));
863 pte = swp_entry_to_pte(entry);
864 if (pte_swp_uffd_wp(orig_pte))
865 pte = pte_swp_mkuffd_wp(pte);
866 set_pte_at(src_mm, addr, src_pte, pte);
867 }
868 } else if (is_device_exclusive_entry(entry)) {
869 /*
870 * Make device exclusive entries present by restoring the
871 * original entry then copying as for a present pte. Device
872 * exclusive entries currently only support private writable
873 * (ie. COW) mappings.
874 */
875 VM_BUG_ON(!is_cow_mapping(src_vma->vm_flags));
876 if (try_restore_exclusive_pte(src_vma, addr, src_pte, orig_pte))
877 return -EBUSY;
878 return -ENOENT;
879 } else if (is_pte_marker_entry(entry)) {
880 pte_marker marker = copy_pte_marker(entry, dst_vma);
881
882 if (marker)
883 set_pte_at(dst_mm, addr, dst_pte,
884 make_pte_marker(marker));
885 return 0;
886 }
887 if (!userfaultfd_wp(dst_vma))
888 pte = pte_swp_clear_uffd_wp(pte);
889 set_pte_at(dst_mm, addr, dst_pte, pte);
890 return 0;
891 }
892
893 /*
894 * Copy a present and normal page.
895 *
896 * NOTE! The usual case is that this isn't required;
897 * instead, the caller can just increase the page refcount
898 * and re-use the pte the traditional way.
899 *
900 * And if we need a pre-allocated page but don't yet have
901 * one, return a negative error to let the preallocation
902 * code know so that it can do so outside the page table
903 * lock.
904 */
905 static inline int
copy_present_page(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,pte_t * dst_pte,pte_t * src_pte,unsigned long addr,int * rss,struct folio ** prealloc,struct page * page)906 copy_present_page(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
907 pte_t *dst_pte, pte_t *src_pte, unsigned long addr, int *rss,
908 struct folio **prealloc, struct page *page)
909 {
910 struct folio *new_folio;
911 pte_t pte;
912
913 new_folio = *prealloc;
914 if (!new_folio)
915 return -EAGAIN;
916
917 /*
918 * We have a prealloc page, all good! Take it
919 * over and copy the page & arm it.
920 */
921
922 if (copy_mc_user_highpage(&new_folio->page, page, addr, src_vma))
923 return -EHWPOISON;
924
925 *prealloc = NULL;
926 __folio_mark_uptodate(new_folio);
927 folio_add_new_anon_rmap(new_folio, dst_vma, addr, RMAP_EXCLUSIVE);
928 folio_add_lru_vma(new_folio, dst_vma);
929 rss[MM_ANONPAGES]++;
930
931 /* All done, just insert the new page copy in the child */
932 pte = mk_pte(&new_folio->page, dst_vma->vm_page_prot);
933 pte = maybe_mkwrite(pte_mkdirty(pte), dst_vma);
934 if (userfaultfd_pte_wp(dst_vma, ptep_get(src_pte)))
935 /* Uffd-wp needs to be delivered to dest pte as well */
936 pte = pte_mkuffd_wp(pte);
937 set_pte_at(dst_vma->vm_mm, addr, dst_pte, pte);
938 return 0;
939 }
940
__copy_present_ptes(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,pte_t * dst_pte,pte_t * src_pte,pte_t pte,unsigned long addr,int nr)941 static __always_inline void __copy_present_ptes(struct vm_area_struct *dst_vma,
942 struct vm_area_struct *src_vma, pte_t *dst_pte, pte_t *src_pte,
943 pte_t pte, unsigned long addr, int nr)
944 {
945 struct mm_struct *src_mm = src_vma->vm_mm;
946
947 /* If it's a COW mapping, write protect it both processes. */
948 if (is_cow_mapping(src_vma->vm_flags) && pte_write(pte)) {
949 wrprotect_ptes(src_mm, addr, src_pte, nr);
950 pte = pte_wrprotect(pte);
951 }
952
953 /* If it's a shared mapping, mark it clean in the child. */
954 if (src_vma->vm_flags & VM_SHARED)
955 pte = pte_mkclean(pte);
956 pte = pte_mkold(pte);
957
958 if (!userfaultfd_wp(dst_vma))
959 pte = pte_clear_uffd_wp(pte);
960
961 set_ptes(dst_vma->vm_mm, addr, dst_pte, pte, nr);
962 }
963
964 /*
965 * Copy one present PTE, trying to batch-process subsequent PTEs that map
966 * consecutive pages of the same folio by copying them as well.
967 *
968 * Returns -EAGAIN if one preallocated page is required to copy the next PTE.
969 * Otherwise, returns the number of copied PTEs (at least 1).
970 */
971 static inline int
copy_present_ptes(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,pte_t * dst_pte,pte_t * src_pte,pte_t pte,unsigned long addr,int max_nr,int * rss,struct folio ** prealloc)972 copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
973 pte_t *dst_pte, pte_t *src_pte, pte_t pte, unsigned long addr,
974 int max_nr, int *rss, struct folio **prealloc)
975 {
976 struct page *page;
977 struct folio *folio;
978 bool any_writable;
979 fpb_t flags = 0;
980 int err, nr;
981
982 page = vm_normal_page(src_vma, addr, pte);
983 if (unlikely(!page))
984 goto copy_pte;
985
986 folio = page_folio(page);
987
988 /*
989 * If we likely have to copy, just don't bother with batching. Make
990 * sure that the common "small folio" case is as fast as possible
991 * by keeping the batching logic separate.
992 */
993 if (unlikely(!*prealloc && folio_test_large(folio) && max_nr != 1)) {
994 if (src_vma->vm_flags & VM_SHARED)
995 flags |= FPB_IGNORE_DIRTY;
996 if (!vma_soft_dirty_enabled(src_vma))
997 flags |= FPB_IGNORE_SOFT_DIRTY;
998
999 nr = folio_pte_batch(folio, addr, src_pte, pte, max_nr, flags,
1000 &any_writable, NULL, NULL);
1001 folio_ref_add(folio, nr);
1002 if (folio_test_anon(folio)) {
1003 if (unlikely(folio_try_dup_anon_rmap_ptes(folio, page,
1004 nr, dst_vma, src_vma))) {
1005 folio_ref_sub(folio, nr);
1006 return -EAGAIN;
1007 }
1008 rss[MM_ANONPAGES] += nr;
1009 VM_WARN_ON_FOLIO(PageAnonExclusive(page), folio);
1010 } else {
1011 folio_dup_file_rmap_ptes(folio, page, nr, dst_vma);
1012 rss[mm_counter_file(folio)] += nr;
1013 }
1014 if (any_writable)
1015 pte = pte_mkwrite(pte, src_vma);
1016 __copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, pte,
1017 addr, nr);
1018 return nr;
1019 }
1020
1021 folio_get(folio);
1022 if (folio_test_anon(folio)) {
1023 /*
1024 * If this page may have been pinned by the parent process,
1025 * copy the page immediately for the child so that we'll always
1026 * guarantee the pinned page won't be randomly replaced in the
1027 * future.
1028 */
1029 if (unlikely(folio_try_dup_anon_rmap_pte(folio, page, dst_vma, src_vma))) {
1030 /* Page may be pinned, we have to copy. */
1031 folio_put(folio);
1032 err = copy_present_page(dst_vma, src_vma, dst_pte, src_pte,
1033 addr, rss, prealloc, page);
1034 return err ? err : 1;
1035 }
1036 rss[MM_ANONPAGES]++;
1037 VM_WARN_ON_FOLIO(PageAnonExclusive(page), folio);
1038 } else {
1039 folio_dup_file_rmap_pte(folio, page, dst_vma);
1040 rss[mm_counter_file(folio)]++;
1041 }
1042
1043 copy_pte:
1044 __copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte, pte, addr, 1);
1045 return 1;
1046 }
1047
folio_prealloc(struct mm_struct * src_mm,struct vm_area_struct * vma,unsigned long addr,bool need_zero)1048 static inline struct folio *folio_prealloc(struct mm_struct *src_mm,
1049 struct vm_area_struct *vma, unsigned long addr, bool need_zero)
1050 {
1051 struct folio *new_folio;
1052
1053 if (need_zero)
1054 new_folio = vma_alloc_zeroed_movable_folio(vma, addr);
1055 else
1056 new_folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, addr);
1057
1058 if (!new_folio)
1059 return NULL;
1060
1061 if (mem_cgroup_charge(new_folio, src_mm, GFP_KERNEL)) {
1062 folio_put(new_folio);
1063 return NULL;
1064 }
1065 folio_throttle_swaprate(new_folio, GFP_KERNEL);
1066
1067 return new_folio;
1068 }
1069
1070 static int
copy_pte_range(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,pmd_t * dst_pmd,pmd_t * src_pmd,unsigned long addr,unsigned long end)1071 copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1072 pmd_t *dst_pmd, pmd_t *src_pmd, unsigned long addr,
1073 unsigned long end)
1074 {
1075 struct mm_struct *dst_mm = dst_vma->vm_mm;
1076 struct mm_struct *src_mm = src_vma->vm_mm;
1077 pte_t *orig_src_pte, *orig_dst_pte;
1078 pte_t *src_pte, *dst_pte;
1079 pmd_t dummy_pmdval;
1080 pte_t ptent;
1081 spinlock_t *src_ptl, *dst_ptl;
1082 int progress, max_nr, ret = 0;
1083 int rss[NR_MM_COUNTERS];
1084 swp_entry_t entry = (swp_entry_t){0};
1085 struct folio *prealloc = NULL;
1086 int nr;
1087
1088 again:
1089 progress = 0;
1090 init_rss_vec(rss);
1091
1092 /*
1093 * copy_pmd_range()'s prior pmd_none_or_clear_bad(src_pmd), and the
1094 * error handling here, assume that exclusive mmap_lock on dst and src
1095 * protects anon from unexpected THP transitions; with shmem and file
1096 * protected by mmap_lock-less collapse skipping areas with anon_vma
1097 * (whereas vma_needs_copy() skips areas without anon_vma). A rework
1098 * can remove such assumptions later, but this is good enough for now.
1099 */
1100 dst_pte = pte_alloc_map_lock(dst_mm, dst_pmd, addr, &dst_ptl);
1101 if (!dst_pte) {
1102 ret = -ENOMEM;
1103 goto out;
1104 }
1105
1106 /*
1107 * We already hold the exclusive mmap_lock, the copy_pte_range() and
1108 * retract_page_tables() are using vma->anon_vma to be exclusive, so
1109 * the PTE page is stable, and there is no need to get pmdval and do
1110 * pmd_same() check.
1111 */
1112 src_pte = pte_offset_map_rw_nolock(src_mm, src_pmd, addr, &dummy_pmdval,
1113 &src_ptl);
1114 if (!src_pte) {
1115 pte_unmap_unlock(dst_pte, dst_ptl);
1116 /* ret == 0 */
1117 goto out;
1118 }
1119 spin_lock_nested(src_ptl, SINGLE_DEPTH_NESTING);
1120 orig_src_pte = src_pte;
1121 orig_dst_pte = dst_pte;
1122 arch_enter_lazy_mmu_mode();
1123
1124 do {
1125 nr = 1;
1126
1127 /*
1128 * We are holding two locks at this point - either of them
1129 * could generate latencies in another task on another CPU.
1130 */
1131 if (progress >= 32) {
1132 progress = 0;
1133 if (need_resched() ||
1134 spin_needbreak(src_ptl) || spin_needbreak(dst_ptl))
1135 break;
1136 }
1137 ptent = ptep_get(src_pte);
1138 if (pte_none(ptent)) {
1139 progress++;
1140 continue;
1141 }
1142 if (unlikely(!pte_present(ptent))) {
1143 ret = copy_nonpresent_pte(dst_mm, src_mm,
1144 dst_pte, src_pte,
1145 dst_vma, src_vma,
1146 addr, rss);
1147 if (ret == -EIO) {
1148 entry = pte_to_swp_entry(ptep_get(src_pte));
1149 break;
1150 } else if (ret == -EBUSY) {
1151 break;
1152 } else if (!ret) {
1153 progress += 8;
1154 continue;
1155 }
1156 ptent = ptep_get(src_pte);
1157 VM_WARN_ON_ONCE(!pte_present(ptent));
1158
1159 /*
1160 * Device exclusive entry restored, continue by copying
1161 * the now present pte.
1162 */
1163 WARN_ON_ONCE(ret != -ENOENT);
1164 }
1165 /* copy_present_ptes() will clear `*prealloc' if consumed */
1166 max_nr = (end - addr) / PAGE_SIZE;
1167 ret = copy_present_ptes(dst_vma, src_vma, dst_pte, src_pte,
1168 ptent, addr, max_nr, rss, &prealloc);
1169 /*
1170 * If we need a pre-allocated page for this pte, drop the
1171 * locks, allocate, and try again.
1172 * If copy failed due to hwpoison in source page, break out.
1173 */
1174 if (unlikely(ret == -EAGAIN || ret == -EHWPOISON))
1175 break;
1176 if (unlikely(prealloc)) {
1177 /*
1178 * pre-alloc page cannot be reused by next time so as
1179 * to strictly follow mempolicy (e.g., alloc_page_vma()
1180 * will allocate page according to address). This
1181 * could only happen if one pinned pte changed.
1182 */
1183 folio_put(prealloc);
1184 prealloc = NULL;
1185 }
1186 nr = ret;
1187 progress += 8 * nr;
1188 } while (dst_pte += nr, src_pte += nr, addr += PAGE_SIZE * nr,
1189 addr != end);
1190
1191 arch_leave_lazy_mmu_mode();
1192 pte_unmap_unlock(orig_src_pte, src_ptl);
1193 add_mm_rss_vec(dst_mm, rss);
1194 pte_unmap_unlock(orig_dst_pte, dst_ptl);
1195 cond_resched();
1196
1197 if (ret == -EIO) {
1198 VM_WARN_ON_ONCE(!entry.val);
1199 if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
1200 ret = -ENOMEM;
1201 goto out;
1202 }
1203 entry.val = 0;
1204 } else if (ret == -EBUSY || unlikely(ret == -EHWPOISON)) {
1205 goto out;
1206 } else if (ret == -EAGAIN) {
1207 prealloc = folio_prealloc(src_mm, src_vma, addr, false);
1208 if (!prealloc)
1209 return -ENOMEM;
1210 } else if (ret < 0) {
1211 VM_WARN_ON_ONCE(1);
1212 }
1213
1214 /* We've captured and resolved the error. Reset, try again. */
1215 ret = 0;
1216
1217 if (addr != end)
1218 goto again;
1219 out:
1220 if (unlikely(prealloc))
1221 folio_put(prealloc);
1222 return ret;
1223 }
1224
1225 static inline int
copy_pmd_range(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,pud_t * dst_pud,pud_t * src_pud,unsigned long addr,unsigned long end)1226 copy_pmd_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1227 pud_t *dst_pud, pud_t *src_pud, unsigned long addr,
1228 unsigned long end)
1229 {
1230 struct mm_struct *dst_mm = dst_vma->vm_mm;
1231 struct mm_struct *src_mm = src_vma->vm_mm;
1232 pmd_t *src_pmd, *dst_pmd;
1233 unsigned long next;
1234
1235 dst_pmd = pmd_alloc(dst_mm, dst_pud, addr);
1236 if (!dst_pmd)
1237 return -ENOMEM;
1238 src_pmd = pmd_offset(src_pud, addr);
1239 do {
1240 next = pmd_addr_end(addr, end);
1241 if (is_swap_pmd(*src_pmd) || pmd_trans_huge(*src_pmd)
1242 || pmd_devmap(*src_pmd)) {
1243 int err;
1244 VM_BUG_ON_VMA(next-addr != HPAGE_PMD_SIZE, src_vma);
1245 err = copy_huge_pmd(dst_mm, src_mm, dst_pmd, src_pmd,
1246 addr, dst_vma, src_vma);
1247 if (err == -ENOMEM)
1248 return -ENOMEM;
1249 if (!err)
1250 continue;
1251 /* fall through */
1252 }
1253 if (pmd_none_or_clear_bad(src_pmd))
1254 continue;
1255 if (copy_pte_range(dst_vma, src_vma, dst_pmd, src_pmd,
1256 addr, next))
1257 return -ENOMEM;
1258 } while (dst_pmd++, src_pmd++, addr = next, addr != end);
1259 return 0;
1260 }
1261
1262 static inline int
copy_pud_range(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,p4d_t * dst_p4d,p4d_t * src_p4d,unsigned long addr,unsigned long end)1263 copy_pud_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1264 p4d_t *dst_p4d, p4d_t *src_p4d, unsigned long addr,
1265 unsigned long end)
1266 {
1267 struct mm_struct *dst_mm = dst_vma->vm_mm;
1268 struct mm_struct *src_mm = src_vma->vm_mm;
1269 pud_t *src_pud, *dst_pud;
1270 unsigned long next;
1271
1272 dst_pud = pud_alloc(dst_mm, dst_p4d, addr);
1273 if (!dst_pud)
1274 return -ENOMEM;
1275 src_pud = pud_offset(src_p4d, addr);
1276 do {
1277 next = pud_addr_end(addr, end);
1278 if (pud_trans_huge(*src_pud) || pud_devmap(*src_pud)) {
1279 int err;
1280
1281 VM_BUG_ON_VMA(next-addr != HPAGE_PUD_SIZE, src_vma);
1282 err = copy_huge_pud(dst_mm, src_mm,
1283 dst_pud, src_pud, addr, src_vma);
1284 if (err == -ENOMEM)
1285 return -ENOMEM;
1286 if (!err)
1287 continue;
1288 /* fall through */
1289 }
1290 if (pud_none_or_clear_bad(src_pud))
1291 continue;
1292 if (copy_pmd_range(dst_vma, src_vma, dst_pud, src_pud,
1293 addr, next))
1294 return -ENOMEM;
1295 } while (dst_pud++, src_pud++, addr = next, addr != end);
1296 return 0;
1297 }
1298
1299 static inline int
copy_p4d_range(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma,pgd_t * dst_pgd,pgd_t * src_pgd,unsigned long addr,unsigned long end)1300 copy_p4d_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
1301 pgd_t *dst_pgd, pgd_t *src_pgd, unsigned long addr,
1302 unsigned long end)
1303 {
1304 struct mm_struct *dst_mm = dst_vma->vm_mm;
1305 p4d_t *src_p4d, *dst_p4d;
1306 unsigned long next;
1307
1308 dst_p4d = p4d_alloc(dst_mm, dst_pgd, addr);
1309 if (!dst_p4d)
1310 return -ENOMEM;
1311 src_p4d = p4d_offset(src_pgd, addr);
1312 do {
1313 next = p4d_addr_end(addr, end);
1314 if (p4d_none_or_clear_bad(src_p4d))
1315 continue;
1316 if (copy_pud_range(dst_vma, src_vma, dst_p4d, src_p4d,
1317 addr, next))
1318 return -ENOMEM;
1319 } while (dst_p4d++, src_p4d++, addr = next, addr != end);
1320 return 0;
1321 }
1322
1323 /*
1324 * Return true if the vma needs to copy the pgtable during this fork(). Return
1325 * false when we can speed up fork() by allowing lazy page faults later until
1326 * when the child accesses the memory range.
1327 */
1328 static bool
vma_needs_copy(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma)1329 vma_needs_copy(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1330 {
1331 /*
1332 * Always copy pgtables when dst_vma has uffd-wp enabled even if it's
1333 * file-backed (e.g. shmem). Because when uffd-wp is enabled, pgtable
1334 * contains uffd-wp protection information, that's something we can't
1335 * retrieve from page cache, and skip copying will lose those info.
1336 */
1337 if (userfaultfd_wp(dst_vma))
1338 return true;
1339
1340 if (src_vma->vm_flags & (VM_PFNMAP | VM_MIXEDMAP))
1341 return true;
1342
1343 if (src_vma->anon_vma)
1344 return true;
1345
1346 /*
1347 * Don't copy ptes where a page fault will fill them correctly. Fork
1348 * becomes much lighter when there are big shared or private readonly
1349 * mappings. The tradeoff is that copy_page_range is more efficient
1350 * than faulting.
1351 */
1352 return false;
1353 }
1354
1355 int
copy_page_range(struct vm_area_struct * dst_vma,struct vm_area_struct * src_vma)1356 copy_page_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma)
1357 {
1358 pgd_t *src_pgd, *dst_pgd;
1359 unsigned long addr = src_vma->vm_start;
1360 unsigned long end = src_vma->vm_end;
1361 struct mm_struct *dst_mm = dst_vma->vm_mm;
1362 struct mm_struct *src_mm = src_vma->vm_mm;
1363 struct mmu_notifier_range range;
1364 unsigned long next, pfn;
1365 bool is_cow;
1366 int ret;
1367
1368 if (!vma_needs_copy(dst_vma, src_vma))
1369 return 0;
1370
1371 if (is_vm_hugetlb_page(src_vma))
1372 return copy_hugetlb_page_range(dst_mm, src_mm, dst_vma, src_vma);
1373
1374 if (unlikely(src_vma->vm_flags & VM_PFNMAP)) {
1375 ret = track_pfn_copy(dst_vma, src_vma, &pfn);
1376 if (ret)
1377 return ret;
1378 }
1379
1380 /*
1381 * We need to invalidate the secondary MMU mappings only when
1382 * there could be a permission downgrade on the ptes of the
1383 * parent mm. And a permission downgrade will only happen if
1384 * is_cow_mapping() returns true.
1385 */
1386 is_cow = is_cow_mapping(src_vma->vm_flags);
1387
1388 if (is_cow) {
1389 mmu_notifier_range_init(&range, MMU_NOTIFY_PROTECTION_PAGE,
1390 0, src_mm, addr, end);
1391 mmu_notifier_invalidate_range_start(&range);
1392 /*
1393 * Disabling preemption is not needed for the write side, as
1394 * the read side doesn't spin, but goes to the mmap_lock.
1395 *
1396 * Use the raw variant of the seqcount_t write API to avoid
1397 * lockdep complaining about preemptibility.
1398 */
1399 vma_assert_write_locked(src_vma);
1400 raw_write_seqcount_begin(&src_mm->write_protect_seq);
1401 }
1402
1403 ret = 0;
1404 dst_pgd = pgd_offset(dst_mm, addr);
1405 src_pgd = pgd_offset(src_mm, addr);
1406 do {
1407 next = pgd_addr_end(addr, end);
1408 if (pgd_none_or_clear_bad(src_pgd))
1409 continue;
1410 if (unlikely(copy_p4d_range(dst_vma, src_vma, dst_pgd, src_pgd,
1411 addr, next))) {
1412 ret = -ENOMEM;
1413 break;
1414 }
1415 } while (dst_pgd++, src_pgd++, addr = next, addr != end);
1416
1417 if (is_cow) {
1418 raw_write_seqcount_end(&src_mm->write_protect_seq);
1419 mmu_notifier_invalidate_range_end(&range);
1420 }
1421 if (ret && unlikely(src_vma->vm_flags & VM_PFNMAP))
1422 untrack_pfn_copy(dst_vma, pfn);
1423 return ret;
1424 }
1425
1426 /* Whether we should zap all COWed (private) pages too */
should_zap_cows(struct zap_details * details)1427 static inline bool should_zap_cows(struct zap_details *details)
1428 {
1429 /* By default, zap all pages */
1430 if (!details || details->reclaim_pt)
1431 return true;
1432
1433 /* Or, we zap COWed pages only if the caller wants to */
1434 return details->even_cows;
1435 }
1436
1437 /* Decides whether we should zap this folio with the folio pointer specified */
should_zap_folio(struct zap_details * details,struct folio * folio)1438 static inline bool should_zap_folio(struct zap_details *details,
1439 struct folio *folio)
1440 {
1441 /* If we can make a decision without *folio.. */
1442 if (should_zap_cows(details))
1443 return true;
1444
1445 /* Otherwise we should only zap non-anon folios */
1446 return !folio_test_anon(folio);
1447 }
1448
zap_drop_markers(struct zap_details * details)1449 static inline bool zap_drop_markers(struct zap_details *details)
1450 {
1451 if (!details)
1452 return false;
1453
1454 return details->zap_flags & ZAP_FLAG_DROP_MARKER;
1455 }
1456
1457 /*
1458 * This function makes sure that we'll replace the none pte with an uffd-wp
1459 * swap special pte marker when necessary. Must be with the pgtable lock held.
1460 *
1461 * Returns true if uffd-wp ptes was installed, false otherwise.
1462 */
1463 static inline bool
zap_install_uffd_wp_if_needed(struct vm_area_struct * vma,unsigned long addr,pte_t * pte,int nr,struct zap_details * details,pte_t pteval)1464 zap_install_uffd_wp_if_needed(struct vm_area_struct *vma,
1465 unsigned long addr, pte_t *pte, int nr,
1466 struct zap_details *details, pte_t pteval)
1467 {
1468 bool was_installed = false;
1469
1470 #ifdef CONFIG_PTE_MARKER_UFFD_WP
1471 /* Zap on anonymous always means dropping everything */
1472 if (vma_is_anonymous(vma))
1473 return false;
1474
1475 if (zap_drop_markers(details))
1476 return false;
1477
1478 for (;;) {
1479 /* the PFN in the PTE is irrelevant. */
1480 if (pte_install_uffd_wp_if_needed(vma, addr, pte, pteval))
1481 was_installed = true;
1482 if (--nr == 0)
1483 break;
1484 pte++;
1485 addr += PAGE_SIZE;
1486 }
1487 #endif
1488 return was_installed;
1489 }
1490
zap_present_folio_ptes(struct mmu_gather * tlb,struct vm_area_struct * vma,struct folio * folio,struct page * page,pte_t * pte,pte_t ptent,unsigned int nr,unsigned long addr,struct zap_details * details,int * rss,bool * force_flush,bool * force_break,bool * any_skipped)1491 static __always_inline void zap_present_folio_ptes(struct mmu_gather *tlb,
1492 struct vm_area_struct *vma, struct folio *folio,
1493 struct page *page, pte_t *pte, pte_t ptent, unsigned int nr,
1494 unsigned long addr, struct zap_details *details, int *rss,
1495 bool *force_flush, bool *force_break, bool *any_skipped)
1496 {
1497 struct mm_struct *mm = tlb->mm;
1498 bool delay_rmap = false;
1499
1500 if (!folio_test_anon(folio)) {
1501 ptent = get_and_clear_full_ptes(mm, addr, pte, nr, tlb->fullmm);
1502 if (pte_dirty(ptent)) {
1503 folio_mark_dirty(folio);
1504 if (tlb_delay_rmap(tlb)) {
1505 delay_rmap = true;
1506 *force_flush = true;
1507 }
1508 }
1509 if (pte_young(ptent) && likely(vma_has_recency(vma)))
1510 folio_mark_accessed(folio);
1511 rss[mm_counter(folio)] -= nr;
1512 } else {
1513 /* We don't need up-to-date accessed/dirty bits. */
1514 clear_full_ptes(mm, addr, pte, nr, tlb->fullmm);
1515 rss[MM_ANONPAGES] -= nr;
1516 }
1517 /* Checking a single PTE in a batch is sufficient. */
1518 arch_check_zapped_pte(vma, ptent);
1519 tlb_remove_tlb_entries(tlb, pte, nr, addr);
1520 if (unlikely(userfaultfd_pte_wp(vma, ptent)))
1521 *any_skipped = zap_install_uffd_wp_if_needed(vma, addr, pte,
1522 nr, details, ptent);
1523
1524 if (!delay_rmap) {
1525 folio_remove_rmap_ptes(folio, page, nr, vma);
1526
1527 if (unlikely(folio_mapcount(folio) < 0))
1528 print_bad_pte(vma, addr, ptent, page);
1529 }
1530 if (unlikely(__tlb_remove_folio_pages(tlb, page, nr, delay_rmap))) {
1531 *force_flush = true;
1532 *force_break = true;
1533 }
1534 }
1535
1536 /*
1537 * Zap or skip at least one present PTE, trying to batch-process subsequent
1538 * PTEs that map consecutive pages of the same folio.
1539 *
1540 * Returns the number of processed (skipped or zapped) PTEs (at least 1).
1541 */
zap_present_ptes(struct mmu_gather * tlb,struct vm_area_struct * vma,pte_t * pte,pte_t ptent,unsigned int max_nr,unsigned long addr,struct zap_details * details,int * rss,bool * force_flush,bool * force_break,bool * any_skipped)1542 static inline int zap_present_ptes(struct mmu_gather *tlb,
1543 struct vm_area_struct *vma, pte_t *pte, pte_t ptent,
1544 unsigned int max_nr, unsigned long addr,
1545 struct zap_details *details, int *rss, bool *force_flush,
1546 bool *force_break, bool *any_skipped)
1547 {
1548 const fpb_t fpb_flags = FPB_IGNORE_DIRTY | FPB_IGNORE_SOFT_DIRTY;
1549 struct mm_struct *mm = tlb->mm;
1550 struct folio *folio;
1551 struct page *page;
1552 int nr;
1553
1554 page = vm_normal_page(vma, addr, ptent);
1555 if (!page) {
1556 /* We don't need up-to-date accessed/dirty bits. */
1557 ptep_get_and_clear_full(mm, addr, pte, tlb->fullmm);
1558 arch_check_zapped_pte(vma, ptent);
1559 tlb_remove_tlb_entry(tlb, pte, addr);
1560 if (userfaultfd_pte_wp(vma, ptent))
1561 *any_skipped = zap_install_uffd_wp_if_needed(vma, addr,
1562 pte, 1, details, ptent);
1563 ksm_might_unmap_zero_page(mm, ptent);
1564 return 1;
1565 }
1566
1567 folio = page_folio(page);
1568 if (unlikely(!should_zap_folio(details, folio))) {
1569 *any_skipped = true;
1570 return 1;
1571 }
1572
1573 /*
1574 * Make sure that the common "small folio" case is as fast as possible
1575 * by keeping the batching logic separate.
1576 */
1577 if (unlikely(folio_test_large(folio) && max_nr != 1)) {
1578 nr = folio_pte_batch(folio, addr, pte, ptent, max_nr, fpb_flags,
1579 NULL, NULL, NULL);
1580
1581 zap_present_folio_ptes(tlb, vma, folio, page, pte, ptent, nr,
1582 addr, details, rss, force_flush,
1583 force_break, any_skipped);
1584 return nr;
1585 }
1586 zap_present_folio_ptes(tlb, vma, folio, page, pte, ptent, 1, addr,
1587 details, rss, force_flush, force_break, any_skipped);
1588 return 1;
1589 }
1590
zap_nonpresent_ptes(struct mmu_gather * tlb,struct vm_area_struct * vma,pte_t * pte,pte_t ptent,unsigned int max_nr,unsigned long addr,struct zap_details * details,int * rss,bool * any_skipped)1591 static inline int zap_nonpresent_ptes(struct mmu_gather *tlb,
1592 struct vm_area_struct *vma, pte_t *pte, pte_t ptent,
1593 unsigned int max_nr, unsigned long addr,
1594 struct zap_details *details, int *rss, bool *any_skipped)
1595 {
1596 swp_entry_t entry;
1597 int nr = 1;
1598
1599 *any_skipped = true;
1600 entry = pte_to_swp_entry(ptent);
1601 if (is_device_private_entry(entry) ||
1602 is_device_exclusive_entry(entry)) {
1603 struct page *page = pfn_swap_entry_to_page(entry);
1604 struct folio *folio = page_folio(page);
1605
1606 if (unlikely(!should_zap_folio(details, folio)))
1607 return 1;
1608 /*
1609 * Both device private/exclusive mappings should only
1610 * work with anonymous page so far, so we don't need to
1611 * consider uffd-wp bit when zap. For more information,
1612 * see zap_install_uffd_wp_if_needed().
1613 */
1614 WARN_ON_ONCE(!vma_is_anonymous(vma));
1615 rss[mm_counter(folio)]--;
1616 folio_remove_rmap_pte(folio, page, vma);
1617 folio_put(folio);
1618 } else if (!non_swap_entry(entry)) {
1619 /* Genuine swap entries, hence a private anon pages */
1620 if (!should_zap_cows(details))
1621 return 1;
1622
1623 nr = swap_pte_batch(pte, max_nr, ptent);
1624 rss[MM_SWAPENTS] -= nr;
1625 free_swap_and_cache_nr(entry, nr);
1626 } else if (is_migration_entry(entry)) {
1627 struct folio *folio = pfn_swap_entry_folio(entry);
1628
1629 if (!should_zap_folio(details, folio))
1630 return 1;
1631 rss[mm_counter(folio)]--;
1632 } else if (pte_marker_entry_uffd_wp(entry)) {
1633 /*
1634 * For anon: always drop the marker; for file: only
1635 * drop the marker if explicitly requested.
1636 */
1637 if (!vma_is_anonymous(vma) && !zap_drop_markers(details))
1638 return 1;
1639 } else if (is_guard_swp_entry(entry)) {
1640 /*
1641 * Ordinary zapping should not remove guard PTE
1642 * markers. Only do so if we should remove PTE markers
1643 * in general.
1644 */
1645 if (!zap_drop_markers(details))
1646 return 1;
1647 } else if (is_hwpoison_entry(entry) || is_poisoned_swp_entry(entry)) {
1648 if (!should_zap_cows(details))
1649 return 1;
1650 } else {
1651 /* We should have covered all the swap entry types */
1652 pr_alert("unrecognized swap entry 0x%lx\n", entry.val);
1653 WARN_ON_ONCE(1);
1654 }
1655 clear_not_present_full_ptes(vma->vm_mm, addr, pte, nr, tlb->fullmm);
1656 *any_skipped = zap_install_uffd_wp_if_needed(vma, addr, pte, nr, details, ptent);
1657
1658 return nr;
1659 }
1660
do_zap_pte_range(struct mmu_gather * tlb,struct vm_area_struct * vma,pte_t * pte,unsigned long addr,unsigned long end,struct zap_details * details,int * rss,bool * force_flush,bool * force_break,bool * any_skipped)1661 static inline int do_zap_pte_range(struct mmu_gather *tlb,
1662 struct vm_area_struct *vma, pte_t *pte,
1663 unsigned long addr, unsigned long end,
1664 struct zap_details *details, int *rss,
1665 bool *force_flush, bool *force_break,
1666 bool *any_skipped)
1667 {
1668 pte_t ptent = ptep_get(pte);
1669 int max_nr = (end - addr) / PAGE_SIZE;
1670 int nr = 0;
1671
1672 /* Skip all consecutive none ptes */
1673 if (pte_none(ptent)) {
1674 for (nr = 1; nr < max_nr; nr++) {
1675 ptent = ptep_get(pte + nr);
1676 if (!pte_none(ptent))
1677 break;
1678 }
1679 max_nr -= nr;
1680 if (!max_nr)
1681 return nr;
1682 pte += nr;
1683 addr += nr * PAGE_SIZE;
1684 }
1685
1686 if (pte_present(ptent))
1687 nr += zap_present_ptes(tlb, vma, pte, ptent, max_nr, addr,
1688 details, rss, force_flush, force_break,
1689 any_skipped);
1690 else
1691 nr += zap_nonpresent_ptes(tlb, vma, pte, ptent, max_nr, addr,
1692 details, rss, any_skipped);
1693
1694 return nr;
1695 }
1696
zap_pte_range(struct mmu_gather * tlb,struct vm_area_struct * vma,pmd_t * pmd,unsigned long addr,unsigned long end,struct zap_details * details)1697 static unsigned long zap_pte_range(struct mmu_gather *tlb,
1698 struct vm_area_struct *vma, pmd_t *pmd,
1699 unsigned long addr, unsigned long end,
1700 struct zap_details *details)
1701 {
1702 bool force_flush = false, force_break = false;
1703 struct mm_struct *mm = tlb->mm;
1704 int rss[NR_MM_COUNTERS];
1705 spinlock_t *ptl;
1706 pte_t *start_pte;
1707 pte_t *pte;
1708 pmd_t pmdval;
1709 unsigned long start = addr;
1710 bool can_reclaim_pt = reclaim_pt_is_enabled(start, end, details);
1711 bool direct_reclaim = true;
1712 int nr;
1713
1714 retry:
1715 tlb_change_page_size(tlb, PAGE_SIZE);
1716 init_rss_vec(rss);
1717 start_pte = pte = pte_offset_map_lock(mm, pmd, addr, &ptl);
1718 if (!pte)
1719 return addr;
1720
1721 flush_tlb_batched_pending(mm);
1722 arch_enter_lazy_mmu_mode();
1723 do {
1724 bool any_skipped = false;
1725
1726 if (need_resched()) {
1727 direct_reclaim = false;
1728 break;
1729 }
1730
1731 nr = do_zap_pte_range(tlb, vma, pte, addr, end, details, rss,
1732 &force_flush, &force_break, &any_skipped);
1733 if (any_skipped)
1734 can_reclaim_pt = false;
1735 if (unlikely(force_break)) {
1736 addr += nr * PAGE_SIZE;
1737 direct_reclaim = false;
1738 break;
1739 }
1740 } while (pte += nr, addr += PAGE_SIZE * nr, addr != end);
1741
1742 /*
1743 * Fast path: try to hold the pmd lock and unmap the PTE page.
1744 *
1745 * If the pte lock was released midway (retry case), or if the attempt
1746 * to hold the pmd lock failed, then we need to recheck all pte entries
1747 * to ensure they are still none, thereby preventing the pte entries
1748 * from being repopulated by another thread.
1749 */
1750 if (can_reclaim_pt && direct_reclaim && addr == end)
1751 direct_reclaim = try_get_and_clear_pmd(mm, pmd, &pmdval);
1752
1753 add_mm_rss_vec(mm, rss);
1754 arch_leave_lazy_mmu_mode();
1755
1756 /* Do the actual TLB flush before dropping ptl */
1757 if (force_flush) {
1758 tlb_flush_mmu_tlbonly(tlb);
1759 tlb_flush_rmaps(tlb, vma);
1760 }
1761 pte_unmap_unlock(start_pte, ptl);
1762
1763 /*
1764 * If we forced a TLB flush (either due to running out of
1765 * batch buffers or because we needed to flush dirty TLB
1766 * entries before releasing the ptl), free the batched
1767 * memory too. Come back again if we didn't do everything.
1768 */
1769 if (force_flush)
1770 tlb_flush_mmu(tlb);
1771
1772 if (addr != end) {
1773 cond_resched();
1774 force_flush = false;
1775 force_break = false;
1776 goto retry;
1777 }
1778
1779 if (can_reclaim_pt) {
1780 if (direct_reclaim)
1781 free_pte(mm, start, tlb, pmdval);
1782 else
1783 try_to_free_pte(mm, pmd, start, tlb);
1784 }
1785
1786 return addr;
1787 }
1788
zap_pmd_range(struct mmu_gather * tlb,struct vm_area_struct * vma,pud_t * pud,unsigned long addr,unsigned long end,struct zap_details * details)1789 static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
1790 struct vm_area_struct *vma, pud_t *pud,
1791 unsigned long addr, unsigned long end,
1792 struct zap_details *details)
1793 {
1794 pmd_t *pmd;
1795 unsigned long next;
1796
1797 pmd = pmd_offset(pud, addr);
1798 do {
1799 next = pmd_addr_end(addr, end);
1800 if (is_swap_pmd(*pmd) || pmd_trans_huge(*pmd) || pmd_devmap(*pmd)) {
1801 if (next - addr != HPAGE_PMD_SIZE)
1802 __split_huge_pmd(vma, pmd, addr, false, NULL);
1803 else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
1804 addr = next;
1805 continue;
1806 }
1807 /* fall through */
1808 } else if (details && details->single_folio &&
1809 folio_test_pmd_mappable(details->single_folio) &&
1810 next - addr == HPAGE_PMD_SIZE && pmd_none(*pmd)) {
1811 spinlock_t *ptl = pmd_lock(tlb->mm, pmd);
1812 /*
1813 * Take and drop THP pmd lock so that we cannot return
1814 * prematurely, while zap_huge_pmd() has cleared *pmd,
1815 * but not yet decremented compound_mapcount().
1816 */
1817 spin_unlock(ptl);
1818 }
1819 if (pmd_none(*pmd)) {
1820 addr = next;
1821 continue;
1822 }
1823 addr = zap_pte_range(tlb, vma, pmd, addr, next, details);
1824 if (addr != next)
1825 pmd--;
1826 } while (pmd++, cond_resched(), addr != end);
1827
1828 return addr;
1829 }
1830
zap_pud_range(struct mmu_gather * tlb,struct vm_area_struct * vma,p4d_t * p4d,unsigned long addr,unsigned long end,struct zap_details * details)1831 static inline unsigned long zap_pud_range(struct mmu_gather *tlb,
1832 struct vm_area_struct *vma, p4d_t *p4d,
1833 unsigned long addr, unsigned long end,
1834 struct zap_details *details)
1835 {
1836 pud_t *pud;
1837 unsigned long next;
1838
1839 pud = pud_offset(p4d, addr);
1840 do {
1841 next = pud_addr_end(addr, end);
1842 if (pud_trans_huge(*pud) || pud_devmap(*pud)) {
1843 if (next - addr != HPAGE_PUD_SIZE) {
1844 mmap_assert_locked(tlb->mm);
1845 split_huge_pud(vma, pud, addr);
1846 } else if (zap_huge_pud(tlb, vma, pud, addr))
1847 goto next;
1848 /* fall through */
1849 }
1850 if (pud_none_or_clear_bad(pud))
1851 continue;
1852 next = zap_pmd_range(tlb, vma, pud, addr, next, details);
1853 next:
1854 cond_resched();
1855 } while (pud++, addr = next, addr != end);
1856
1857 return addr;
1858 }
1859
zap_p4d_range(struct mmu_gather * tlb,struct vm_area_struct * vma,pgd_t * pgd,unsigned long addr,unsigned long end,struct zap_details * details)1860 static inline unsigned long zap_p4d_range(struct mmu_gather *tlb,
1861 struct vm_area_struct *vma, pgd_t *pgd,
1862 unsigned long addr, unsigned long end,
1863 struct zap_details *details)
1864 {
1865 p4d_t *p4d;
1866 unsigned long next;
1867
1868 p4d = p4d_offset(pgd, addr);
1869 do {
1870 next = p4d_addr_end(addr, end);
1871 if (p4d_none_or_clear_bad(p4d))
1872 continue;
1873 next = zap_pud_range(tlb, vma, p4d, addr, next, details);
1874 } while (p4d++, addr = next, addr != end);
1875
1876 return addr;
1877 }
1878
unmap_page_range(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long addr,unsigned long end,struct zap_details * details)1879 void unmap_page_range(struct mmu_gather *tlb,
1880 struct vm_area_struct *vma,
1881 unsigned long addr, unsigned long end,
1882 struct zap_details *details)
1883 {
1884 pgd_t *pgd;
1885 unsigned long next;
1886
1887 BUG_ON(addr >= end);
1888 tlb_start_vma(tlb, vma);
1889 pgd = pgd_offset(vma->vm_mm, addr);
1890 do {
1891 next = pgd_addr_end(addr, end);
1892 if (pgd_none_or_clear_bad(pgd))
1893 continue;
1894 next = zap_p4d_range(tlb, vma, pgd, addr, next, details);
1895 } while (pgd++, addr = next, addr != end);
1896 tlb_end_vma(tlb, vma);
1897 }
1898
1899
unmap_single_vma(struct mmu_gather * tlb,struct vm_area_struct * vma,unsigned long start_addr,unsigned long end_addr,struct zap_details * details,bool mm_wr_locked)1900 static void unmap_single_vma(struct mmu_gather *tlb,
1901 struct vm_area_struct *vma, unsigned long start_addr,
1902 unsigned long end_addr,
1903 struct zap_details *details, bool mm_wr_locked)
1904 {
1905 unsigned long start = max(vma->vm_start, start_addr);
1906 unsigned long end;
1907
1908 if (start >= vma->vm_end)
1909 return;
1910 end = min(vma->vm_end, end_addr);
1911 if (end <= vma->vm_start)
1912 return;
1913
1914 if (vma->vm_file)
1915 uprobe_munmap(vma, start, end);
1916
1917 if (unlikely(vma->vm_flags & VM_PFNMAP))
1918 untrack_pfn(vma, 0, 0, mm_wr_locked);
1919
1920 if (start != end) {
1921 if (unlikely(is_vm_hugetlb_page(vma))) {
1922 /*
1923 * It is undesirable to test vma->vm_file as it
1924 * should be non-null for valid hugetlb area.
1925 * However, vm_file will be NULL in the error
1926 * cleanup path of mmap_region. When
1927 * hugetlbfs ->mmap method fails,
1928 * mmap_region() nullifies vma->vm_file
1929 * before calling this function to clean up.
1930 * Since no pte has actually been setup, it is
1931 * safe to do nothing in this case.
1932 */
1933 if (vma->vm_file) {
1934 zap_flags_t zap_flags = details ?
1935 details->zap_flags : 0;
1936 __unmap_hugepage_range(tlb, vma, start, end,
1937 NULL, zap_flags);
1938 }
1939 } else
1940 unmap_page_range(tlb, vma, start, end, details);
1941 }
1942 }
1943
1944 /**
1945 * unmap_vmas - unmap a range of memory covered by a list of vma's
1946 * @tlb: address of the caller's struct mmu_gather
1947 * @mas: the maple state
1948 * @vma: the starting vma
1949 * @start_addr: virtual address at which to start unmapping
1950 * @end_addr: virtual address at which to end unmapping
1951 * @tree_end: The maximum index to check
1952 * @mm_wr_locked: lock flag
1953 *
1954 * Unmap all pages in the vma list.
1955 *
1956 * Only addresses between `start' and `end' will be unmapped.
1957 *
1958 * The VMA list must be sorted in ascending virtual address order.
1959 *
1960 * unmap_vmas() assumes that the caller will flush the whole unmapped address
1961 * range after unmap_vmas() returns. So the only responsibility here is to
1962 * ensure that any thus-far unmapped pages are flushed before unmap_vmas()
1963 * drops the lock and schedules.
1964 */
unmap_vmas(struct mmu_gather * tlb,struct ma_state * mas,struct vm_area_struct * vma,unsigned long start_addr,unsigned long end_addr,unsigned long tree_end,bool mm_wr_locked)1965 void unmap_vmas(struct mmu_gather *tlb, struct ma_state *mas,
1966 struct vm_area_struct *vma, unsigned long start_addr,
1967 unsigned long end_addr, unsigned long tree_end,
1968 bool mm_wr_locked)
1969 {
1970 struct mmu_notifier_range range;
1971 struct zap_details details = {
1972 .zap_flags = ZAP_FLAG_DROP_MARKER | ZAP_FLAG_UNMAP,
1973 /* Careful - we need to zap private pages too! */
1974 .even_cows = true,
1975 };
1976
1977 mmu_notifier_range_init(&range, MMU_NOTIFY_UNMAP, 0, vma->vm_mm,
1978 start_addr, end_addr);
1979 mmu_notifier_invalidate_range_start(&range);
1980 do {
1981 unsigned long start = start_addr;
1982 unsigned long end = end_addr;
1983 hugetlb_zap_begin(vma, &start, &end);
1984 unmap_single_vma(tlb, vma, start, end, &details,
1985 mm_wr_locked);
1986 hugetlb_zap_end(vma, &details);
1987 vma = mas_find(mas, tree_end - 1);
1988 } while (vma && likely(!xa_is_zero(vma)));
1989 mmu_notifier_invalidate_range_end(&range);
1990 }
1991
1992 /**
1993 * zap_page_range_single - remove user pages in a given range
1994 * @vma: vm_area_struct holding the applicable pages
1995 * @address: starting address of pages to zap
1996 * @size: number of bytes to zap
1997 * @details: details of shared cache invalidation
1998 *
1999 * The range must fit into one VMA.
2000 */
zap_page_range_single(struct vm_area_struct * vma,unsigned long address,unsigned long size,struct zap_details * details)2001 void zap_page_range_single(struct vm_area_struct *vma, unsigned long address,
2002 unsigned long size, struct zap_details *details)
2003 {
2004 const unsigned long end = address + size;
2005 struct mmu_notifier_range range;
2006 struct mmu_gather tlb;
2007
2008 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, vma->vm_mm,
2009 address, end);
2010 hugetlb_zap_begin(vma, &range.start, &range.end);
2011 tlb_gather_mmu(&tlb, vma->vm_mm);
2012 update_hiwater_rss(vma->vm_mm);
2013 mmu_notifier_invalidate_range_start(&range);
2014 /*
2015 * unmap 'address-end' not 'range.start-range.end' as range
2016 * could have been expanded for hugetlb pmd sharing.
2017 */
2018 unmap_single_vma(&tlb, vma, address, end, details, false);
2019 mmu_notifier_invalidate_range_end(&range);
2020 tlb_finish_mmu(&tlb);
2021 hugetlb_zap_end(vma, details);
2022 }
2023
2024 /**
2025 * zap_vma_ptes - remove ptes mapping the vma
2026 * @vma: vm_area_struct holding ptes to be zapped
2027 * @address: starting address of pages to zap
2028 * @size: number of bytes to zap
2029 *
2030 * This function only unmaps ptes assigned to VM_PFNMAP vmas.
2031 *
2032 * The entire address range must be fully contained within the vma.
2033 *
2034 */
zap_vma_ptes(struct vm_area_struct * vma,unsigned long address,unsigned long size)2035 void zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
2036 unsigned long size)
2037 {
2038 if (!range_in_vma(vma, address, address + size) ||
2039 !(vma->vm_flags & VM_PFNMAP))
2040 return;
2041
2042 zap_page_range_single(vma, address, size, NULL);
2043 }
2044 EXPORT_SYMBOL_GPL(zap_vma_ptes);
2045
walk_to_pmd(struct mm_struct * mm,unsigned long addr)2046 static pmd_t *walk_to_pmd(struct mm_struct *mm, unsigned long addr)
2047 {
2048 pgd_t *pgd;
2049 p4d_t *p4d;
2050 pud_t *pud;
2051 pmd_t *pmd;
2052
2053 pgd = pgd_offset(mm, addr);
2054 p4d = p4d_alloc(mm, pgd, addr);
2055 if (!p4d)
2056 return NULL;
2057 pud = pud_alloc(mm, p4d, addr);
2058 if (!pud)
2059 return NULL;
2060 pmd = pmd_alloc(mm, pud, addr);
2061 if (!pmd)
2062 return NULL;
2063
2064 VM_BUG_ON(pmd_trans_huge(*pmd));
2065 return pmd;
2066 }
2067
__get_locked_pte(struct mm_struct * mm,unsigned long addr,spinlock_t ** ptl)2068 pte_t *__get_locked_pte(struct mm_struct *mm, unsigned long addr,
2069 spinlock_t **ptl)
2070 {
2071 pmd_t *pmd = walk_to_pmd(mm, addr);
2072
2073 if (!pmd)
2074 return NULL;
2075 return pte_alloc_map_lock(mm, pmd, addr, ptl);
2076 }
2077
vm_mixed_zeropage_allowed(struct vm_area_struct * vma)2078 static bool vm_mixed_zeropage_allowed(struct vm_area_struct *vma)
2079 {
2080 VM_WARN_ON_ONCE(vma->vm_flags & VM_PFNMAP);
2081 /*
2082 * Whoever wants to forbid the zeropage after some zeropages
2083 * might already have been mapped has to scan the page tables and
2084 * bail out on any zeropages. Zeropages in COW mappings can
2085 * be unshared using FAULT_FLAG_UNSHARE faults.
2086 */
2087 if (mm_forbids_zeropage(vma->vm_mm))
2088 return false;
2089 /* zeropages in COW mappings are common and unproblematic. */
2090 if (is_cow_mapping(vma->vm_flags))
2091 return true;
2092 /* Mappings that do not allow for writable PTEs are unproblematic. */
2093 if (!(vma->vm_flags & (VM_WRITE | VM_MAYWRITE)))
2094 return true;
2095 /*
2096 * Why not allow any VMA that has vm_ops->pfn_mkwrite? GUP could
2097 * find the shared zeropage and longterm-pin it, which would
2098 * be problematic as soon as the zeropage gets replaced by a different
2099 * page due to vma->vm_ops->pfn_mkwrite, because what's mapped would
2100 * now differ to what GUP looked up. FSDAX is incompatible to
2101 * FOLL_LONGTERM and VM_IO is incompatible to GUP completely (see
2102 * check_vma_flags).
2103 */
2104 return vma->vm_ops && vma->vm_ops->pfn_mkwrite &&
2105 (vma_is_fsdax(vma) || vma->vm_flags & VM_IO);
2106 }
2107
validate_page_before_insert(struct vm_area_struct * vma,struct page * page)2108 static int validate_page_before_insert(struct vm_area_struct *vma,
2109 struct page *page)
2110 {
2111 struct folio *folio = page_folio(page);
2112
2113 if (!folio_ref_count(folio))
2114 return -EINVAL;
2115 if (unlikely(is_zero_folio(folio))) {
2116 if (!vm_mixed_zeropage_allowed(vma))
2117 return -EINVAL;
2118 return 0;
2119 }
2120 if (folio_test_anon(folio) || folio_test_slab(folio) ||
2121 page_has_type(page))
2122 return -EINVAL;
2123 flush_dcache_folio(folio);
2124 return 0;
2125 }
2126
insert_page_into_pte_locked(struct vm_area_struct * vma,pte_t * pte,unsigned long addr,struct page * page,pgprot_t prot,bool mkwrite)2127 static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
2128 unsigned long addr, struct page *page,
2129 pgprot_t prot, bool mkwrite)
2130 {
2131 struct folio *folio = page_folio(page);
2132 pte_t pteval = ptep_get(pte);
2133
2134 if (!pte_none(pteval)) {
2135 if (!mkwrite)
2136 return -EBUSY;
2137
2138 /* see insert_pfn(). */
2139 if (pte_pfn(pteval) != page_to_pfn(page)) {
2140 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(pteval)));
2141 return -EFAULT;
2142 }
2143 pteval = maybe_mkwrite(pteval, vma);
2144 pteval = pte_mkyoung(pteval);
2145 if (ptep_set_access_flags(vma, addr, pte, pteval, 1))
2146 update_mmu_cache(vma, addr, pte);
2147 return 0;
2148 }
2149
2150 /* Ok, finally just insert the thing.. */
2151 pteval = mk_pte(page, prot);
2152 if (unlikely(is_zero_folio(folio))) {
2153 pteval = pte_mkspecial(pteval);
2154 } else {
2155 folio_get(folio);
2156 pteval = mk_pte(page, prot);
2157 if (mkwrite) {
2158 pteval = pte_mkyoung(pteval);
2159 pteval = maybe_mkwrite(pte_mkdirty(pteval), vma);
2160 }
2161 inc_mm_counter(vma->vm_mm, mm_counter_file(folio));
2162 folio_add_file_rmap_pte(folio, page, vma);
2163 }
2164 set_pte_at(vma->vm_mm, addr, pte, pteval);
2165 return 0;
2166 }
2167
insert_page(struct vm_area_struct * vma,unsigned long addr,struct page * page,pgprot_t prot,bool mkwrite)2168 static int insert_page(struct vm_area_struct *vma, unsigned long addr,
2169 struct page *page, pgprot_t prot, bool mkwrite)
2170 {
2171 int retval;
2172 pte_t *pte;
2173 spinlock_t *ptl;
2174
2175 retval = validate_page_before_insert(vma, page);
2176 if (retval)
2177 goto out;
2178 retval = -ENOMEM;
2179 pte = get_locked_pte(vma->vm_mm, addr, &ptl);
2180 if (!pte)
2181 goto out;
2182 retval = insert_page_into_pte_locked(vma, pte, addr, page, prot,
2183 mkwrite);
2184 pte_unmap_unlock(pte, ptl);
2185 out:
2186 return retval;
2187 }
2188
insert_page_in_batch_locked(struct vm_area_struct * vma,pte_t * pte,unsigned long addr,struct page * page,pgprot_t prot)2189 static int insert_page_in_batch_locked(struct vm_area_struct *vma, pte_t *pte,
2190 unsigned long addr, struct page *page, pgprot_t prot)
2191 {
2192 int err;
2193
2194 err = validate_page_before_insert(vma, page);
2195 if (err)
2196 return err;
2197 return insert_page_into_pte_locked(vma, pte, addr, page, prot, false);
2198 }
2199
2200 /* insert_pages() amortizes the cost of spinlock operations
2201 * when inserting pages in a loop.
2202 */
insert_pages(struct vm_area_struct * vma,unsigned long addr,struct page ** pages,unsigned long * num,pgprot_t prot)2203 static int insert_pages(struct vm_area_struct *vma, unsigned long addr,
2204 struct page **pages, unsigned long *num, pgprot_t prot)
2205 {
2206 pmd_t *pmd = NULL;
2207 pte_t *start_pte, *pte;
2208 spinlock_t *pte_lock;
2209 struct mm_struct *const mm = vma->vm_mm;
2210 unsigned long curr_page_idx = 0;
2211 unsigned long remaining_pages_total = *num;
2212 unsigned long pages_to_write_in_pmd;
2213 int ret;
2214 more:
2215 ret = -EFAULT;
2216 pmd = walk_to_pmd(mm, addr);
2217 if (!pmd)
2218 goto out;
2219
2220 pages_to_write_in_pmd = min_t(unsigned long,
2221 remaining_pages_total, PTRS_PER_PTE - pte_index(addr));
2222
2223 /* Allocate the PTE if necessary; takes PMD lock once only. */
2224 ret = -ENOMEM;
2225 if (pte_alloc(mm, pmd))
2226 goto out;
2227
2228 while (pages_to_write_in_pmd) {
2229 int pte_idx = 0;
2230 const int batch_size = min_t(int, pages_to_write_in_pmd, 8);
2231
2232 start_pte = pte_offset_map_lock(mm, pmd, addr, &pte_lock);
2233 if (!start_pte) {
2234 ret = -EFAULT;
2235 goto out;
2236 }
2237 for (pte = start_pte; pte_idx < batch_size; ++pte, ++pte_idx) {
2238 int err = insert_page_in_batch_locked(vma, pte,
2239 addr, pages[curr_page_idx], prot);
2240 if (unlikely(err)) {
2241 pte_unmap_unlock(start_pte, pte_lock);
2242 ret = err;
2243 remaining_pages_total -= pte_idx;
2244 goto out;
2245 }
2246 addr += PAGE_SIZE;
2247 ++curr_page_idx;
2248 }
2249 pte_unmap_unlock(start_pte, pte_lock);
2250 pages_to_write_in_pmd -= batch_size;
2251 remaining_pages_total -= batch_size;
2252 }
2253 if (remaining_pages_total)
2254 goto more;
2255 ret = 0;
2256 out:
2257 *num = remaining_pages_total;
2258 return ret;
2259 }
2260
2261 /**
2262 * vm_insert_pages - insert multiple pages into user vma, batching the pmd lock.
2263 * @vma: user vma to map to
2264 * @addr: target start user address of these pages
2265 * @pages: source kernel pages
2266 * @num: in: number of pages to map. out: number of pages that were *not*
2267 * mapped. (0 means all pages were successfully mapped).
2268 *
2269 * Preferred over vm_insert_page() when inserting multiple pages.
2270 *
2271 * In case of error, we may have mapped a subset of the provided
2272 * pages. It is the caller's responsibility to account for this case.
2273 *
2274 * The same restrictions apply as in vm_insert_page().
2275 */
vm_insert_pages(struct vm_area_struct * vma,unsigned long addr,struct page ** pages,unsigned long * num)2276 int vm_insert_pages(struct vm_area_struct *vma, unsigned long addr,
2277 struct page **pages, unsigned long *num)
2278 {
2279 const unsigned long end_addr = addr + (*num * PAGE_SIZE) - 1;
2280
2281 if (addr < vma->vm_start || end_addr >= vma->vm_end)
2282 return -EFAULT;
2283 if (!(vma->vm_flags & VM_MIXEDMAP)) {
2284 BUG_ON(mmap_read_trylock(vma->vm_mm));
2285 BUG_ON(vma->vm_flags & VM_PFNMAP);
2286 vm_flags_set(vma, VM_MIXEDMAP);
2287 }
2288 /* Defer page refcount checking till we're about to map that page. */
2289 return insert_pages(vma, addr, pages, num, vma->vm_page_prot);
2290 }
2291 EXPORT_SYMBOL(vm_insert_pages);
2292
2293 /**
2294 * vm_insert_page - insert single page into user vma
2295 * @vma: user vma to map to
2296 * @addr: target user address of this page
2297 * @page: source kernel page
2298 *
2299 * This allows drivers to insert individual pages they've allocated
2300 * into a user vma. The zeropage is supported in some VMAs,
2301 * see vm_mixed_zeropage_allowed().
2302 *
2303 * The page has to be a nice clean _individual_ kernel allocation.
2304 * If you allocate a compound page, you need to have marked it as
2305 * such (__GFP_COMP), or manually just split the page up yourself
2306 * (see split_page()).
2307 *
2308 * NOTE! Traditionally this was done with "remap_pfn_range()" which
2309 * took an arbitrary page protection parameter. This doesn't allow
2310 * that. Your vma protection will have to be set up correctly, which
2311 * means that if you want a shared writable mapping, you'd better
2312 * ask for a shared writable mapping!
2313 *
2314 * The page does not need to be reserved.
2315 *
2316 * Usually this function is called from f_op->mmap() handler
2317 * under mm->mmap_lock write-lock, so it can change vma->vm_flags.
2318 * Caller must set VM_MIXEDMAP on vma if it wants to call this
2319 * function from other places, for example from page-fault handler.
2320 *
2321 * Return: %0 on success, negative error code otherwise.
2322 */
vm_insert_page(struct vm_area_struct * vma,unsigned long addr,struct page * page)2323 int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
2324 struct page *page)
2325 {
2326 if (addr < vma->vm_start || addr >= vma->vm_end)
2327 return -EFAULT;
2328 if (!(vma->vm_flags & VM_MIXEDMAP)) {
2329 BUG_ON(mmap_read_trylock(vma->vm_mm));
2330 BUG_ON(vma->vm_flags & VM_PFNMAP);
2331 vm_flags_set(vma, VM_MIXEDMAP);
2332 }
2333 return insert_page(vma, addr, page, vma->vm_page_prot, false);
2334 }
2335 EXPORT_SYMBOL(vm_insert_page);
2336
2337 /*
2338 * __vm_map_pages - maps range of kernel pages into user vma
2339 * @vma: user vma to map to
2340 * @pages: pointer to array of source kernel pages
2341 * @num: number of pages in page array
2342 * @offset: user's requested vm_pgoff
2343 *
2344 * This allows drivers to map range of kernel pages into a user vma.
2345 * The zeropage is supported in some VMAs, see
2346 * vm_mixed_zeropage_allowed().
2347 *
2348 * Return: 0 on success and error code otherwise.
2349 */
__vm_map_pages(struct vm_area_struct * vma,struct page ** pages,unsigned long num,unsigned long offset)2350 static int __vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2351 unsigned long num, unsigned long offset)
2352 {
2353 unsigned long count = vma_pages(vma);
2354 unsigned long uaddr = vma->vm_start;
2355 int ret, i;
2356
2357 /* Fail if the user requested offset is beyond the end of the object */
2358 if (offset >= num)
2359 return -ENXIO;
2360
2361 /* Fail if the user requested size exceeds available object size */
2362 if (count > num - offset)
2363 return -ENXIO;
2364
2365 for (i = 0; i < count; i++) {
2366 ret = vm_insert_page(vma, uaddr, pages[offset + i]);
2367 if (ret < 0)
2368 return ret;
2369 uaddr += PAGE_SIZE;
2370 }
2371
2372 return 0;
2373 }
2374
2375 /**
2376 * vm_map_pages - maps range of kernel pages starts with non zero offset
2377 * @vma: user vma to map to
2378 * @pages: pointer to array of source kernel pages
2379 * @num: number of pages in page array
2380 *
2381 * Maps an object consisting of @num pages, catering for the user's
2382 * requested vm_pgoff
2383 *
2384 * If we fail to insert any page into the vma, the function will return
2385 * immediately leaving any previously inserted pages present. Callers
2386 * from the mmap handler may immediately return the error as their caller
2387 * will destroy the vma, removing any successfully inserted pages. Other
2388 * callers should make their own arrangements for calling unmap_region().
2389 *
2390 * Context: Process context. Called by mmap handlers.
2391 * Return: 0 on success and error code otherwise.
2392 */
vm_map_pages(struct vm_area_struct * vma,struct page ** pages,unsigned long num)2393 int vm_map_pages(struct vm_area_struct *vma, struct page **pages,
2394 unsigned long num)
2395 {
2396 return __vm_map_pages(vma, pages, num, vma->vm_pgoff);
2397 }
2398 EXPORT_SYMBOL(vm_map_pages);
2399
2400 /**
2401 * vm_map_pages_zero - map range of kernel pages starts with zero offset
2402 * @vma: user vma to map to
2403 * @pages: pointer to array of source kernel pages
2404 * @num: number of pages in page array
2405 *
2406 * Similar to vm_map_pages(), except that it explicitly sets the offset
2407 * to 0. This function is intended for the drivers that did not consider
2408 * vm_pgoff.
2409 *
2410 * Context: Process context. Called by mmap handlers.
2411 * Return: 0 on success and error code otherwise.
2412 */
vm_map_pages_zero(struct vm_area_struct * vma,struct page ** pages,unsigned long num)2413 int vm_map_pages_zero(struct vm_area_struct *vma, struct page **pages,
2414 unsigned long num)
2415 {
2416 return __vm_map_pages(vma, pages, num, 0);
2417 }
2418 EXPORT_SYMBOL(vm_map_pages_zero);
2419
insert_pfn(struct vm_area_struct * vma,unsigned long addr,pfn_t pfn,pgprot_t prot,bool mkwrite)2420 static vm_fault_t insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2421 pfn_t pfn, pgprot_t prot, bool mkwrite)
2422 {
2423 struct mm_struct *mm = vma->vm_mm;
2424 pte_t *pte, entry;
2425 spinlock_t *ptl;
2426
2427 pte = get_locked_pte(mm, addr, &ptl);
2428 if (!pte)
2429 return VM_FAULT_OOM;
2430 entry = ptep_get(pte);
2431 if (!pte_none(entry)) {
2432 if (mkwrite) {
2433 /*
2434 * For read faults on private mappings the PFN passed
2435 * in may not match the PFN we have mapped if the
2436 * mapped PFN is a writeable COW page. In the mkwrite
2437 * case we are creating a writable PTE for a shared
2438 * mapping and we expect the PFNs to match. If they
2439 * don't match, we are likely racing with block
2440 * allocation and mapping invalidation so just skip the
2441 * update.
2442 */
2443 if (pte_pfn(entry) != pfn_t_to_pfn(pfn)) {
2444 WARN_ON_ONCE(!is_zero_pfn(pte_pfn(entry)));
2445 goto out_unlock;
2446 }
2447 entry = pte_mkyoung(entry);
2448 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2449 if (ptep_set_access_flags(vma, addr, pte, entry, 1))
2450 update_mmu_cache(vma, addr, pte);
2451 }
2452 goto out_unlock;
2453 }
2454
2455 /* Ok, finally just insert the thing.. */
2456 if (pfn_t_devmap(pfn))
2457 entry = pte_mkdevmap(pfn_t_pte(pfn, prot));
2458 else
2459 entry = pte_mkspecial(pfn_t_pte(pfn, prot));
2460
2461 if (mkwrite) {
2462 entry = pte_mkyoung(entry);
2463 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
2464 }
2465
2466 set_pte_at(mm, addr, pte, entry);
2467 update_mmu_cache(vma, addr, pte); /* XXX: why not for insert_page? */
2468
2469 out_unlock:
2470 pte_unmap_unlock(pte, ptl);
2471 return VM_FAULT_NOPAGE;
2472 }
2473
2474 /**
2475 * vmf_insert_pfn_prot - insert single pfn into user vma with specified pgprot
2476 * @vma: user vma to map to
2477 * @addr: target user address of this page
2478 * @pfn: source kernel pfn
2479 * @pgprot: pgprot flags for the inserted page
2480 *
2481 * This is exactly like vmf_insert_pfn(), except that it allows drivers
2482 * to override pgprot on a per-page basis.
2483 *
2484 * This only makes sense for IO mappings, and it makes no sense for
2485 * COW mappings. In general, using multiple vmas is preferable;
2486 * vmf_insert_pfn_prot should only be used if using multiple VMAs is
2487 * impractical.
2488 *
2489 * pgprot typically only differs from @vma->vm_page_prot when drivers set
2490 * caching- and encryption bits different than those of @vma->vm_page_prot,
2491 * because the caching- or encryption mode may not be known at mmap() time.
2492 *
2493 * This is ok as long as @vma->vm_page_prot is not used by the core vm
2494 * to set caching and encryption bits for those vmas (except for COW pages).
2495 * This is ensured by core vm only modifying these page table entries using
2496 * functions that don't touch caching- or encryption bits, using pte_modify()
2497 * if needed. (See for example mprotect()).
2498 *
2499 * Also when new page-table entries are created, this is only done using the
2500 * fault() callback, and never using the value of vma->vm_page_prot,
2501 * except for page-table entries that point to anonymous pages as the result
2502 * of COW.
2503 *
2504 * Context: Process context. May allocate using %GFP_KERNEL.
2505 * Return: vm_fault_t value.
2506 */
vmf_insert_pfn_prot(struct vm_area_struct * vma,unsigned long addr,unsigned long pfn,pgprot_t pgprot)2507 vm_fault_t vmf_insert_pfn_prot(struct vm_area_struct *vma, unsigned long addr,
2508 unsigned long pfn, pgprot_t pgprot)
2509 {
2510 /*
2511 * Technically, architectures with pte_special can avoid all these
2512 * restrictions (same for remap_pfn_range). However we would like
2513 * consistency in testing and feature parity among all, so we should
2514 * try to keep these invariants in place for everybody.
2515 */
2516 BUG_ON(!(vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)));
2517 BUG_ON((vma->vm_flags & (VM_PFNMAP|VM_MIXEDMAP)) ==
2518 (VM_PFNMAP|VM_MIXEDMAP));
2519 BUG_ON((vma->vm_flags & VM_PFNMAP) && is_cow_mapping(vma->vm_flags));
2520 BUG_ON((vma->vm_flags & VM_MIXEDMAP) && pfn_valid(pfn));
2521
2522 if (addr < vma->vm_start || addr >= vma->vm_end)
2523 return VM_FAULT_SIGBUS;
2524
2525 if (!pfn_modify_allowed(pfn, pgprot))
2526 return VM_FAULT_SIGBUS;
2527
2528 track_pfn_insert(vma, &pgprot, __pfn_to_pfn_t(pfn, PFN_DEV));
2529
2530 return insert_pfn(vma, addr, __pfn_to_pfn_t(pfn, PFN_DEV), pgprot,
2531 false);
2532 }
2533 EXPORT_SYMBOL(vmf_insert_pfn_prot);
2534
2535 /**
2536 * vmf_insert_pfn - insert single pfn into user vma
2537 * @vma: user vma to map to
2538 * @addr: target user address of this page
2539 * @pfn: source kernel pfn
2540 *
2541 * Similar to vm_insert_page, this allows drivers to insert individual pages
2542 * they've allocated into a user vma. Same comments apply.
2543 *
2544 * This function should only be called from a vm_ops->fault handler, and
2545 * in that case the handler should return the result of this function.
2546 *
2547 * vma cannot be a COW mapping.
2548 *
2549 * As this is called only for pages that do not currently exist, we
2550 * do not need to flush old virtual caches or the TLB.
2551 *
2552 * Context: Process context. May allocate using %GFP_KERNEL.
2553 * Return: vm_fault_t value.
2554 */
vmf_insert_pfn(struct vm_area_struct * vma,unsigned long addr,unsigned long pfn)2555 vm_fault_t vmf_insert_pfn(struct vm_area_struct *vma, unsigned long addr,
2556 unsigned long pfn)
2557 {
2558 return vmf_insert_pfn_prot(vma, addr, pfn, vma->vm_page_prot);
2559 }
2560 EXPORT_SYMBOL(vmf_insert_pfn);
2561
vm_mixed_ok(struct vm_area_struct * vma,pfn_t pfn,bool mkwrite)2562 static bool vm_mixed_ok(struct vm_area_struct *vma, pfn_t pfn, bool mkwrite)
2563 {
2564 if (unlikely(is_zero_pfn(pfn_t_to_pfn(pfn))) &&
2565 (mkwrite || !vm_mixed_zeropage_allowed(vma)))
2566 return false;
2567 /* these checks mirror the abort conditions in vm_normal_page */
2568 if (vma->vm_flags & VM_MIXEDMAP)
2569 return true;
2570 if (pfn_t_devmap(pfn))
2571 return true;
2572 if (pfn_t_special(pfn))
2573 return true;
2574 if (is_zero_pfn(pfn_t_to_pfn(pfn)))
2575 return true;
2576 return false;
2577 }
2578
__vm_insert_mixed(struct vm_area_struct * vma,unsigned long addr,pfn_t pfn,bool mkwrite)2579 static vm_fault_t __vm_insert_mixed(struct vm_area_struct *vma,
2580 unsigned long addr, pfn_t pfn, bool mkwrite)
2581 {
2582 pgprot_t pgprot = vma->vm_page_prot;
2583 int err;
2584
2585 if (!vm_mixed_ok(vma, pfn, mkwrite))
2586 return VM_FAULT_SIGBUS;
2587
2588 if (addr < vma->vm_start || addr >= vma->vm_end)
2589 return VM_FAULT_SIGBUS;
2590
2591 track_pfn_insert(vma, &pgprot, pfn);
2592
2593 if (!pfn_modify_allowed(pfn_t_to_pfn(pfn), pgprot))
2594 return VM_FAULT_SIGBUS;
2595
2596 /*
2597 * If we don't have pte special, then we have to use the pfn_valid()
2598 * based VM_MIXEDMAP scheme (see vm_normal_page), and thus we *must*
2599 * refcount the page if pfn_valid is true (hence insert_page rather
2600 * than insert_pfn). If a zero_pfn were inserted into a VM_MIXEDMAP
2601 * without pte special, it would there be refcounted as a normal page.
2602 */
2603 if (!IS_ENABLED(CONFIG_ARCH_HAS_PTE_SPECIAL) &&
2604 !pfn_t_devmap(pfn) && pfn_t_valid(pfn)) {
2605 struct page *page;
2606
2607 /*
2608 * At this point we are committed to insert_page()
2609 * regardless of whether the caller specified flags that
2610 * result in pfn_t_has_page() == false.
2611 */
2612 page = pfn_to_page(pfn_t_to_pfn(pfn));
2613 err = insert_page(vma, addr, page, pgprot, mkwrite);
2614 } else {
2615 return insert_pfn(vma, addr, pfn, pgprot, mkwrite);
2616 }
2617
2618 if (err == -ENOMEM)
2619 return VM_FAULT_OOM;
2620 if (err < 0 && err != -EBUSY)
2621 return VM_FAULT_SIGBUS;
2622
2623 return VM_FAULT_NOPAGE;
2624 }
2625
vmf_insert_page_mkwrite(struct vm_fault * vmf,struct page * page,bool write)2626 vm_fault_t vmf_insert_page_mkwrite(struct vm_fault *vmf, struct page *page,
2627 bool write)
2628 {
2629 pgprot_t pgprot = vmf->vma->vm_page_prot;
2630 unsigned long addr = vmf->address;
2631 int err;
2632
2633 if (addr < vmf->vma->vm_start || addr >= vmf->vma->vm_end)
2634 return VM_FAULT_SIGBUS;
2635
2636 err = insert_page(vmf->vma, addr, page, pgprot, write);
2637 if (err == -ENOMEM)
2638 return VM_FAULT_OOM;
2639 if (err < 0 && err != -EBUSY)
2640 return VM_FAULT_SIGBUS;
2641
2642 return VM_FAULT_NOPAGE;
2643 }
2644 EXPORT_SYMBOL_GPL(vmf_insert_page_mkwrite);
2645
vmf_insert_mixed(struct vm_area_struct * vma,unsigned long addr,pfn_t pfn)2646 vm_fault_t vmf_insert_mixed(struct vm_area_struct *vma, unsigned long addr,
2647 pfn_t pfn)
2648 {
2649 return __vm_insert_mixed(vma, addr, pfn, false);
2650 }
2651 EXPORT_SYMBOL(vmf_insert_mixed);
2652
2653 /*
2654 * If the insertion of PTE failed because someone else already added a
2655 * different entry in the mean time, we treat that as success as we assume
2656 * the same entry was actually inserted.
2657 */
vmf_insert_mixed_mkwrite(struct vm_area_struct * vma,unsigned long addr,pfn_t pfn)2658 vm_fault_t vmf_insert_mixed_mkwrite(struct vm_area_struct *vma,
2659 unsigned long addr, pfn_t pfn)
2660 {
2661 return __vm_insert_mixed(vma, addr, pfn, true);
2662 }
2663
2664 /*
2665 * maps a range of physical memory into the requested pages. the old
2666 * mappings are removed. any references to nonexistent pages results
2667 * in null mappings (currently treated as "copy-on-access")
2668 */
remap_pte_range(struct mm_struct * mm,pmd_t * pmd,unsigned long addr,unsigned long end,unsigned long pfn,pgprot_t prot)2669 static int remap_pte_range(struct mm_struct *mm, pmd_t *pmd,
2670 unsigned long addr, unsigned long end,
2671 unsigned long pfn, pgprot_t prot)
2672 {
2673 pte_t *pte, *mapped_pte;
2674 spinlock_t *ptl;
2675 int err = 0;
2676
2677 mapped_pte = pte = pte_alloc_map_lock(mm, pmd, addr, &ptl);
2678 if (!pte)
2679 return -ENOMEM;
2680 arch_enter_lazy_mmu_mode();
2681 do {
2682 BUG_ON(!pte_none(ptep_get(pte)));
2683 if (!pfn_modify_allowed(pfn, prot)) {
2684 err = -EACCES;
2685 break;
2686 }
2687 set_pte_at(mm, addr, pte, pte_mkspecial(pfn_pte(pfn, prot)));
2688 pfn++;
2689 } while (pte++, addr += PAGE_SIZE, addr != end);
2690 arch_leave_lazy_mmu_mode();
2691 pte_unmap_unlock(mapped_pte, ptl);
2692 return err;
2693 }
2694
remap_pmd_range(struct mm_struct * mm,pud_t * pud,unsigned long addr,unsigned long end,unsigned long pfn,pgprot_t prot)2695 static inline int remap_pmd_range(struct mm_struct *mm, pud_t *pud,
2696 unsigned long addr, unsigned long end,
2697 unsigned long pfn, pgprot_t prot)
2698 {
2699 pmd_t *pmd;
2700 unsigned long next;
2701 int err;
2702
2703 pfn -= addr >> PAGE_SHIFT;
2704 pmd = pmd_alloc(mm, pud, addr);
2705 if (!pmd)
2706 return -ENOMEM;
2707 VM_BUG_ON(pmd_trans_huge(*pmd));
2708 do {
2709 next = pmd_addr_end(addr, end);
2710 err = remap_pte_range(mm, pmd, addr, next,
2711 pfn + (addr >> PAGE_SHIFT), prot);
2712 if (err)
2713 return err;
2714 } while (pmd++, addr = next, addr != end);
2715 return 0;
2716 }
2717
remap_pud_range(struct mm_struct * mm,p4d_t * p4d,unsigned long addr,unsigned long end,unsigned long pfn,pgprot_t prot)2718 static inline int remap_pud_range(struct mm_struct *mm, p4d_t *p4d,
2719 unsigned long addr, unsigned long end,
2720 unsigned long pfn, pgprot_t prot)
2721 {
2722 pud_t *pud;
2723 unsigned long next;
2724 int err;
2725
2726 pfn -= addr >> PAGE_SHIFT;
2727 pud = pud_alloc(mm, p4d, addr);
2728 if (!pud)
2729 return -ENOMEM;
2730 do {
2731 next = pud_addr_end(addr, end);
2732 err = remap_pmd_range(mm, pud, addr, next,
2733 pfn + (addr >> PAGE_SHIFT), prot);
2734 if (err)
2735 return err;
2736 } while (pud++, addr = next, addr != end);
2737 return 0;
2738 }
2739
remap_p4d_range(struct mm_struct * mm,pgd_t * pgd,unsigned long addr,unsigned long end,unsigned long pfn,pgprot_t prot)2740 static inline int remap_p4d_range(struct mm_struct *mm, pgd_t *pgd,
2741 unsigned long addr, unsigned long end,
2742 unsigned long pfn, pgprot_t prot)
2743 {
2744 p4d_t *p4d;
2745 unsigned long next;
2746 int err;
2747
2748 pfn -= addr >> PAGE_SHIFT;
2749 p4d = p4d_alloc(mm, pgd, addr);
2750 if (!p4d)
2751 return -ENOMEM;
2752 do {
2753 next = p4d_addr_end(addr, end);
2754 err = remap_pud_range(mm, p4d, addr, next,
2755 pfn + (addr >> PAGE_SHIFT), prot);
2756 if (err)
2757 return err;
2758 } while (p4d++, addr = next, addr != end);
2759 return 0;
2760 }
2761
remap_pfn_range_internal(struct vm_area_struct * vma,unsigned long addr,unsigned long pfn,unsigned long size,pgprot_t prot)2762 static int remap_pfn_range_internal(struct vm_area_struct *vma, unsigned long addr,
2763 unsigned long pfn, unsigned long size, pgprot_t prot)
2764 {
2765 pgd_t *pgd;
2766 unsigned long next;
2767 unsigned long end = addr + PAGE_ALIGN(size);
2768 struct mm_struct *mm = vma->vm_mm;
2769 int err;
2770
2771 if (WARN_ON_ONCE(!PAGE_ALIGNED(addr)))
2772 return -EINVAL;
2773
2774 /*
2775 * Physically remapped pages are special. Tell the
2776 * rest of the world about it:
2777 * VM_IO tells people not to look at these pages
2778 * (accesses can have side effects).
2779 * VM_PFNMAP tells the core MM that the base pages are just
2780 * raw PFN mappings, and do not have a "struct page" associated
2781 * with them.
2782 * VM_DONTEXPAND
2783 * Disable vma merging and expanding with mremap().
2784 * VM_DONTDUMP
2785 * Omit vma from core dump, even when VM_IO turned off.
2786 *
2787 * There's a horrible special case to handle copy-on-write
2788 * behaviour that some programs depend on. We mark the "original"
2789 * un-COW'ed pages by matching them up with "vma->vm_pgoff".
2790 * See vm_normal_page() for details.
2791 */
2792 if (is_cow_mapping(vma->vm_flags)) {
2793 if (addr != vma->vm_start || end != vma->vm_end)
2794 return -EINVAL;
2795 vma->vm_pgoff = pfn;
2796 }
2797
2798 vm_flags_set(vma, VM_IO | VM_PFNMAP | VM_DONTEXPAND | VM_DONTDUMP);
2799
2800 BUG_ON(addr >= end);
2801 pfn -= addr >> PAGE_SHIFT;
2802 pgd = pgd_offset(mm, addr);
2803 flush_cache_range(vma, addr, end);
2804 do {
2805 next = pgd_addr_end(addr, end);
2806 err = remap_p4d_range(mm, pgd, addr, next,
2807 pfn + (addr >> PAGE_SHIFT), prot);
2808 if (err)
2809 return err;
2810 } while (pgd++, addr = next, addr != end);
2811
2812 return 0;
2813 }
2814
2815 /*
2816 * Variant of remap_pfn_range that does not call track_pfn_remap. The caller
2817 * must have pre-validated the caching bits of the pgprot_t.
2818 */
remap_pfn_range_notrack(struct vm_area_struct * vma,unsigned long addr,unsigned long pfn,unsigned long size,pgprot_t prot)2819 int remap_pfn_range_notrack(struct vm_area_struct *vma, unsigned long addr,
2820 unsigned long pfn, unsigned long size, pgprot_t prot)
2821 {
2822 int error = remap_pfn_range_internal(vma, addr, pfn, size, prot);
2823
2824 if (!error)
2825 return 0;
2826
2827 /*
2828 * A partial pfn range mapping is dangerous: it does not
2829 * maintain page reference counts, and callers may free
2830 * pages due to the error. So zap it early.
2831 */
2832 zap_page_range_single(vma, addr, size, NULL);
2833 return error;
2834 }
2835
2836 /**
2837 * remap_pfn_range - remap kernel memory to userspace
2838 * @vma: user vma to map to
2839 * @addr: target page aligned user address to start at
2840 * @pfn: page frame number of kernel physical memory address
2841 * @size: size of mapping area
2842 * @prot: page protection flags for this mapping
2843 *
2844 * Note: this is only safe if the mm semaphore is held when called.
2845 *
2846 * Return: %0 on success, negative error code otherwise.
2847 */
remap_pfn_range(struct vm_area_struct * vma,unsigned long addr,unsigned long pfn,unsigned long size,pgprot_t prot)2848 int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
2849 unsigned long pfn, unsigned long size, pgprot_t prot)
2850 {
2851 int err;
2852
2853 err = track_pfn_remap(vma, &prot, pfn, addr, PAGE_ALIGN(size));
2854 if (err)
2855 return -EINVAL;
2856
2857 err = remap_pfn_range_notrack(vma, addr, pfn, size, prot);
2858 if (err)
2859 untrack_pfn(vma, pfn, PAGE_ALIGN(size), true);
2860 return err;
2861 }
2862 EXPORT_SYMBOL(remap_pfn_range);
2863
2864 /**
2865 * vm_iomap_memory - remap memory to userspace
2866 * @vma: user vma to map to
2867 * @start: start of the physical memory to be mapped
2868 * @len: size of area
2869 *
2870 * This is a simplified io_remap_pfn_range() for common driver use. The
2871 * driver just needs to give us the physical memory range to be mapped,
2872 * we'll figure out the rest from the vma information.
2873 *
2874 * NOTE! Some drivers might want to tweak vma->vm_page_prot first to get
2875 * whatever write-combining details or similar.
2876 *
2877 * Return: %0 on success, negative error code otherwise.
2878 */
vm_iomap_memory(struct vm_area_struct * vma,phys_addr_t start,unsigned long len)2879 int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
2880 {
2881 unsigned long vm_len, pfn, pages;
2882
2883 /* Check that the physical memory area passed in looks valid */
2884 if (start + len < start)
2885 return -EINVAL;
2886 /*
2887 * You *really* shouldn't map things that aren't page-aligned,
2888 * but we've historically allowed it because IO memory might
2889 * just have smaller alignment.
2890 */
2891 len += start & ~PAGE_MASK;
2892 pfn = start >> PAGE_SHIFT;
2893 pages = (len + ~PAGE_MASK) >> PAGE_SHIFT;
2894 if (pfn + pages < pfn)
2895 return -EINVAL;
2896
2897 /* We start the mapping 'vm_pgoff' pages into the area */
2898 if (vma->vm_pgoff > pages)
2899 return -EINVAL;
2900 pfn += vma->vm_pgoff;
2901 pages -= vma->vm_pgoff;
2902
2903 /* Can we fit all of the mapping? */
2904 vm_len = vma->vm_end - vma->vm_start;
2905 if (vm_len >> PAGE_SHIFT > pages)
2906 return -EINVAL;
2907
2908 /* Ok, let it rip */
2909 return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
2910 }
2911 EXPORT_SYMBOL(vm_iomap_memory);
2912
apply_to_pte_range(struct mm_struct * mm,pmd_t * pmd,unsigned long addr,unsigned long end,pte_fn_t fn,void * data,bool create,pgtbl_mod_mask * mask)2913 static int apply_to_pte_range(struct mm_struct *mm, pmd_t *pmd,
2914 unsigned long addr, unsigned long end,
2915 pte_fn_t fn, void *data, bool create,
2916 pgtbl_mod_mask *mask)
2917 {
2918 pte_t *pte, *mapped_pte;
2919 int err = 0;
2920 spinlock_t *ptl;
2921
2922 if (create) {
2923 mapped_pte = pte = (mm == &init_mm) ?
2924 pte_alloc_kernel_track(pmd, addr, mask) :
2925 pte_alloc_map_lock(mm, pmd, addr, &ptl);
2926 if (!pte)
2927 return -ENOMEM;
2928 } else {
2929 mapped_pte = pte = (mm == &init_mm) ?
2930 pte_offset_kernel(pmd, addr) :
2931 pte_offset_map_lock(mm, pmd, addr, &ptl);
2932 if (!pte)
2933 return -EINVAL;
2934 }
2935
2936 arch_enter_lazy_mmu_mode();
2937
2938 if (fn) {
2939 do {
2940 if (create || !pte_none(ptep_get(pte))) {
2941 err = fn(pte++, addr, data);
2942 if (err)
2943 break;
2944 }
2945 } while (addr += PAGE_SIZE, addr != end);
2946 }
2947 *mask |= PGTBL_PTE_MODIFIED;
2948
2949 arch_leave_lazy_mmu_mode();
2950
2951 if (mm != &init_mm)
2952 pte_unmap_unlock(mapped_pte, ptl);
2953 return err;
2954 }
2955
apply_to_pmd_range(struct mm_struct * mm,pud_t * pud,unsigned long addr,unsigned long end,pte_fn_t fn,void * data,bool create,pgtbl_mod_mask * mask)2956 static int apply_to_pmd_range(struct mm_struct *mm, pud_t *pud,
2957 unsigned long addr, unsigned long end,
2958 pte_fn_t fn, void *data, bool create,
2959 pgtbl_mod_mask *mask)
2960 {
2961 pmd_t *pmd;
2962 unsigned long next;
2963 int err = 0;
2964
2965 BUG_ON(pud_leaf(*pud));
2966
2967 if (create) {
2968 pmd = pmd_alloc_track(mm, pud, addr, mask);
2969 if (!pmd)
2970 return -ENOMEM;
2971 } else {
2972 pmd = pmd_offset(pud, addr);
2973 }
2974 do {
2975 next = pmd_addr_end(addr, end);
2976 if (pmd_none(*pmd) && !create)
2977 continue;
2978 if (WARN_ON_ONCE(pmd_leaf(*pmd)))
2979 return -EINVAL;
2980 if (!pmd_none(*pmd) && WARN_ON_ONCE(pmd_bad(*pmd))) {
2981 if (!create)
2982 continue;
2983 pmd_clear_bad(pmd);
2984 }
2985 err = apply_to_pte_range(mm, pmd, addr, next,
2986 fn, data, create, mask);
2987 if (err)
2988 break;
2989 } while (pmd++, addr = next, addr != end);
2990
2991 return err;
2992 }
2993
apply_to_pud_range(struct mm_struct * mm,p4d_t * p4d,unsigned long addr,unsigned long end,pte_fn_t fn,void * data,bool create,pgtbl_mod_mask * mask)2994 static int apply_to_pud_range(struct mm_struct *mm, p4d_t *p4d,
2995 unsigned long addr, unsigned long end,
2996 pte_fn_t fn, void *data, bool create,
2997 pgtbl_mod_mask *mask)
2998 {
2999 pud_t *pud;
3000 unsigned long next;
3001 int err = 0;
3002
3003 if (create) {
3004 pud = pud_alloc_track(mm, p4d, addr, mask);
3005 if (!pud)
3006 return -ENOMEM;
3007 } else {
3008 pud = pud_offset(p4d, addr);
3009 }
3010 do {
3011 next = pud_addr_end(addr, end);
3012 if (pud_none(*pud) && !create)
3013 continue;
3014 if (WARN_ON_ONCE(pud_leaf(*pud)))
3015 return -EINVAL;
3016 if (!pud_none(*pud) && WARN_ON_ONCE(pud_bad(*pud))) {
3017 if (!create)
3018 continue;
3019 pud_clear_bad(pud);
3020 }
3021 err = apply_to_pmd_range(mm, pud, addr, next,
3022 fn, data, create, mask);
3023 if (err)
3024 break;
3025 } while (pud++, addr = next, addr != end);
3026
3027 return err;
3028 }
3029
apply_to_p4d_range(struct mm_struct * mm,pgd_t * pgd,unsigned long addr,unsigned long end,pte_fn_t fn,void * data,bool create,pgtbl_mod_mask * mask)3030 static int apply_to_p4d_range(struct mm_struct *mm, pgd_t *pgd,
3031 unsigned long addr, unsigned long end,
3032 pte_fn_t fn, void *data, bool create,
3033 pgtbl_mod_mask *mask)
3034 {
3035 p4d_t *p4d;
3036 unsigned long next;
3037 int err = 0;
3038
3039 if (create) {
3040 p4d = p4d_alloc_track(mm, pgd, addr, mask);
3041 if (!p4d)
3042 return -ENOMEM;
3043 } else {
3044 p4d = p4d_offset(pgd, addr);
3045 }
3046 do {
3047 next = p4d_addr_end(addr, end);
3048 if (p4d_none(*p4d) && !create)
3049 continue;
3050 if (WARN_ON_ONCE(p4d_leaf(*p4d)))
3051 return -EINVAL;
3052 if (!p4d_none(*p4d) && WARN_ON_ONCE(p4d_bad(*p4d))) {
3053 if (!create)
3054 continue;
3055 p4d_clear_bad(p4d);
3056 }
3057 err = apply_to_pud_range(mm, p4d, addr, next,
3058 fn, data, create, mask);
3059 if (err)
3060 break;
3061 } while (p4d++, addr = next, addr != end);
3062
3063 return err;
3064 }
3065
__apply_to_page_range(struct mm_struct * mm,unsigned long addr,unsigned long size,pte_fn_t fn,void * data,bool create)3066 static int __apply_to_page_range(struct mm_struct *mm, unsigned long addr,
3067 unsigned long size, pte_fn_t fn,
3068 void *data, bool create)
3069 {
3070 pgd_t *pgd;
3071 unsigned long start = addr, next;
3072 unsigned long end = addr + size;
3073 pgtbl_mod_mask mask = 0;
3074 int err = 0;
3075
3076 if (WARN_ON(addr >= end))
3077 return -EINVAL;
3078
3079 pgd = pgd_offset(mm, addr);
3080 do {
3081 next = pgd_addr_end(addr, end);
3082 if (pgd_none(*pgd) && !create)
3083 continue;
3084 if (WARN_ON_ONCE(pgd_leaf(*pgd))) {
3085 err = -EINVAL;
3086 break;
3087 }
3088 if (!pgd_none(*pgd) && WARN_ON_ONCE(pgd_bad(*pgd))) {
3089 if (!create)
3090 continue;
3091 pgd_clear_bad(pgd);
3092 }
3093 err = apply_to_p4d_range(mm, pgd, addr, next,
3094 fn, data, create, &mask);
3095 if (err)
3096 break;
3097 } while (pgd++, addr = next, addr != end);
3098
3099 if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
3100 arch_sync_kernel_mappings(start, start + size);
3101
3102 return err;
3103 }
3104
3105 /*
3106 * Scan a region of virtual memory, filling in page tables as necessary
3107 * and calling a provided function on each leaf page table.
3108 */
apply_to_page_range(struct mm_struct * mm,unsigned long addr,unsigned long size,pte_fn_t fn,void * data)3109 int apply_to_page_range(struct mm_struct *mm, unsigned long addr,
3110 unsigned long size, pte_fn_t fn, void *data)
3111 {
3112 return __apply_to_page_range(mm, addr, size, fn, data, true);
3113 }
3114 EXPORT_SYMBOL_GPL(apply_to_page_range);
3115
3116 /*
3117 * Scan a region of virtual memory, calling a provided function on
3118 * each leaf page table where it exists.
3119 *
3120 * Unlike apply_to_page_range, this does _not_ fill in page tables
3121 * where they are absent.
3122 */
apply_to_existing_page_range(struct mm_struct * mm,unsigned long addr,unsigned long size,pte_fn_t fn,void * data)3123 int apply_to_existing_page_range(struct mm_struct *mm, unsigned long addr,
3124 unsigned long size, pte_fn_t fn, void *data)
3125 {
3126 return __apply_to_page_range(mm, addr, size, fn, data, false);
3127 }
3128
3129 /*
3130 * handle_pte_fault chooses page fault handler according to an entry which was
3131 * read non-atomically. Before making any commitment, on those architectures
3132 * or configurations (e.g. i386 with PAE) which might give a mix of unmatched
3133 * parts, do_swap_page must check under lock before unmapping the pte and
3134 * proceeding (but do_wp_page is only called after already making such a check;
3135 * and do_anonymous_page can safely check later on).
3136 */
pte_unmap_same(struct vm_fault * vmf)3137 static inline int pte_unmap_same(struct vm_fault *vmf)
3138 {
3139 int same = 1;
3140 #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPTION)
3141 if (sizeof(pte_t) > sizeof(unsigned long)) {
3142 spin_lock(vmf->ptl);
3143 same = pte_same(ptep_get(vmf->pte), vmf->orig_pte);
3144 spin_unlock(vmf->ptl);
3145 }
3146 #endif
3147 pte_unmap(vmf->pte);
3148 vmf->pte = NULL;
3149 return same;
3150 }
3151
3152 /*
3153 * Return:
3154 * 0: copied succeeded
3155 * -EHWPOISON: copy failed due to hwpoison in source page
3156 * -EAGAIN: copied failed (some other reason)
3157 */
__wp_page_copy_user(struct page * dst,struct page * src,struct vm_fault * vmf)3158 static inline int __wp_page_copy_user(struct page *dst, struct page *src,
3159 struct vm_fault *vmf)
3160 {
3161 int ret;
3162 void *kaddr;
3163 void __user *uaddr;
3164 struct vm_area_struct *vma = vmf->vma;
3165 struct mm_struct *mm = vma->vm_mm;
3166 unsigned long addr = vmf->address;
3167
3168 if (likely(src)) {
3169 if (copy_mc_user_highpage(dst, src, addr, vma))
3170 return -EHWPOISON;
3171 return 0;
3172 }
3173
3174 /*
3175 * If the source page was a PFN mapping, we don't have
3176 * a "struct page" for it. We do a best-effort copy by
3177 * just copying from the original user address. If that
3178 * fails, we just zero-fill it. Live with it.
3179 */
3180 kaddr = kmap_local_page(dst);
3181 pagefault_disable();
3182 uaddr = (void __user *)(addr & PAGE_MASK);
3183
3184 /*
3185 * On architectures with software "accessed" bits, we would
3186 * take a double page fault, so mark it accessed here.
3187 */
3188 vmf->pte = NULL;
3189 if (!arch_has_hw_pte_young() && !pte_young(vmf->orig_pte)) {
3190 pte_t entry;
3191
3192 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
3193 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
3194 /*
3195 * Other thread has already handled the fault
3196 * and update local tlb only
3197 */
3198 if (vmf->pte)
3199 update_mmu_tlb(vma, addr, vmf->pte);
3200 ret = -EAGAIN;
3201 goto pte_unlock;
3202 }
3203
3204 entry = pte_mkyoung(vmf->orig_pte);
3205 if (ptep_set_access_flags(vma, addr, vmf->pte, entry, 0))
3206 update_mmu_cache_range(vmf, vma, addr, vmf->pte, 1);
3207 }
3208
3209 /*
3210 * This really shouldn't fail, because the page is there
3211 * in the page tables. But it might just be unreadable,
3212 * in which case we just give up and fill the result with
3213 * zeroes.
3214 */
3215 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
3216 if (vmf->pte)
3217 goto warn;
3218
3219 /* Re-validate under PTL if the page is still mapped */
3220 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, addr, &vmf->ptl);
3221 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
3222 /* The PTE changed under us, update local tlb */
3223 if (vmf->pte)
3224 update_mmu_tlb(vma, addr, vmf->pte);
3225 ret = -EAGAIN;
3226 goto pte_unlock;
3227 }
3228
3229 /*
3230 * The same page can be mapped back since last copy attempt.
3231 * Try to copy again under PTL.
3232 */
3233 if (__copy_from_user_inatomic(kaddr, uaddr, PAGE_SIZE)) {
3234 /*
3235 * Give a warn in case there can be some obscure
3236 * use-case
3237 */
3238 warn:
3239 WARN_ON_ONCE(1);
3240 clear_page(kaddr);
3241 }
3242 }
3243
3244 ret = 0;
3245
3246 pte_unlock:
3247 if (vmf->pte)
3248 pte_unmap_unlock(vmf->pte, vmf->ptl);
3249 pagefault_enable();
3250 kunmap_local(kaddr);
3251 flush_dcache_page(dst);
3252
3253 return ret;
3254 }
3255
__get_fault_gfp_mask(struct vm_area_struct * vma)3256 static gfp_t __get_fault_gfp_mask(struct vm_area_struct *vma)
3257 {
3258 struct file *vm_file = vma->vm_file;
3259
3260 if (vm_file)
3261 return mapping_gfp_mask(vm_file->f_mapping) | __GFP_FS | __GFP_IO;
3262
3263 /*
3264 * Special mappings (e.g. VDSO) do not have any file so fake
3265 * a default GFP_KERNEL for them.
3266 */
3267 return GFP_KERNEL;
3268 }
3269
3270 /*
3271 * Notify the address space that the page is about to become writable so that
3272 * it can prohibit this or wait for the page to get into an appropriate state.
3273 *
3274 * We do this without the lock held, so that it can sleep if it needs to.
3275 */
do_page_mkwrite(struct vm_fault * vmf,struct folio * folio)3276 static vm_fault_t do_page_mkwrite(struct vm_fault *vmf, struct folio *folio)
3277 {
3278 vm_fault_t ret;
3279 unsigned int old_flags = vmf->flags;
3280
3281 vmf->flags = FAULT_FLAG_WRITE|FAULT_FLAG_MKWRITE;
3282
3283 if (vmf->vma->vm_file &&
3284 IS_SWAPFILE(vmf->vma->vm_file->f_mapping->host))
3285 return VM_FAULT_SIGBUS;
3286
3287 ret = vmf->vma->vm_ops->page_mkwrite(vmf);
3288 /* Restore original flags so that caller is not surprised */
3289 vmf->flags = old_flags;
3290 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))
3291 return ret;
3292 if (unlikely(!(ret & VM_FAULT_LOCKED))) {
3293 folio_lock(folio);
3294 if (!folio->mapping) {
3295 folio_unlock(folio);
3296 return 0; /* retry */
3297 }
3298 ret |= VM_FAULT_LOCKED;
3299 } else
3300 VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
3301 return ret;
3302 }
3303
3304 /*
3305 * Handle dirtying of a page in shared file mapping on a write fault.
3306 *
3307 * The function expects the page to be locked and unlocks it.
3308 */
fault_dirty_shared_page(struct vm_fault * vmf)3309 static vm_fault_t fault_dirty_shared_page(struct vm_fault *vmf)
3310 {
3311 struct vm_area_struct *vma = vmf->vma;
3312 struct address_space *mapping;
3313 struct folio *folio = page_folio(vmf->page);
3314 bool dirtied;
3315 bool page_mkwrite = vma->vm_ops && vma->vm_ops->page_mkwrite;
3316
3317 dirtied = folio_mark_dirty(folio);
3318 VM_BUG_ON_FOLIO(folio_test_anon(folio), folio);
3319 /*
3320 * Take a local copy of the address_space - folio.mapping may be zeroed
3321 * by truncate after folio_unlock(). The address_space itself remains
3322 * pinned by vma->vm_file's reference. We rely on folio_unlock()'s
3323 * release semantics to prevent the compiler from undoing this copying.
3324 */
3325 mapping = folio_raw_mapping(folio);
3326 folio_unlock(folio);
3327
3328 if (!page_mkwrite)
3329 file_update_time(vma->vm_file);
3330
3331 /*
3332 * Throttle page dirtying rate down to writeback speed.
3333 *
3334 * mapping may be NULL here because some device drivers do not
3335 * set page.mapping but still dirty their pages
3336 *
3337 * Drop the mmap_lock before waiting on IO, if we can. The file
3338 * is pinning the mapping, as per above.
3339 */
3340 if ((dirtied || page_mkwrite) && mapping) {
3341 struct file *fpin;
3342
3343 fpin = maybe_unlock_mmap_for_io(vmf, NULL);
3344 balance_dirty_pages_ratelimited(mapping);
3345 if (fpin) {
3346 fput(fpin);
3347 return VM_FAULT_COMPLETED;
3348 }
3349 }
3350
3351 return 0;
3352 }
3353
3354 /*
3355 * Handle write page faults for pages that can be reused in the current vma
3356 *
3357 * This can happen either due to the mapping being with the VM_SHARED flag,
3358 * or due to us being the last reference standing to the page. In either
3359 * case, all we need to do here is to mark the page as writable and update
3360 * any related book-keeping.
3361 */
wp_page_reuse(struct vm_fault * vmf,struct folio * folio)3362 static inline void wp_page_reuse(struct vm_fault *vmf, struct folio *folio)
3363 __releases(vmf->ptl)
3364 {
3365 struct vm_area_struct *vma = vmf->vma;
3366 pte_t entry;
3367
3368 VM_BUG_ON(!(vmf->flags & FAULT_FLAG_WRITE));
3369 VM_WARN_ON(is_zero_pfn(pte_pfn(vmf->orig_pte)));
3370
3371 if (folio) {
3372 VM_BUG_ON(folio_test_anon(folio) &&
3373 !PageAnonExclusive(vmf->page));
3374 /*
3375 * Clear the folio's cpupid information as the existing
3376 * information potentially belongs to a now completely
3377 * unrelated process.
3378 */
3379 folio_xchg_last_cpupid(folio, (1 << LAST_CPUPID_SHIFT) - 1);
3380 }
3381
3382 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3383 entry = pte_mkyoung(vmf->orig_pte);
3384 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3385 if (ptep_set_access_flags(vma, vmf->address, vmf->pte, entry, 1))
3386 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1);
3387 pte_unmap_unlock(vmf->pte, vmf->ptl);
3388 count_vm_event(PGREUSE);
3389 }
3390
3391 /*
3392 * We could add a bitflag somewhere, but for now, we know that all
3393 * vm_ops that have a ->map_pages have been audited and don't need
3394 * the mmap_lock to be held.
3395 */
vmf_can_call_fault(const struct vm_fault * vmf)3396 static inline vm_fault_t vmf_can_call_fault(const struct vm_fault *vmf)
3397 {
3398 struct vm_area_struct *vma = vmf->vma;
3399
3400 if (vma->vm_ops->map_pages || !(vmf->flags & FAULT_FLAG_VMA_LOCK))
3401 return 0;
3402 vma_end_read(vma);
3403 return VM_FAULT_RETRY;
3404 }
3405
3406 /**
3407 * __vmf_anon_prepare - Prepare to handle an anonymous fault.
3408 * @vmf: The vm_fault descriptor passed from the fault handler.
3409 *
3410 * When preparing to insert an anonymous page into a VMA from a
3411 * fault handler, call this function rather than anon_vma_prepare().
3412 * If this vma does not already have an associated anon_vma and we are
3413 * only protected by the per-VMA lock, the caller must retry with the
3414 * mmap_lock held. __anon_vma_prepare() will look at adjacent VMAs to
3415 * determine if this VMA can share its anon_vma, and that's not safe to
3416 * do with only the per-VMA lock held for this VMA.
3417 *
3418 * Return: 0 if fault handling can proceed. Any other value should be
3419 * returned to the caller.
3420 */
__vmf_anon_prepare(struct vm_fault * vmf)3421 vm_fault_t __vmf_anon_prepare(struct vm_fault *vmf)
3422 {
3423 struct vm_area_struct *vma = vmf->vma;
3424 vm_fault_t ret = 0;
3425
3426 if (likely(vma->anon_vma))
3427 return 0;
3428 if (vmf->flags & FAULT_FLAG_VMA_LOCK) {
3429 if (!mmap_read_trylock(vma->vm_mm))
3430 return VM_FAULT_RETRY;
3431 }
3432 if (__anon_vma_prepare(vma))
3433 ret = VM_FAULT_OOM;
3434 if (vmf->flags & FAULT_FLAG_VMA_LOCK)
3435 mmap_read_unlock(vma->vm_mm);
3436 return ret;
3437 }
3438
3439 /*
3440 * Handle the case of a page which we actually need to copy to a new page,
3441 * either due to COW or unsharing.
3442 *
3443 * Called with mmap_lock locked and the old page referenced, but
3444 * without the ptl held.
3445 *
3446 * High level logic flow:
3447 *
3448 * - Allocate a page, copy the content of the old page to the new one.
3449 * - Handle book keeping and accounting - cgroups, mmu-notifiers, etc.
3450 * - Take the PTL. If the pte changed, bail out and release the allocated page
3451 * - If the pte is still the way we remember it, update the page table and all
3452 * relevant references. This includes dropping the reference the page-table
3453 * held to the old page, as well as updating the rmap.
3454 * - In any case, unlock the PTL and drop the reference we took to the old page.
3455 */
wp_page_copy(struct vm_fault * vmf)3456 static vm_fault_t wp_page_copy(struct vm_fault *vmf)
3457 {
3458 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3459 struct vm_area_struct *vma = vmf->vma;
3460 struct mm_struct *mm = vma->vm_mm;
3461 struct folio *old_folio = NULL;
3462 struct folio *new_folio = NULL;
3463 pte_t entry;
3464 int page_copied = 0;
3465 struct mmu_notifier_range range;
3466 vm_fault_t ret;
3467 bool pfn_is_zero;
3468
3469 delayacct_wpcopy_start();
3470
3471 if (vmf->page)
3472 old_folio = page_folio(vmf->page);
3473 ret = vmf_anon_prepare(vmf);
3474 if (unlikely(ret))
3475 goto out;
3476
3477 pfn_is_zero = is_zero_pfn(pte_pfn(vmf->orig_pte));
3478 new_folio = folio_prealloc(mm, vma, vmf->address, pfn_is_zero);
3479 if (!new_folio)
3480 goto oom;
3481
3482 if (!pfn_is_zero) {
3483 int err;
3484
3485 err = __wp_page_copy_user(&new_folio->page, vmf->page, vmf);
3486 if (err) {
3487 /*
3488 * COW failed, if the fault was solved by other,
3489 * it's fine. If not, userspace would re-fault on
3490 * the same address and we will handle the fault
3491 * from the second attempt.
3492 * The -EHWPOISON case will not be retried.
3493 */
3494 folio_put(new_folio);
3495 if (old_folio)
3496 folio_put(old_folio);
3497
3498 delayacct_wpcopy_end();
3499 return err == -EHWPOISON ? VM_FAULT_HWPOISON : 0;
3500 }
3501 kmsan_copy_page_meta(&new_folio->page, vmf->page);
3502 }
3503
3504 __folio_mark_uptodate(new_folio);
3505
3506 mmu_notifier_range_init(&range, MMU_NOTIFY_CLEAR, 0, mm,
3507 vmf->address & PAGE_MASK,
3508 (vmf->address & PAGE_MASK) + PAGE_SIZE);
3509 mmu_notifier_invalidate_range_start(&range);
3510
3511 /*
3512 * Re-check the pte - we dropped the lock
3513 */
3514 vmf->pte = pte_offset_map_lock(mm, vmf->pmd, vmf->address, &vmf->ptl);
3515 if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
3516 if (old_folio) {
3517 if (!folio_test_anon(old_folio)) {
3518 dec_mm_counter(mm, mm_counter_file(old_folio));
3519 inc_mm_counter(mm, MM_ANONPAGES);
3520 }
3521 } else {
3522 ksm_might_unmap_zero_page(mm, vmf->orig_pte);
3523 inc_mm_counter(mm, MM_ANONPAGES);
3524 }
3525 flush_cache_page(vma, vmf->address, pte_pfn(vmf->orig_pte));
3526 entry = mk_pte(&new_folio->page, vma->vm_page_prot);
3527 entry = pte_sw_mkyoung(entry);
3528 if (unlikely(unshare)) {
3529 if (pte_soft_dirty(vmf->orig_pte))
3530 entry = pte_mksoft_dirty(entry);
3531 if (pte_uffd_wp(vmf->orig_pte))
3532 entry = pte_mkuffd_wp(entry);
3533 } else {
3534 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
3535 }
3536
3537 /*
3538 * Clear the pte entry and flush it first, before updating the
3539 * pte with the new entry, to keep TLBs on different CPUs in
3540 * sync. This code used to set the new PTE then flush TLBs, but
3541 * that left a window where the new PTE could be loaded into
3542 * some TLBs while the old PTE remains in others.
3543 */
3544 ptep_clear_flush(vma, vmf->address, vmf->pte);
3545 folio_add_new_anon_rmap(new_folio, vma, vmf->address, RMAP_EXCLUSIVE);
3546 folio_add_lru_vma(new_folio, vma);
3547 BUG_ON(unshare && pte_write(entry));
3548 set_pte_at(mm, vmf->address, vmf->pte, entry);
3549 update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1);
3550 if (old_folio) {
3551 /*
3552 * Only after switching the pte to the new page may
3553 * we remove the mapcount here. Otherwise another
3554 * process may come and find the rmap count decremented
3555 * before the pte is switched to the new page, and
3556 * "reuse" the old page writing into it while our pte
3557 * here still points into it and can be read by other
3558 * threads.
3559 *
3560 * The critical issue is to order this
3561 * folio_remove_rmap_pte() with the ptp_clear_flush
3562 * above. Those stores are ordered by (if nothing else,)
3563 * the barrier present in the atomic_add_negative
3564 * in folio_remove_rmap_pte();
3565 *
3566 * Then the TLB flush in ptep_clear_flush ensures that
3567 * no process can access the old page before the
3568 * decremented mapcount is visible. And the old page
3569 * cannot be reused until after the decremented
3570 * mapcount is visible. So transitively, TLBs to
3571 * old page will be flushed before it can be reused.
3572 */
3573 folio_remove_rmap_pte(old_folio, vmf->page, vma);
3574 }
3575
3576 /* Free the old page.. */
3577 new_folio = old_folio;
3578 page_copied = 1;
3579 pte_unmap_unlock(vmf->pte, vmf->ptl);
3580 } else if (vmf->pte) {
3581 update_mmu_tlb(vma, vmf->address, vmf->pte);
3582 pte_unmap_unlock(vmf->pte, vmf->ptl);
3583 }
3584
3585 mmu_notifier_invalidate_range_end(&range);
3586
3587 if (new_folio)
3588 folio_put(new_folio);
3589 if (old_folio) {
3590 if (page_copied)
3591 free_swap_cache(old_folio);
3592 folio_put(old_folio);
3593 }
3594
3595 delayacct_wpcopy_end();
3596 return 0;
3597 oom:
3598 ret = VM_FAULT_OOM;
3599 out:
3600 if (old_folio)
3601 folio_put(old_folio);
3602
3603 delayacct_wpcopy_end();
3604 return ret;
3605 }
3606
3607 /**
3608 * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
3609 * writeable once the page is prepared
3610 *
3611 * @vmf: structure describing the fault
3612 * @folio: the folio of vmf->page
3613 *
3614 * This function handles all that is needed to finish a write page fault in a
3615 * shared mapping due to PTE being read-only once the mapped page is prepared.
3616 * It handles locking of PTE and modifying it.
3617 *
3618 * The function expects the page to be locked or other protection against
3619 * concurrent faults / writeback (such as DAX radix tree locks).
3620 *
3621 * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before
3622 * we acquired PTE lock.
3623 */
finish_mkwrite_fault(struct vm_fault * vmf,struct folio * folio)3624 static vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf, struct folio *folio)
3625 {
3626 WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
3627 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
3628 &vmf->ptl);
3629 if (!vmf->pte)
3630 return VM_FAULT_NOPAGE;
3631 /*
3632 * We might have raced with another page fault while we released the
3633 * pte_offset_map_lock.
3634 */
3635 if (!pte_same(ptep_get(vmf->pte), vmf->orig_pte)) {
3636 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
3637 pte_unmap_unlock(vmf->pte, vmf->ptl);
3638 return VM_FAULT_NOPAGE;
3639 }
3640 wp_page_reuse(vmf, folio);
3641 return 0;
3642 }
3643
3644 /*
3645 * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
3646 * mapping
3647 */
wp_pfn_shared(struct vm_fault * vmf)3648 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
3649 {
3650 struct vm_area_struct *vma = vmf->vma;
3651
3652 if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
3653 vm_fault_t ret;
3654
3655 pte_unmap_unlock(vmf->pte, vmf->ptl);
3656 ret = vmf_can_call_fault(vmf);
3657 if (ret)
3658 return ret;
3659
3660 vmf->flags |= FAULT_FLAG_MKWRITE;
3661 ret = vma->vm_ops->pfn_mkwrite(vmf);
3662 if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
3663 return ret;
3664 return finish_mkwrite_fault(vmf, NULL);
3665 }
3666 wp_page_reuse(vmf, NULL);
3667 return 0;
3668 }
3669
wp_page_shared(struct vm_fault * vmf,struct folio * folio)3670 static vm_fault_t wp_page_shared(struct vm_fault *vmf, struct folio *folio)
3671 __releases(vmf->ptl)
3672 {
3673 struct vm_area_struct *vma = vmf->vma;
3674 vm_fault_t ret = 0;
3675
3676 folio_get(folio);
3677
3678 if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
3679 vm_fault_t tmp;
3680
3681 pte_unmap_unlock(vmf->pte, vmf->ptl);
3682 tmp = vmf_can_call_fault(vmf);
3683 if (tmp) {
3684 folio_put(folio);
3685 return tmp;
3686 }
3687
3688 tmp = do_page_mkwrite(vmf, folio);
3689 if (unlikely(!tmp || (tmp &
3690 (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
3691 folio_put(folio);
3692 return tmp;
3693 }
3694 tmp = finish_mkwrite_fault(vmf, folio);
3695 if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
3696 folio_unlock(folio);
3697 folio_put(folio);
3698 return tmp;
3699 }
3700 } else {
3701 wp_page_reuse(vmf, folio);
3702 folio_lock(folio);
3703 }
3704 ret |= fault_dirty_shared_page(vmf);
3705 folio_put(folio);
3706
3707 return ret;
3708 }
3709
3710 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
__wp_can_reuse_large_anon_folio(struct folio * folio,struct vm_area_struct * vma)3711 static bool __wp_can_reuse_large_anon_folio(struct folio *folio,
3712 struct vm_area_struct *vma)
3713 {
3714 bool exclusive = false;
3715
3716 /* Let's just free up a large folio if only a single page is mapped. */
3717 if (folio_large_mapcount(folio) <= 1)
3718 return false;
3719
3720 /*
3721 * The assumption for anonymous folios is that each page can only get
3722 * mapped once into each MM. The only exception are KSM folios, which
3723 * are always small.
3724 *
3725 * Each taken mapcount must be paired with exactly one taken reference,
3726 * whereby the refcount must be incremented before the mapcount when
3727 * mapping a page, and the refcount must be decremented after the
3728 * mapcount when unmapping a page.
3729 *
3730 * If all folio references are from mappings, and all mappings are in
3731 * the page tables of this MM, then this folio is exclusive to this MM.
3732 */
3733 if (folio_test_large_maybe_mapped_shared(folio))
3734 return false;
3735
3736 VM_WARN_ON_ONCE(folio_test_ksm(folio));
3737 VM_WARN_ON_ONCE(folio_mapcount(folio) > folio_nr_pages(folio));
3738 VM_WARN_ON_ONCE(folio_entire_mapcount(folio));
3739
3740 if (unlikely(folio_test_swapcache(folio))) {
3741 /*
3742 * Note: freeing up the swapcache will fail if some PTEs are
3743 * still swap entries.
3744 */
3745 if (!folio_trylock(folio))
3746 return false;
3747 folio_free_swap(folio);
3748 folio_unlock(folio);
3749 }
3750
3751 if (folio_large_mapcount(folio) != folio_ref_count(folio))
3752 return false;
3753
3754 /* Stabilize the mapcount vs. refcount and recheck. */
3755 folio_lock_large_mapcount(folio);
3756 VM_WARN_ON_ONCE(folio_large_mapcount(folio) < folio_ref_count(folio));
3757
3758 if (folio_test_large_maybe_mapped_shared(folio))
3759 goto unlock;
3760 if (folio_large_mapcount(folio) != folio_ref_count(folio))
3761 goto unlock;
3762
3763 VM_WARN_ON_ONCE(folio_mm_id(folio, 0) != vma->vm_mm->mm_id &&
3764 folio_mm_id(folio, 1) != vma->vm_mm->mm_id);
3765
3766 /*
3767 * Do we need the folio lock? Likely not. If there would have been
3768 * references from page migration/swapout, we would have detected
3769 * an additional folio reference and never ended up here.
3770 */
3771 exclusive = true;
3772 unlock:
3773 folio_unlock_large_mapcount(folio);
3774 return exclusive;
3775 }
3776 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
__wp_can_reuse_large_anon_folio(struct folio * folio,struct vm_area_struct * vma)3777 static bool __wp_can_reuse_large_anon_folio(struct folio *folio,
3778 struct vm_area_struct *vma)
3779 {
3780 BUILD_BUG();
3781 }
3782 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
3783
wp_can_reuse_anon_folio(struct folio * folio,struct vm_area_struct * vma)3784 static bool wp_can_reuse_anon_folio(struct folio *folio,
3785 struct vm_area_struct *vma)
3786 {
3787 if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && folio_test_large(folio))
3788 return __wp_can_reuse_large_anon_folio(folio, vma);
3789
3790 /*
3791 * We have to verify under folio lock: these early checks are
3792 * just an optimization to avoid locking the folio and freeing
3793 * the swapcache if there is little hope that we can reuse.
3794 *
3795 * KSM doesn't necessarily raise the folio refcount.
3796 */
3797 if (folio_test_ksm(folio) || folio_ref_count(folio) > 3)
3798 return false;
3799 if (!folio_test_lru(folio))
3800 /*
3801 * We cannot easily detect+handle references from
3802 * remote LRU caches or references to LRU folios.
3803 */
3804 lru_add_drain();
3805 if (folio_ref_count(folio) > 1 + folio_test_swapcache(folio))
3806 return false;
3807 if (!folio_trylock(folio))
3808 return false;
3809 if (folio_test_swapcache(folio))
3810 folio_free_swap(folio);
3811 if (folio_test_ksm(folio) || folio_ref_count(folio) != 1) {
3812 folio_unlock(folio);
3813 return false;
3814 }
3815 /*
3816 * Ok, we've got the only folio reference from our mapping
3817 * and the folio is locked, it's dark out, and we're wearing
3818 * sunglasses. Hit it.
3819 */
3820 folio_move_anon_rmap(folio, vma);
3821 folio_unlock(folio);
3822 return true;
3823 }
3824
3825 /*
3826 * This routine handles present pages, when
3827 * * users try to write to a shared page (FAULT_FLAG_WRITE)
3828 * * GUP wants to take a R/O pin on a possibly shared anonymous page
3829 * (FAULT_FLAG_UNSHARE)
3830 *
3831 * It is done by copying the page to a new address and decrementing the
3832 * shared-page counter for the old page.
3833 *
3834 * Note that this routine assumes that the protection checks have been
3835 * done by the caller (the low-level page fault routine in most cases).
3836 * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've
3837 * done any necessary COW.
3838 *
3839 * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even
3840 * though the page will change only once the write actually happens. This
3841 * avoids a few races, and potentially makes it more efficient.
3842 *
3843 * We enter with non-exclusive mmap_lock (to exclude vma changes,
3844 * but allow concurrent faults), with pte both mapped and locked.
3845 * We return with mmap_lock still held, but pte unmapped and unlocked.
3846 */
do_wp_page(struct vm_fault * vmf)3847 static vm_fault_t do_wp_page(struct vm_fault *vmf)
3848 __releases(vmf->ptl)
3849 {
3850 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
3851 struct vm_area_struct *vma = vmf->vma;
3852 struct folio *folio = NULL;
3853 pte_t pte;
3854
3855 if (likely(!unshare)) {
3856 if (userfaultfd_pte_wp(vma, ptep_get(vmf->pte))) {
3857 if (!userfaultfd_wp_async(vma)) {
3858 pte_unmap_unlock(vmf->pte, vmf->ptl);
3859 return handle_userfault(vmf, VM_UFFD_WP);
3860 }
3861
3862 /*
3863 * Nothing needed (cache flush, TLB invalidations,
3864 * etc.) because we're only removing the uffd-wp bit,
3865 * which is completely invisible to the user.
3866 */
3867 pte = pte_clear_uffd_wp(ptep_get(vmf->pte));
3868
3869 set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
3870 /*
3871 * Update this to be prepared for following up CoW
3872 * handling
3873 */
3874 vmf->orig_pte = pte;
3875 }
3876
3877 /*
3878 * Userfaultfd write-protect can defer flushes. Ensure the TLB
3879 * is flushed in this case before copying.
3880 */
3881 if (unlikely(userfaultfd_wp(vmf->vma) &&
3882 mm_tlb_flush_pending(vmf->vma->vm_mm)))
3883 flush_tlb_page(vmf->vma, vmf->address);
3884 }
3885
3886 vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
3887
3888 if (vmf->page)
3889 folio = page_folio(vmf->page);
3890
3891 /*
3892 * Shared mapping: we are guaranteed to have VM_WRITE and
3893 * FAULT_FLAG_WRITE set at this point.
3894 */
3895 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
3896 /*
3897 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
3898 * VM_PFNMAP VMA. FS DAX also wants ops->pfn_mkwrite called.
3899 *
3900 * We should not cow pages in a shared writeable mapping.
3901 * Just mark the pages writable and/or call ops->pfn_mkwrite.
3902 */
3903 if (!vmf->page || is_fsdax_page(vmf->page)) {
3904 vmf->page = NULL;
3905 return wp_pfn_shared(vmf);
3906 }
3907 return wp_page_shared(vmf, folio);
3908 }
3909
3910 /*
3911 * Private mapping: create an exclusive anonymous page copy if reuse
3912 * is impossible. We might miss VM_WRITE for FOLL_FORCE handling.
3913 *
3914 * If we encounter a page that is marked exclusive, we must reuse
3915 * the page without further checks.
3916 */
3917 if (folio && folio_test_anon(folio) &&
3918 (PageAnonExclusive(vmf->page) || wp_can_reuse_anon_folio(folio, vma))) {
3919 if (!PageAnonExclusive(vmf->page))
3920 SetPageAnonExclusive(vmf->page);
3921 if (unlikely(unshare)) {
3922 pte_unmap_unlock(vmf->pte, vmf->ptl);
3923 return 0;
3924 }
3925 wp_page_reuse(vmf, folio);
3926 return 0;
3927 }
3928 /*
3929 * Ok, we need to copy. Oh, well..
3930 */
3931 if (folio)
3932 folio_get(folio);
3933
3934 pte_unmap_unlock(vmf->pte, vmf->ptl);
3935 #ifdef CONFIG_KSM
3936 if (folio && folio_test_ksm(folio))
3937 count_vm_event(COW_KSM);
3938 #endif
3939 return wp_page_copy(vmf);
3940 }
3941
unmap_mapping_range_vma(struct vm_area_struct * vma,unsigned long start_addr,unsigned long end_addr,struct zap_details * details)3942 static void unmap_mapping_range_vma(struct vm_area_struct *vma,
3943 unsigned long start_addr, unsigned long end_addr,
3944 struct zap_details *details)
3945 {
3946 zap_page_range_single(vma, start_addr, end_addr - start_addr, details);
3947 }
3948
unmap_mapping_range_tree(struct rb_root_cached * root,pgoff_t first_index,pgoff_t last_index,struct zap_details * details)3949 static inline void unmap_mapping_range_tree(struct rb_root_cached *root,
3950 pgoff_t first_index,
3951 pgoff_t last_index,
3952 struct zap_details *details)
3953 {
3954 struct vm_area_struct *vma;
3955 pgoff_t vba, vea, zba, zea;
3956
3957 vma_interval_tree_foreach(vma, root, first_index, last_index) {
3958 vba = vma->vm_pgoff;
3959 vea = vba + vma_pages(vma) - 1;
3960 zba = max(first_index, vba);
3961 zea = min(last_index, vea);
3962
3963 unmap_mapping_range_vma(vma,
3964 ((zba - vba) << PAGE_SHIFT) + vma->vm_start,
3965 ((zea - vba + 1) << PAGE_SHIFT) + vma->vm_start,
3966 details);
3967 }
3968 }
3969
3970 /**
3971 * unmap_mapping_folio() - Unmap single folio from processes.
3972 * @folio: The locked folio to be unmapped.
3973 *
3974 * Unmap this folio from any userspace process which still has it mmaped.
3975 * Typically, for efficiency, the range of nearby pages has already been
3976 * unmapped by unmap_mapping_pages() or unmap_mapping_range(). But once
3977 * truncation or invalidation holds the lock on a folio, it may find that
3978 * the page has been remapped again: and then uses unmap_mapping_folio()
3979 * to unmap it finally.
3980 */
unmap_mapping_folio(struct folio * folio)3981 void unmap_mapping_folio(struct folio *folio)
3982 {
3983 struct address_space *mapping = folio->mapping;
3984 struct zap_details details = { };
3985 pgoff_t first_index;
3986 pgoff_t last_index;
3987
3988 VM_BUG_ON(!folio_test_locked(folio));
3989
3990 first_index = folio->index;
3991 last_index = folio_next_index(folio) - 1;
3992
3993 details.even_cows = false;
3994 details.single_folio = folio;
3995 details.zap_flags = ZAP_FLAG_DROP_MARKER;
3996
3997 i_mmap_lock_read(mapping);
3998 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
3999 unmap_mapping_range_tree(&mapping->i_mmap, first_index,
4000 last_index, &details);
4001 i_mmap_unlock_read(mapping);
4002 }
4003
4004 /**
4005 * unmap_mapping_pages() - Unmap pages from processes.
4006 * @mapping: The address space containing pages to be unmapped.
4007 * @start: Index of first page to be unmapped.
4008 * @nr: Number of pages to be unmapped. 0 to unmap to end of file.
4009 * @even_cows: Whether to unmap even private COWed pages.
4010 *
4011 * Unmap the pages in this address space from any userspace process which
4012 * has them mmaped. Generally, you want to remove COWed pages as well when
4013 * a file is being truncated, but not when invalidating pages from the page
4014 * cache.
4015 */
unmap_mapping_pages(struct address_space * mapping,pgoff_t start,pgoff_t nr,bool even_cows)4016 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
4017 pgoff_t nr, bool even_cows)
4018 {
4019 struct zap_details details = { };
4020 pgoff_t first_index = start;
4021 pgoff_t last_index = start + nr - 1;
4022
4023 details.even_cows = even_cows;
4024 if (last_index < first_index)
4025 last_index = ULONG_MAX;
4026
4027 i_mmap_lock_read(mapping);
4028 if (unlikely(!RB_EMPTY_ROOT(&mapping->i_mmap.rb_root)))
4029 unmap_mapping_range_tree(&mapping->i_mmap, first_index,
4030 last_index, &details);
4031 i_mmap_unlock_read(mapping);
4032 }
4033 EXPORT_SYMBOL_GPL(unmap_mapping_pages);
4034
4035 /**
4036 * unmap_mapping_range - unmap the portion of all mmaps in the specified
4037 * address_space corresponding to the specified byte range in the underlying
4038 * file.
4039 *
4040 * @mapping: the address space containing mmaps to be unmapped.
4041 * @holebegin: byte in first page to unmap, relative to the start of
4042 * the underlying file. This will be rounded down to a PAGE_SIZE
4043 * boundary. Note that this is different from truncate_pagecache(), which
4044 * must keep the partial page. In contrast, we must get rid of
4045 * partial pages.
4046 * @holelen: size of prospective hole in bytes. This will be rounded
4047 * up to a PAGE_SIZE boundary. A holelen of zero truncates to the
4048 * end of the file.
4049 * @even_cows: 1 when truncating a file, unmap even private COWed pages;
4050 * but 0 when invalidating pagecache, don't throw away private data.
4051 */
unmap_mapping_range(struct address_space * mapping,loff_t const holebegin,loff_t const holelen,int even_cows)4052 void unmap_mapping_range(struct address_space *mapping,
4053 loff_t const holebegin, loff_t const holelen, int even_cows)
4054 {
4055 pgoff_t hba = (pgoff_t)(holebegin) >> PAGE_SHIFT;
4056 pgoff_t hlen = ((pgoff_t)(holelen) + PAGE_SIZE - 1) >> PAGE_SHIFT;
4057
4058 /* Check for overflow. */
4059 if (sizeof(holelen) > sizeof(hlen)) {
4060 long long holeend =
4061 (holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
4062 if (holeend & ~(long long)ULONG_MAX)
4063 hlen = ULONG_MAX - hba + 1;
4064 }
4065
4066 unmap_mapping_pages(mapping, hba, hlen, even_cows);
4067 }
4068 EXPORT_SYMBOL(unmap_mapping_range);
4069
4070 /*
4071 * Restore a potential device exclusive pte to a working pte entry
4072 */
remove_device_exclusive_entry(struct vm_fault * vmf)4073 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf)
4074 {
4075 struct folio *folio = page_folio(vmf->page);
4076 struct vm_area_struct *vma = vmf->vma;
4077 struct mmu_notifier_range range;
4078 vm_fault_t ret;
4079
4080 /*
4081 * We need a reference to lock the folio because we don't hold
4082 * the PTL so a racing thread can remove the device-exclusive
4083 * entry and unmap it. If the folio is free the entry must
4084 * have been removed already. If it happens to have already
4085 * been re-allocated after being freed all we do is lock and
4086 * unlock it.
4087 */
4088 if (!folio_try_get(folio))
4089 return 0;
4090
4091 ret = folio_lock_or_retry(folio, vmf);
4092 if (ret) {
4093 folio_put(folio);
4094 return ret;
4095 }
4096 mmu_notifier_range_init_owner(&range, MMU_NOTIFY_CLEAR, 0,
4097 vma->vm_mm, vmf->address & PAGE_MASK,
4098 (vmf->address & PAGE_MASK) + PAGE_SIZE, NULL);
4099 mmu_notifier_invalidate_range_start(&range);
4100
4101 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
4102 &vmf->ptl);
4103 if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
4104 restore_exclusive_pte(vma, folio, vmf->page, vmf->address,
4105 vmf->pte, vmf->orig_pte);
4106
4107 if (vmf->pte)
4108 pte_unmap_unlock(vmf->pte, vmf->ptl);
4109 folio_unlock(folio);
4110 folio_put(folio);
4111
4112 mmu_notifier_invalidate_range_end(&range);
4113 return 0;
4114 }
4115
should_try_to_free_swap(struct folio * folio,struct vm_area_struct * vma,unsigned int fault_flags)4116 static inline bool should_try_to_free_swap(struct folio *folio,
4117 struct vm_area_struct *vma,
4118 unsigned int fault_flags)
4119 {
4120 if (!folio_test_swapcache(folio))
4121 return false;
4122 if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
4123 folio_test_mlocked(folio))
4124 return true;
4125 /*
4126 * If we want to map a page that's in the swapcache writable, we
4127 * have to detect via the refcount if we're really the exclusive
4128 * user. Try freeing the swapcache to get rid of the swapcache
4129 * reference only in case it's likely that we'll be the exlusive user.
4130 */
4131 return (fault_flags & FAULT_FLAG_WRITE) && !folio_test_ksm(folio) &&
4132 folio_ref_count(folio) == (1 + folio_nr_pages(folio));
4133 }
4134
pte_marker_clear(struct vm_fault * vmf)4135 static vm_fault_t pte_marker_clear(struct vm_fault *vmf)
4136 {
4137 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
4138 vmf->address, &vmf->ptl);
4139 if (!vmf->pte)
4140 return 0;
4141 /*
4142 * Be careful so that we will only recover a special uffd-wp pte into a
4143 * none pte. Otherwise it means the pte could have changed, so retry.
4144 *
4145 * This should also cover the case where e.g. the pte changed
4146 * quickly from a PTE_MARKER_UFFD_WP into PTE_MARKER_POISONED.
4147 * So is_pte_marker() check is not enough to safely drop the pte.
4148 */
4149 if (pte_same(vmf->orig_pte, ptep_get(vmf->pte)))
4150 pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte);
4151 pte_unmap_unlock(vmf->pte, vmf->ptl);
4152 return 0;
4153 }
4154
do_pte_missing(struct vm_fault * vmf)4155 static vm_fault_t do_pte_missing(struct vm_fault *vmf)
4156 {
4157 if (vma_is_anonymous(vmf->vma))
4158 return do_anonymous_page(vmf);
4159 else
4160 return do_fault(vmf);
4161 }
4162
4163 /*
4164 * This is actually a page-missing access, but with uffd-wp special pte
4165 * installed. It means this pte was wr-protected before being unmapped.
4166 */
pte_marker_handle_uffd_wp(struct vm_fault * vmf)4167 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf)
4168 {
4169 /*
4170 * Just in case there're leftover special ptes even after the region
4171 * got unregistered - we can simply clear them.
4172 */
4173 if (unlikely(!userfaultfd_wp(vmf->vma)))
4174 return pte_marker_clear(vmf);
4175
4176 return do_pte_missing(vmf);
4177 }
4178
handle_pte_marker(struct vm_fault * vmf)4179 static vm_fault_t handle_pte_marker(struct vm_fault *vmf)
4180 {
4181 swp_entry_t entry = pte_to_swp_entry(vmf->orig_pte);
4182 unsigned long marker = pte_marker_get(entry);
4183
4184 /*
4185 * PTE markers should never be empty. If anything weird happened,
4186 * the best thing to do is to kill the process along with its mm.
4187 */
4188 if (WARN_ON_ONCE(!marker))
4189 return VM_FAULT_SIGBUS;
4190
4191 /* Higher priority than uffd-wp when data corrupted */
4192 if (marker & PTE_MARKER_POISONED)
4193 return VM_FAULT_HWPOISON;
4194
4195 /* Hitting a guard page is always a fatal condition. */
4196 if (marker & PTE_MARKER_GUARD)
4197 return VM_FAULT_SIGSEGV;
4198
4199 if (pte_marker_entry_uffd_wp(entry))
4200 return pte_marker_handle_uffd_wp(vmf);
4201
4202 /* This is an unknown pte marker */
4203 return VM_FAULT_SIGBUS;
4204 }
4205
__alloc_swap_folio(struct vm_fault * vmf)4206 static struct folio *__alloc_swap_folio(struct vm_fault *vmf)
4207 {
4208 struct vm_area_struct *vma = vmf->vma;
4209 struct folio *folio;
4210 swp_entry_t entry;
4211
4212 folio = vma_alloc_folio(GFP_HIGHUSER_MOVABLE, 0, vma, vmf->address);
4213 if (!folio)
4214 return NULL;
4215
4216 entry = pte_to_swp_entry(vmf->orig_pte);
4217 if (mem_cgroup_swapin_charge_folio(folio, vma->vm_mm,
4218 GFP_KERNEL, entry)) {
4219 folio_put(folio);
4220 return NULL;
4221 }
4222
4223 return folio;
4224 }
4225
4226 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
non_swapcache_batch(swp_entry_t entry,int max_nr)4227 static inline int non_swapcache_batch(swp_entry_t entry, int max_nr)
4228 {
4229 struct swap_info_struct *si = swp_swap_info(entry);
4230 pgoff_t offset = swp_offset(entry);
4231 int i;
4232
4233 /*
4234 * While allocating a large folio and doing swap_read_folio, which is
4235 * the case the being faulted pte doesn't have swapcache. We need to
4236 * ensure all PTEs have no cache as well, otherwise, we might go to
4237 * swap devices while the content is in swapcache.
4238 */
4239 for (i = 0; i < max_nr; i++) {
4240 if ((si->swap_map[offset + i] & SWAP_HAS_CACHE))
4241 return i;
4242 }
4243
4244 return i;
4245 }
4246
4247 /*
4248 * Check if the PTEs within a range are contiguous swap entries
4249 * and have consistent swapcache, zeromap.
4250 */
can_swapin_thp(struct vm_fault * vmf,pte_t * ptep,int nr_pages)4251 static bool can_swapin_thp(struct vm_fault *vmf, pte_t *ptep, int nr_pages)
4252 {
4253 unsigned long addr;
4254 swp_entry_t entry;
4255 int idx;
4256 pte_t pte;
4257
4258 addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE);
4259 idx = (vmf->address - addr) / PAGE_SIZE;
4260 pte = ptep_get(ptep);
4261
4262 if (!pte_same(pte, pte_move_swp_offset(vmf->orig_pte, -idx)))
4263 return false;
4264 entry = pte_to_swp_entry(pte);
4265 if (swap_pte_batch(ptep, nr_pages, pte) != nr_pages)
4266 return false;
4267
4268 /*
4269 * swap_read_folio() can't handle the case a large folio is hybridly
4270 * from different backends. And they are likely corner cases. Similar
4271 * things might be added once zswap support large folios.
4272 */
4273 if (unlikely(swap_zeromap_batch(entry, nr_pages, NULL) != nr_pages))
4274 return false;
4275 if (unlikely(non_swapcache_batch(entry, nr_pages) != nr_pages))
4276 return false;
4277
4278 return true;
4279 }
4280
thp_swap_suitable_orders(pgoff_t swp_offset,unsigned long addr,unsigned long orders)4281 static inline unsigned long thp_swap_suitable_orders(pgoff_t swp_offset,
4282 unsigned long addr,
4283 unsigned long orders)
4284 {
4285 int order, nr;
4286
4287 order = highest_order(orders);
4288
4289 /*
4290 * To swap in a THP with nr pages, we require that its first swap_offset
4291 * is aligned with that number, as it was when the THP was swapped out.
4292 * This helps filter out most invalid entries.
4293 */
4294 while (orders) {
4295 nr = 1 << order;
4296 if ((addr >> PAGE_SHIFT) % nr == swp_offset % nr)
4297 break;
4298 order = next_order(&orders, order);
4299 }
4300
4301 return orders;
4302 }
4303
alloc_swap_folio(struct vm_fault * vmf)4304 static struct folio *alloc_swap_folio(struct vm_fault *vmf)
4305 {
4306 struct vm_area_struct *vma = vmf->vma;
4307 unsigned long orders;
4308 struct folio *folio;
4309 unsigned long addr;
4310 swp_entry_t entry;
4311 spinlock_t *ptl;
4312 pte_t *pte;
4313 gfp_t gfp;
4314 int order;
4315
4316 /*
4317 * If uffd is active for the vma we need per-page fault fidelity to
4318 * maintain the uffd semantics.
4319 */
4320 if (unlikely(userfaultfd_armed(vma)))
4321 goto fallback;
4322
4323 /*
4324 * A large swapped out folio could be partially or fully in zswap. We
4325 * lack handling for such cases, so fallback to swapping in order-0
4326 * folio.
4327 */
4328 if (!zswap_never_enabled())
4329 goto fallback;
4330
4331 entry = pte_to_swp_entry(vmf->orig_pte);
4332 /*
4333 * Get a list of all the (large) orders below PMD_ORDER that are enabled
4334 * and suitable for swapping THP.
4335 */
4336 orders = thp_vma_allowable_orders(vma, vma->vm_flags,
4337 TVA_IN_PF | TVA_ENFORCE_SYSFS, BIT(PMD_ORDER) - 1);
4338 orders = thp_vma_suitable_orders(vma, vmf->address, orders);
4339 orders = thp_swap_suitable_orders(swp_offset(entry),
4340 vmf->address, orders);
4341
4342 if (!orders)
4343 goto fallback;
4344
4345 pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
4346 vmf->address & PMD_MASK, &ptl);
4347 if (unlikely(!pte))
4348 goto fallback;
4349
4350 /*
4351 * For do_swap_page, find the highest order where the aligned range is
4352 * completely swap entries with contiguous swap offsets.
4353 */
4354 order = highest_order(orders);
4355 while (orders) {
4356 addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4357 if (can_swapin_thp(vmf, pte + pte_index(addr), 1 << order))
4358 break;
4359 order = next_order(&orders, order);
4360 }
4361
4362 pte_unmap_unlock(pte, ptl);
4363
4364 /* Try allocating the highest of the remaining orders. */
4365 gfp = vma_thp_gfp_mask(vma);
4366 while (orders) {
4367 addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4368 folio = vma_alloc_folio(gfp, order, vma, addr);
4369 if (folio) {
4370 if (!mem_cgroup_swapin_charge_folio(folio, vma->vm_mm,
4371 gfp, entry))
4372 return folio;
4373 count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK_CHARGE);
4374 folio_put(folio);
4375 }
4376 count_mthp_stat(order, MTHP_STAT_SWPIN_FALLBACK);
4377 order = next_order(&orders, order);
4378 }
4379
4380 fallback:
4381 return __alloc_swap_folio(vmf);
4382 }
4383 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
alloc_swap_folio(struct vm_fault * vmf)4384 static struct folio *alloc_swap_folio(struct vm_fault *vmf)
4385 {
4386 return __alloc_swap_folio(vmf);
4387 }
4388 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4389
4390 static DECLARE_WAIT_QUEUE_HEAD(swapcache_wq);
4391
4392 /*
4393 * We enter with non-exclusive mmap_lock (to exclude vma changes,
4394 * but allow concurrent faults), and pte mapped but not yet locked.
4395 * We return with pte unmapped and unlocked.
4396 *
4397 * We return with the mmap_lock locked or unlocked in the same cases
4398 * as does filemap_fault().
4399 */
do_swap_page(struct vm_fault * vmf)4400 vm_fault_t do_swap_page(struct vm_fault *vmf)
4401 {
4402 struct vm_area_struct *vma = vmf->vma;
4403 struct folio *swapcache, *folio = NULL;
4404 DECLARE_WAITQUEUE(wait, current);
4405 struct page *page;
4406 struct swap_info_struct *si = NULL;
4407 rmap_t rmap_flags = RMAP_NONE;
4408 bool need_clear_cache = false;
4409 bool exclusive = false;
4410 swp_entry_t entry;
4411 pte_t pte;
4412 vm_fault_t ret = 0;
4413 void *shadow = NULL;
4414 int nr_pages;
4415 unsigned long page_idx;
4416 unsigned long address;
4417 pte_t *ptep;
4418
4419 if (!pte_unmap_same(vmf))
4420 goto out;
4421
4422 entry = pte_to_swp_entry(vmf->orig_pte);
4423 if (unlikely(non_swap_entry(entry))) {
4424 if (is_migration_entry(entry)) {
4425 migration_entry_wait(vma->vm_mm, vmf->pmd,
4426 vmf->address);
4427 } else if (is_device_exclusive_entry(entry)) {
4428 vmf->page = pfn_swap_entry_to_page(entry);
4429 ret = remove_device_exclusive_entry(vmf);
4430 } else if (is_device_private_entry(entry)) {
4431 if (vmf->flags & FAULT_FLAG_VMA_LOCK) {
4432 /*
4433 * migrate_to_ram is not yet ready to operate
4434 * under VMA lock.
4435 */
4436 vma_end_read(vma);
4437 ret = VM_FAULT_RETRY;
4438 goto out;
4439 }
4440
4441 vmf->page = pfn_swap_entry_to_page(entry);
4442 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4443 vmf->address, &vmf->ptl);
4444 if (unlikely(!vmf->pte ||
4445 !pte_same(ptep_get(vmf->pte),
4446 vmf->orig_pte)))
4447 goto unlock;
4448
4449 /*
4450 * Get a page reference while we know the page can't be
4451 * freed.
4452 */
4453 if (trylock_page(vmf->page)) {
4454 struct dev_pagemap *pgmap;
4455
4456 get_page(vmf->page);
4457 pte_unmap_unlock(vmf->pte, vmf->ptl);
4458 pgmap = page_pgmap(vmf->page);
4459 ret = pgmap->ops->migrate_to_ram(vmf);
4460 unlock_page(vmf->page);
4461 put_page(vmf->page);
4462 } else {
4463 pte_unmap_unlock(vmf->pte, vmf->ptl);
4464 }
4465 } else if (is_hwpoison_entry(entry)) {
4466 ret = VM_FAULT_HWPOISON;
4467 } else if (is_pte_marker_entry(entry)) {
4468 ret = handle_pte_marker(vmf);
4469 } else {
4470 print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
4471 ret = VM_FAULT_SIGBUS;
4472 }
4473 goto out;
4474 }
4475
4476 /* Prevent swapoff from happening to us. */
4477 si = get_swap_device(entry);
4478 if (unlikely(!si))
4479 goto out;
4480
4481 folio = swap_cache_get_folio(entry, vma, vmf->address);
4482 if (folio)
4483 page = folio_file_page(folio, swp_offset(entry));
4484 swapcache = folio;
4485
4486 if (!folio) {
4487 if (data_race(si->flags & SWP_SYNCHRONOUS_IO) &&
4488 __swap_count(entry) == 1) {
4489 /* skip swapcache */
4490 folio = alloc_swap_folio(vmf);
4491 if (folio) {
4492 __folio_set_locked(folio);
4493 __folio_set_swapbacked(folio);
4494
4495 nr_pages = folio_nr_pages(folio);
4496 if (folio_test_large(folio))
4497 entry.val = ALIGN_DOWN(entry.val, nr_pages);
4498 /*
4499 * Prevent parallel swapin from proceeding with
4500 * the cache flag. Otherwise, another thread
4501 * may finish swapin first, free the entry, and
4502 * swapout reusing the same entry. It's
4503 * undetectable as pte_same() returns true due
4504 * to entry reuse.
4505 */
4506 if (swapcache_prepare(entry, nr_pages)) {
4507 /*
4508 * Relax a bit to prevent rapid
4509 * repeated page faults.
4510 */
4511 add_wait_queue(&swapcache_wq, &wait);
4512 schedule_timeout_uninterruptible(1);
4513 remove_wait_queue(&swapcache_wq, &wait);
4514 goto out_page;
4515 }
4516 need_clear_cache = true;
4517
4518 memcg1_swapin(entry, nr_pages);
4519
4520 shadow = get_shadow_from_swap_cache(entry);
4521 if (shadow)
4522 workingset_refault(folio, shadow);
4523
4524 folio_add_lru(folio);
4525
4526 /* To provide entry to swap_read_folio() */
4527 folio->swap = entry;
4528 swap_read_folio(folio, NULL);
4529 folio->private = NULL;
4530 }
4531 } else {
4532 folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE,
4533 vmf);
4534 swapcache = folio;
4535 }
4536
4537 if (!folio) {
4538 /*
4539 * Back out if somebody else faulted in this pte
4540 * while we released the pte lock.
4541 */
4542 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4543 vmf->address, &vmf->ptl);
4544 if (likely(vmf->pte &&
4545 pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
4546 ret = VM_FAULT_OOM;
4547 goto unlock;
4548 }
4549
4550 /* Had to read the page from swap area: Major fault */
4551 ret = VM_FAULT_MAJOR;
4552 count_vm_event(PGMAJFAULT);
4553 count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
4554 page = folio_file_page(folio, swp_offset(entry));
4555 } else if (PageHWPoison(page)) {
4556 /*
4557 * hwpoisoned dirty swapcache pages are kept for killing
4558 * owner processes (which may be unknown at hwpoison time)
4559 */
4560 ret = VM_FAULT_HWPOISON;
4561 goto out_release;
4562 }
4563
4564 ret |= folio_lock_or_retry(folio, vmf);
4565 if (ret & VM_FAULT_RETRY)
4566 goto out_release;
4567
4568 if (swapcache) {
4569 /*
4570 * Make sure folio_free_swap() or swapoff did not release the
4571 * swapcache from under us. The page pin, and pte_same test
4572 * below, are not enough to exclude that. Even if it is still
4573 * swapcache, we need to check that the page's swap has not
4574 * changed.
4575 */
4576 if (unlikely(!folio_test_swapcache(folio) ||
4577 page_swap_entry(page).val != entry.val))
4578 goto out_page;
4579
4580 /*
4581 * KSM sometimes has to copy on read faults, for example, if
4582 * page->index of !PageKSM() pages would be nonlinear inside the
4583 * anon VMA -- PageKSM() is lost on actual swapout.
4584 */
4585 folio = ksm_might_need_to_copy(folio, vma, vmf->address);
4586 if (unlikely(!folio)) {
4587 ret = VM_FAULT_OOM;
4588 folio = swapcache;
4589 goto out_page;
4590 } else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {
4591 ret = VM_FAULT_HWPOISON;
4592 folio = swapcache;
4593 goto out_page;
4594 }
4595 if (folio != swapcache)
4596 page = folio_page(folio, 0);
4597
4598 /*
4599 * If we want to map a page that's in the swapcache writable, we
4600 * have to detect via the refcount if we're really the exclusive
4601 * owner. Try removing the extra reference from the local LRU
4602 * caches if required.
4603 */
4604 if ((vmf->flags & FAULT_FLAG_WRITE) && folio == swapcache &&
4605 !folio_test_ksm(folio) && !folio_test_lru(folio))
4606 lru_add_drain();
4607 }
4608
4609 folio_throttle_swaprate(folio, GFP_KERNEL);
4610
4611 /*
4612 * Back out if somebody else already faulted in this pte.
4613 */
4614 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
4615 &vmf->ptl);
4616 if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
4617 goto out_nomap;
4618
4619 if (unlikely(!folio_test_uptodate(folio))) {
4620 ret = VM_FAULT_SIGBUS;
4621 goto out_nomap;
4622 }
4623
4624 /* allocated large folios for SWP_SYNCHRONOUS_IO */
4625 if (folio_test_large(folio) && !folio_test_swapcache(folio)) {
4626 unsigned long nr = folio_nr_pages(folio);
4627 unsigned long folio_start = ALIGN_DOWN(vmf->address, nr * PAGE_SIZE);
4628 unsigned long idx = (vmf->address - folio_start) / PAGE_SIZE;
4629 pte_t *folio_ptep = vmf->pte - idx;
4630 pte_t folio_pte = ptep_get(folio_ptep);
4631
4632 if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) ||
4633 swap_pte_batch(folio_ptep, nr, folio_pte) != nr)
4634 goto out_nomap;
4635
4636 page_idx = idx;
4637 address = folio_start;
4638 ptep = folio_ptep;
4639 goto check_folio;
4640 }
4641
4642 nr_pages = 1;
4643 page_idx = 0;
4644 address = vmf->address;
4645 ptep = vmf->pte;
4646 if (folio_test_large(folio) && folio_test_swapcache(folio)) {
4647 int nr = folio_nr_pages(folio);
4648 unsigned long idx = folio_page_idx(folio, page);
4649 unsigned long folio_start = address - idx * PAGE_SIZE;
4650 unsigned long folio_end = folio_start + nr * PAGE_SIZE;
4651 pte_t *folio_ptep;
4652 pte_t folio_pte;
4653
4654 if (unlikely(folio_start < max(address & PMD_MASK, vma->vm_start)))
4655 goto check_folio;
4656 if (unlikely(folio_end > pmd_addr_end(address, vma->vm_end)))
4657 goto check_folio;
4658
4659 folio_ptep = vmf->pte - idx;
4660 folio_pte = ptep_get(folio_ptep);
4661 if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) ||
4662 swap_pte_batch(folio_ptep, nr, folio_pte) != nr)
4663 goto check_folio;
4664
4665 page_idx = idx;
4666 address = folio_start;
4667 ptep = folio_ptep;
4668 nr_pages = nr;
4669 entry = folio->swap;
4670 page = &folio->page;
4671 }
4672
4673 check_folio:
4674 /*
4675 * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte
4676 * must never point at an anonymous page in the swapcache that is
4677 * PG_anon_exclusive. Sanity check that this holds and especially, that
4678 * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity
4679 * check after taking the PT lock and making sure that nobody
4680 * concurrently faulted in this page and set PG_anon_exclusive.
4681 */
4682 BUG_ON(!folio_test_anon(folio) && folio_test_mappedtodisk(folio));
4683 BUG_ON(folio_test_anon(folio) && PageAnonExclusive(page));
4684
4685 /*
4686 * Check under PT lock (to protect against concurrent fork() sharing
4687 * the swap entry concurrently) for certainly exclusive pages.
4688 */
4689 if (!folio_test_ksm(folio)) {
4690 exclusive = pte_swp_exclusive(vmf->orig_pte);
4691 if (folio != swapcache) {
4692 /*
4693 * We have a fresh page that is not exposed to the
4694 * swapcache -> certainly exclusive.
4695 */
4696 exclusive = true;
4697 } else if (exclusive && folio_test_writeback(folio) &&
4698 data_race(si->flags & SWP_STABLE_WRITES)) {
4699 /*
4700 * This is tricky: not all swap backends support
4701 * concurrent page modifications while under writeback.
4702 *
4703 * So if we stumble over such a page in the swapcache
4704 * we must not set the page exclusive, otherwise we can
4705 * map it writable without further checks and modify it
4706 * while still under writeback.
4707 *
4708 * For these problematic swap backends, simply drop the
4709 * exclusive marker: this is perfectly fine as we start
4710 * writeback only if we fully unmapped the page and
4711 * there are no unexpected references on the page after
4712 * unmapping succeeded. After fully unmapped, no
4713 * further GUP references (FOLL_GET and FOLL_PIN) can
4714 * appear, so dropping the exclusive marker and mapping
4715 * it only R/O is fine.
4716 */
4717 exclusive = false;
4718 }
4719 }
4720
4721 /*
4722 * Some architectures may have to restore extra metadata to the page
4723 * when reading from swap. This metadata may be indexed by swap entry
4724 * so this must be called before swap_free().
4725 */
4726 arch_swap_restore(folio_swap(entry, folio), folio);
4727
4728 /*
4729 * Remove the swap entry and conditionally try to free up the swapcache.
4730 * We're already holding a reference on the page but haven't mapped it
4731 * yet.
4732 */
4733 swap_free_nr(entry, nr_pages);
4734 if (should_try_to_free_swap(folio, vma, vmf->flags))
4735 folio_free_swap(folio);
4736
4737 add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages);
4738 add_mm_counter(vma->vm_mm, MM_SWAPENTS, -nr_pages);
4739 pte = mk_pte(page, vma->vm_page_prot);
4740 if (pte_swp_soft_dirty(vmf->orig_pte))
4741 pte = pte_mksoft_dirty(pte);
4742 if (pte_swp_uffd_wp(vmf->orig_pte))
4743 pte = pte_mkuffd_wp(pte);
4744
4745 /*
4746 * Same logic as in do_wp_page(); however, optimize for pages that are
4747 * certainly not shared either because we just allocated them without
4748 * exposing them to the swapcache or because the swap entry indicates
4749 * exclusivity.
4750 */
4751 if (!folio_test_ksm(folio) &&
4752 (exclusive || folio_ref_count(folio) == 1)) {
4753 if ((vma->vm_flags & VM_WRITE) && !userfaultfd_pte_wp(vma, pte) &&
4754 !pte_needs_soft_dirty_wp(vma, pte)) {
4755 pte = pte_mkwrite(pte, vma);
4756 if (vmf->flags & FAULT_FLAG_WRITE) {
4757 pte = pte_mkdirty(pte);
4758 vmf->flags &= ~FAULT_FLAG_WRITE;
4759 }
4760 }
4761 rmap_flags |= RMAP_EXCLUSIVE;
4762 }
4763 folio_ref_add(folio, nr_pages - 1);
4764 flush_icache_pages(vma, page, nr_pages);
4765 vmf->orig_pte = pte_advance_pfn(pte, page_idx);
4766
4767 /* ksm created a completely new copy */
4768 if (unlikely(folio != swapcache && swapcache)) {
4769 folio_add_new_anon_rmap(folio, vma, address, RMAP_EXCLUSIVE);
4770 folio_add_lru_vma(folio, vma);
4771 } else if (!folio_test_anon(folio)) {
4772 /*
4773 * We currently only expect small !anon folios which are either
4774 * fully exclusive or fully shared, or new allocated large
4775 * folios which are fully exclusive. If we ever get large
4776 * folios within swapcache here, we have to be careful.
4777 */
4778 VM_WARN_ON_ONCE(folio_test_large(folio) && folio_test_swapcache(folio));
4779 VM_WARN_ON_FOLIO(!folio_test_locked(folio), folio);
4780 folio_add_new_anon_rmap(folio, vma, address, rmap_flags);
4781 } else {
4782 folio_add_anon_rmap_ptes(folio, page, nr_pages, vma, address,
4783 rmap_flags);
4784 }
4785
4786 VM_BUG_ON(!folio_test_anon(folio) ||
4787 (pte_write(pte) && !PageAnonExclusive(page)));
4788 set_ptes(vma->vm_mm, address, ptep, pte, nr_pages);
4789 arch_do_swap_page_nr(vma->vm_mm, vma, address,
4790 pte, pte, nr_pages);
4791
4792 folio_unlock(folio);
4793 if (folio != swapcache && swapcache) {
4794 /*
4795 * Hold the lock to avoid the swap entry to be reused
4796 * until we take the PT lock for the pte_same() check
4797 * (to avoid false positives from pte_same). For
4798 * further safety release the lock after the swap_free
4799 * so that the swap count won't change under a
4800 * parallel locked swapcache.
4801 */
4802 folio_unlock(swapcache);
4803 folio_put(swapcache);
4804 }
4805
4806 if (vmf->flags & FAULT_FLAG_WRITE) {
4807 ret |= do_wp_page(vmf);
4808 if (ret & VM_FAULT_ERROR)
4809 ret &= VM_FAULT_ERROR;
4810 goto out;
4811 }
4812
4813 /* No need to invalidate - it was non-present before */
4814 update_mmu_cache_range(vmf, vma, address, ptep, nr_pages);
4815 unlock:
4816 if (vmf->pte)
4817 pte_unmap_unlock(vmf->pte, vmf->ptl);
4818 out:
4819 /* Clear the swap cache pin for direct swapin after PTL unlock */
4820 if (need_clear_cache) {
4821 swapcache_clear(si, entry, nr_pages);
4822 if (waitqueue_active(&swapcache_wq))
4823 wake_up(&swapcache_wq);
4824 }
4825 if (si)
4826 put_swap_device(si);
4827 return ret;
4828 out_nomap:
4829 if (vmf->pte)
4830 pte_unmap_unlock(vmf->pte, vmf->ptl);
4831 out_page:
4832 folio_unlock(folio);
4833 out_release:
4834 folio_put(folio);
4835 if (folio != swapcache && swapcache) {
4836 folio_unlock(swapcache);
4837 folio_put(swapcache);
4838 }
4839 if (need_clear_cache) {
4840 swapcache_clear(si, entry, nr_pages);
4841 if (waitqueue_active(&swapcache_wq))
4842 wake_up(&swapcache_wq);
4843 }
4844 if (si)
4845 put_swap_device(si);
4846 return ret;
4847 }
4848
pte_range_none(pte_t * pte,int nr_pages)4849 static bool pte_range_none(pte_t *pte, int nr_pages)
4850 {
4851 int i;
4852
4853 for (i = 0; i < nr_pages; i++) {
4854 if (!pte_none(ptep_get_lockless(pte + i)))
4855 return false;
4856 }
4857
4858 return true;
4859 }
4860
alloc_anon_folio(struct vm_fault * vmf)4861 static struct folio *alloc_anon_folio(struct vm_fault *vmf)
4862 {
4863 struct vm_area_struct *vma = vmf->vma;
4864 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4865 unsigned long orders;
4866 struct folio *folio;
4867 unsigned long addr;
4868 pte_t *pte;
4869 gfp_t gfp;
4870 int order;
4871
4872 /*
4873 * If uffd is active for the vma we need per-page fault fidelity to
4874 * maintain the uffd semantics.
4875 */
4876 if (unlikely(userfaultfd_armed(vma)))
4877 goto fallback;
4878
4879 /*
4880 * Get a list of all the (large) orders below PMD_ORDER that are enabled
4881 * for this vma. Then filter out the orders that can't be allocated over
4882 * the faulting address and still be fully contained in the vma.
4883 */
4884 orders = thp_vma_allowable_orders(vma, vma->vm_flags,
4885 TVA_IN_PF | TVA_ENFORCE_SYSFS, BIT(PMD_ORDER) - 1);
4886 orders = thp_vma_suitable_orders(vma, vmf->address, orders);
4887
4888 if (!orders)
4889 goto fallback;
4890
4891 pte = pte_offset_map(vmf->pmd, vmf->address & PMD_MASK);
4892 if (!pte)
4893 return ERR_PTR(-EAGAIN);
4894
4895 /*
4896 * Find the highest order where the aligned range is completely
4897 * pte_none(). Note that all remaining orders will be completely
4898 * pte_none().
4899 */
4900 order = highest_order(orders);
4901 while (orders) {
4902 addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4903 if (pte_range_none(pte + pte_index(addr), 1 << order))
4904 break;
4905 order = next_order(&orders, order);
4906 }
4907
4908 pte_unmap(pte);
4909
4910 if (!orders)
4911 goto fallback;
4912
4913 /* Try allocating the highest of the remaining orders. */
4914 gfp = vma_thp_gfp_mask(vma);
4915 while (orders) {
4916 addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4917 folio = vma_alloc_folio(gfp, order, vma, addr);
4918 if (folio) {
4919 if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) {
4920 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
4921 folio_put(folio);
4922 goto next;
4923 }
4924 folio_throttle_swaprate(folio, gfp);
4925 /*
4926 * When a folio is not zeroed during allocation
4927 * (__GFP_ZERO not used) or user folios require special
4928 * handling, folio_zero_user() is used to make sure
4929 * that the page corresponding to the faulting address
4930 * will be hot in the cache after zeroing.
4931 */
4932 if (user_alloc_needs_zeroing())
4933 folio_zero_user(folio, vmf->address);
4934 return folio;
4935 }
4936 next:
4937 count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK);
4938 order = next_order(&orders, order);
4939 }
4940
4941 fallback:
4942 #endif
4943 return folio_prealloc(vma->vm_mm, vma, vmf->address, true);
4944 }
4945
4946 /*
4947 * We enter with non-exclusive mmap_lock (to exclude vma changes,
4948 * but allow concurrent faults), and pte mapped but not yet locked.
4949 * We return with mmap_lock still held, but pte unmapped and unlocked.
4950 */
do_anonymous_page(struct vm_fault * vmf)4951 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
4952 {
4953 struct vm_area_struct *vma = vmf->vma;
4954 unsigned long addr = vmf->address;
4955 struct folio *folio;
4956 vm_fault_t ret = 0;
4957 int nr_pages = 1;
4958 pte_t entry;
4959
4960 /* File mapping without ->vm_ops ? */
4961 if (vma->vm_flags & VM_SHARED)
4962 return VM_FAULT_SIGBUS;
4963
4964 /*
4965 * Use pte_alloc() instead of pte_alloc_map(), so that OOM can
4966 * be distinguished from a transient failure of pte_offset_map().
4967 */
4968 if (pte_alloc(vma->vm_mm, vmf->pmd))
4969 return VM_FAULT_OOM;
4970
4971 /* Use the zero-page for reads */
4972 if (!(vmf->flags & FAULT_FLAG_WRITE) &&
4973 !mm_forbids_zeropage(vma->vm_mm)) {
4974 entry = pte_mkspecial(pfn_pte(my_zero_pfn(vmf->address),
4975 vma->vm_page_prot));
4976 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
4977 vmf->address, &vmf->ptl);
4978 if (!vmf->pte)
4979 goto unlock;
4980 if (vmf_pte_changed(vmf)) {
4981 update_mmu_tlb(vma, vmf->address, vmf->pte);
4982 goto unlock;
4983 }
4984 ret = check_stable_address_space(vma->vm_mm);
4985 if (ret)
4986 goto unlock;
4987 /* Deliver the page fault to userland, check inside PT lock */
4988 if (userfaultfd_missing(vma)) {
4989 pte_unmap_unlock(vmf->pte, vmf->ptl);
4990 return handle_userfault(vmf, VM_UFFD_MISSING);
4991 }
4992 goto setpte;
4993 }
4994
4995 /* Allocate our own private page. */
4996 ret = vmf_anon_prepare(vmf);
4997 if (ret)
4998 return ret;
4999 /* Returns NULL on OOM or ERR_PTR(-EAGAIN) if we must retry the fault */
5000 folio = alloc_anon_folio(vmf);
5001 if (IS_ERR(folio))
5002 return 0;
5003 if (!folio)
5004 goto oom;
5005
5006 nr_pages = folio_nr_pages(folio);
5007 addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE);
5008
5009 /*
5010 * The memory barrier inside __folio_mark_uptodate makes sure that
5011 * preceding stores to the page contents become visible before
5012 * the set_pte_at() write.
5013 */
5014 __folio_mark_uptodate(folio);
5015
5016 entry = mk_pte(&folio->page, vma->vm_page_prot);
5017 entry = pte_sw_mkyoung(entry);
5018 if (vma->vm_flags & VM_WRITE)
5019 entry = pte_mkwrite(pte_mkdirty(entry), vma);
5020
5021 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
5022 if (!vmf->pte)
5023 goto release;
5024 if (nr_pages == 1 && vmf_pte_changed(vmf)) {
5025 update_mmu_tlb(vma, addr, vmf->pte);
5026 goto release;
5027 } else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) {
5028 update_mmu_tlb_range(vma, addr, vmf->pte, nr_pages);
5029 goto release;
5030 }
5031
5032 ret = check_stable_address_space(vma->vm_mm);
5033 if (ret)
5034 goto release;
5035
5036 /* Deliver the page fault to userland, check inside PT lock */
5037 if (userfaultfd_missing(vma)) {
5038 pte_unmap_unlock(vmf->pte, vmf->ptl);
5039 folio_put(folio);
5040 return handle_userfault(vmf, VM_UFFD_MISSING);
5041 }
5042
5043 folio_ref_add(folio, nr_pages - 1);
5044 add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages);
5045 count_mthp_stat(folio_order(folio), MTHP_STAT_ANON_FAULT_ALLOC);
5046 folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
5047 folio_add_lru_vma(folio, vma);
5048 setpte:
5049 if (vmf_orig_pte_uffd_wp(vmf))
5050 entry = pte_mkuffd_wp(entry);
5051 set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr_pages);
5052
5053 /* No need to invalidate - it was non-present before */
5054 update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr_pages);
5055 unlock:
5056 if (vmf->pte)
5057 pte_unmap_unlock(vmf->pte, vmf->ptl);
5058 return ret;
5059 release:
5060 folio_put(folio);
5061 goto unlock;
5062 oom:
5063 return VM_FAULT_OOM;
5064 }
5065
5066 /*
5067 * The mmap_lock must have been held on entry, and may have been
5068 * released depending on flags and vma->vm_ops->fault() return value.
5069 * See filemap_fault() and __lock_page_retry().
5070 */
__do_fault(struct vm_fault * vmf)5071 static vm_fault_t __do_fault(struct vm_fault *vmf)
5072 {
5073 struct vm_area_struct *vma = vmf->vma;
5074 struct folio *folio;
5075 vm_fault_t ret;
5076
5077 /*
5078 * Preallocate pte before we take page_lock because this might lead to
5079 * deadlocks for memcg reclaim which waits for pages under writeback:
5080 * lock_page(A)
5081 * SetPageWriteback(A)
5082 * unlock_page(A)
5083 * lock_page(B)
5084 * lock_page(B)
5085 * pte_alloc_one
5086 * shrink_folio_list
5087 * wait_on_page_writeback(A)
5088 * SetPageWriteback(B)
5089 * unlock_page(B)
5090 * # flush A, B to clear the writeback
5091 */
5092 if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
5093 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
5094 if (!vmf->prealloc_pte)
5095 return VM_FAULT_OOM;
5096 }
5097
5098 ret = vma->vm_ops->fault(vmf);
5099 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
5100 VM_FAULT_DONE_COW)))
5101 return ret;
5102
5103 folio = page_folio(vmf->page);
5104 if (unlikely(PageHWPoison(vmf->page))) {
5105 vm_fault_t poisonret = VM_FAULT_HWPOISON;
5106 if (ret & VM_FAULT_LOCKED) {
5107 if (page_mapped(vmf->page))
5108 unmap_mapping_folio(folio);
5109 /* Retry if a clean folio was removed from the cache. */
5110 if (mapping_evict_folio(folio->mapping, folio))
5111 poisonret = VM_FAULT_NOPAGE;
5112 folio_unlock(folio);
5113 }
5114 folio_put(folio);
5115 vmf->page = NULL;
5116 return poisonret;
5117 }
5118
5119 if (unlikely(!(ret & VM_FAULT_LOCKED)))
5120 folio_lock(folio);
5121 else
5122 VM_BUG_ON_PAGE(!folio_test_locked(folio), vmf->page);
5123
5124 return ret;
5125 }
5126
5127 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
deposit_prealloc_pte(struct vm_fault * vmf)5128 static void deposit_prealloc_pte(struct vm_fault *vmf)
5129 {
5130 struct vm_area_struct *vma = vmf->vma;
5131
5132 pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
5133 /*
5134 * We are going to consume the prealloc table,
5135 * count that as nr_ptes.
5136 */
5137 mm_inc_nr_ptes(vma->vm_mm);
5138 vmf->prealloc_pte = NULL;
5139 }
5140
do_set_pmd(struct vm_fault * vmf,struct page * page)5141 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
5142 {
5143 struct folio *folio = page_folio(page);
5144 struct vm_area_struct *vma = vmf->vma;
5145 bool write = vmf->flags & FAULT_FLAG_WRITE;
5146 unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
5147 pmd_t entry;
5148 vm_fault_t ret = VM_FAULT_FALLBACK;
5149
5150 /*
5151 * It is too late to allocate a small folio, we already have a large
5152 * folio in the pagecache: especially s390 KVM cannot tolerate any
5153 * PMD mappings, but PTE-mapped THP are fine. So let's simply refuse any
5154 * PMD mappings if THPs are disabled.
5155 */
5156 if (thp_disabled_by_hw() || vma_thp_disabled(vma, vma->vm_flags))
5157 return ret;
5158
5159 if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER))
5160 return ret;
5161
5162 if (folio_order(folio) != HPAGE_PMD_ORDER)
5163 return ret;
5164 page = &folio->page;
5165
5166 /*
5167 * Just backoff if any subpage of a THP is corrupted otherwise
5168 * the corrupted page may mapped by PMD silently to escape the
5169 * check. This kind of THP just can be PTE mapped. Access to
5170 * the corrupted subpage should trigger SIGBUS as expected.
5171 */
5172 if (unlikely(folio_test_has_hwpoisoned(folio)))
5173 return ret;
5174
5175 /*
5176 * Archs like ppc64 need additional space to store information
5177 * related to pte entry. Use the preallocated table for that.
5178 */
5179 if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
5180 vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
5181 if (!vmf->prealloc_pte)
5182 return VM_FAULT_OOM;
5183 }
5184
5185 vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
5186 if (unlikely(!pmd_none(*vmf->pmd)))
5187 goto out;
5188
5189 flush_icache_pages(vma, page, HPAGE_PMD_NR);
5190
5191 entry = mk_huge_pmd(page, vma->vm_page_prot);
5192 if (write)
5193 entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
5194
5195 add_mm_counter(vma->vm_mm, mm_counter_file(folio), HPAGE_PMD_NR);
5196 folio_add_file_rmap_pmd(folio, page, vma);
5197
5198 /*
5199 * deposit and withdraw with pmd lock held
5200 */
5201 if (arch_needs_pgtable_deposit())
5202 deposit_prealloc_pte(vmf);
5203
5204 set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
5205
5206 update_mmu_cache_pmd(vma, haddr, vmf->pmd);
5207
5208 /* fault is handled */
5209 ret = 0;
5210 count_vm_event(THP_FILE_MAPPED);
5211 out:
5212 spin_unlock(vmf->ptl);
5213 return ret;
5214 }
5215 #else
do_set_pmd(struct vm_fault * vmf,struct page * page)5216 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
5217 {
5218 return VM_FAULT_FALLBACK;
5219 }
5220 #endif
5221
5222 /**
5223 * set_pte_range - Set a range of PTEs to point to pages in a folio.
5224 * @vmf: Fault decription.
5225 * @folio: The folio that contains @page.
5226 * @page: The first page to create a PTE for.
5227 * @nr: The number of PTEs to create.
5228 * @addr: The first address to create a PTE for.
5229 */
set_pte_range(struct vm_fault * vmf,struct folio * folio,struct page * page,unsigned int nr,unsigned long addr)5230 void set_pte_range(struct vm_fault *vmf, struct folio *folio,
5231 struct page *page, unsigned int nr, unsigned long addr)
5232 {
5233 struct vm_area_struct *vma = vmf->vma;
5234 bool write = vmf->flags & FAULT_FLAG_WRITE;
5235 bool prefault = !in_range(vmf->address, addr, nr * PAGE_SIZE);
5236 pte_t entry;
5237
5238 flush_icache_pages(vma, page, nr);
5239 entry = mk_pte(page, vma->vm_page_prot);
5240
5241 if (prefault && arch_wants_old_prefaulted_pte())
5242 entry = pte_mkold(entry);
5243 else
5244 entry = pte_sw_mkyoung(entry);
5245
5246 if (write)
5247 entry = maybe_mkwrite(pte_mkdirty(entry), vma);
5248 if (unlikely(vmf_orig_pte_uffd_wp(vmf)))
5249 entry = pte_mkuffd_wp(entry);
5250 /* copy-on-write page */
5251 if (write && !(vma->vm_flags & VM_SHARED)) {
5252 VM_BUG_ON_FOLIO(nr != 1, folio);
5253 folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
5254 folio_add_lru_vma(folio, vma);
5255 } else {
5256 folio_add_file_rmap_ptes(folio, page, nr, vma);
5257 }
5258 set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr);
5259
5260 /* no need to invalidate: a not-present page won't be cached */
5261 update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr);
5262 }
5263
vmf_pte_changed(struct vm_fault * vmf)5264 static bool vmf_pte_changed(struct vm_fault *vmf)
5265 {
5266 if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)
5267 return !pte_same(ptep_get(vmf->pte), vmf->orig_pte);
5268
5269 return !pte_none(ptep_get(vmf->pte));
5270 }
5271
5272 /**
5273 * finish_fault - finish page fault once we have prepared the page to fault
5274 *
5275 * @vmf: structure describing the fault
5276 *
5277 * This function handles all that is needed to finish a page fault once the
5278 * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
5279 * given page, adds reverse page mapping, handles memcg charges and LRU
5280 * addition.
5281 *
5282 * The function expects the page to be locked and on success it consumes a
5283 * reference of a page being mapped (for the PTE which maps it).
5284 *
5285 * Return: %0 on success, %VM_FAULT_ code in case of error.
5286 */
finish_fault(struct vm_fault * vmf)5287 vm_fault_t finish_fault(struct vm_fault *vmf)
5288 {
5289 struct vm_area_struct *vma = vmf->vma;
5290 struct page *page;
5291 struct folio *folio;
5292 vm_fault_t ret;
5293 bool is_cow = (vmf->flags & FAULT_FLAG_WRITE) &&
5294 !(vma->vm_flags & VM_SHARED);
5295 int type, nr_pages;
5296 unsigned long addr;
5297 bool needs_fallback = false;
5298
5299 fallback:
5300 addr = vmf->address;
5301
5302 /* Did we COW the page? */
5303 if (is_cow)
5304 page = vmf->cow_page;
5305 else
5306 page = vmf->page;
5307
5308 /*
5309 * check even for read faults because we might have lost our CoWed
5310 * page
5311 */
5312 if (!(vma->vm_flags & VM_SHARED)) {
5313 ret = check_stable_address_space(vma->vm_mm);
5314 if (ret)
5315 return ret;
5316 }
5317
5318 if (pmd_none(*vmf->pmd)) {
5319 if (PageTransCompound(page)) {
5320 ret = do_set_pmd(vmf, page);
5321 if (ret != VM_FAULT_FALLBACK)
5322 return ret;
5323 }
5324
5325 if (vmf->prealloc_pte)
5326 pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte);
5327 else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd)))
5328 return VM_FAULT_OOM;
5329 }
5330
5331 folio = page_folio(page);
5332 nr_pages = folio_nr_pages(folio);
5333
5334 /*
5335 * Using per-page fault to maintain the uffd semantics, and same
5336 * approach also applies to non-anonymous-shmem faults to avoid
5337 * inflating the RSS of the process.
5338 */
5339 if (!vma_is_anon_shmem(vma) || unlikely(userfaultfd_armed(vma)) ||
5340 unlikely(needs_fallback)) {
5341 nr_pages = 1;
5342 } else if (nr_pages > 1) {
5343 pgoff_t idx = folio_page_idx(folio, page);
5344 /* The page offset of vmf->address within the VMA. */
5345 pgoff_t vma_off = vmf->pgoff - vmf->vma->vm_pgoff;
5346 /* The index of the entry in the pagetable for fault page. */
5347 pgoff_t pte_off = pte_index(vmf->address);
5348
5349 /*
5350 * Fallback to per-page fault in case the folio size in page
5351 * cache beyond the VMA limits and PMD pagetable limits.
5352 */
5353 if (unlikely(vma_off < idx ||
5354 vma_off + (nr_pages - idx) > vma_pages(vma) ||
5355 pte_off < idx ||
5356 pte_off + (nr_pages - idx) > PTRS_PER_PTE)) {
5357 nr_pages = 1;
5358 } else {
5359 /* Now we can set mappings for the whole large folio. */
5360 addr = vmf->address - idx * PAGE_SIZE;
5361 page = &folio->page;
5362 }
5363 }
5364
5365 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
5366 addr, &vmf->ptl);
5367 if (!vmf->pte)
5368 return VM_FAULT_NOPAGE;
5369
5370 /* Re-check under ptl */
5371 if (nr_pages == 1 && unlikely(vmf_pte_changed(vmf))) {
5372 update_mmu_tlb(vma, addr, vmf->pte);
5373 ret = VM_FAULT_NOPAGE;
5374 goto unlock;
5375 } else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) {
5376 needs_fallback = true;
5377 pte_unmap_unlock(vmf->pte, vmf->ptl);
5378 goto fallback;
5379 }
5380
5381 folio_ref_add(folio, nr_pages - 1);
5382 set_pte_range(vmf, folio, page, nr_pages, addr);
5383 type = is_cow ? MM_ANONPAGES : mm_counter_file(folio);
5384 add_mm_counter(vma->vm_mm, type, nr_pages);
5385 ret = 0;
5386
5387 unlock:
5388 pte_unmap_unlock(vmf->pte, vmf->ptl);
5389 return ret;
5390 }
5391
5392 static unsigned long fault_around_pages __read_mostly =
5393 65536 >> PAGE_SHIFT;
5394
5395 #ifdef CONFIG_DEBUG_FS
fault_around_bytes_get(void * data,u64 * val)5396 static int fault_around_bytes_get(void *data, u64 *val)
5397 {
5398 *val = fault_around_pages << PAGE_SHIFT;
5399 return 0;
5400 }
5401
5402 /*
5403 * fault_around_bytes must be rounded down to the nearest page order as it's
5404 * what do_fault_around() expects to see.
5405 */
fault_around_bytes_set(void * data,u64 val)5406 static int fault_around_bytes_set(void *data, u64 val)
5407 {
5408 if (val / PAGE_SIZE > PTRS_PER_PTE)
5409 return -EINVAL;
5410
5411 /*
5412 * The minimum value is 1 page, however this results in no fault-around
5413 * at all. See should_fault_around().
5414 */
5415 val = max(val, PAGE_SIZE);
5416 fault_around_pages = rounddown_pow_of_two(val) >> PAGE_SHIFT;
5417
5418 return 0;
5419 }
5420 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
5421 fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
5422
fault_around_debugfs(void)5423 static int __init fault_around_debugfs(void)
5424 {
5425 debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
5426 &fault_around_bytes_fops);
5427 return 0;
5428 }
5429 late_initcall(fault_around_debugfs);
5430 #endif
5431
5432 /*
5433 * do_fault_around() tries to map few pages around the fault address. The hope
5434 * is that the pages will be needed soon and this will lower the number of
5435 * faults to handle.
5436 *
5437 * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
5438 * not ready to be mapped: not up-to-date, locked, etc.
5439 *
5440 * This function doesn't cross VMA or page table boundaries, in order to call
5441 * map_pages() and acquire a PTE lock only once.
5442 *
5443 * fault_around_pages defines how many pages we'll try to map.
5444 * do_fault_around() expects it to be set to a power of two less than or equal
5445 * to PTRS_PER_PTE.
5446 *
5447 * The virtual address of the area that we map is naturally aligned to
5448 * fault_around_pages * PAGE_SIZE rounded down to the machine page size
5449 * (and therefore to page order). This way it's easier to guarantee
5450 * that we don't cross page table boundaries.
5451 */
do_fault_around(struct vm_fault * vmf)5452 static vm_fault_t do_fault_around(struct vm_fault *vmf)
5453 {
5454 pgoff_t nr_pages = READ_ONCE(fault_around_pages);
5455 pgoff_t pte_off = pte_index(vmf->address);
5456 /* The page offset of vmf->address within the VMA. */
5457 pgoff_t vma_off = vmf->pgoff - vmf->vma->vm_pgoff;
5458 pgoff_t from_pte, to_pte;
5459 vm_fault_t ret;
5460
5461 /* The PTE offset of the start address, clamped to the VMA. */
5462 from_pte = max(ALIGN_DOWN(pte_off, nr_pages),
5463 pte_off - min(pte_off, vma_off));
5464
5465 /* The PTE offset of the end address, clamped to the VMA and PTE. */
5466 to_pte = min3(from_pte + nr_pages, (pgoff_t)PTRS_PER_PTE,
5467 pte_off + vma_pages(vmf->vma) - vma_off) - 1;
5468
5469 if (pmd_none(*vmf->pmd)) {
5470 vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
5471 if (!vmf->prealloc_pte)
5472 return VM_FAULT_OOM;
5473 }
5474
5475 rcu_read_lock();
5476 ret = vmf->vma->vm_ops->map_pages(vmf,
5477 vmf->pgoff + from_pte - pte_off,
5478 vmf->pgoff + to_pte - pte_off);
5479 rcu_read_unlock();
5480
5481 return ret;
5482 }
5483
5484 /* Return true if we should do read fault-around, false otherwise */
should_fault_around(struct vm_fault * vmf)5485 static inline bool should_fault_around(struct vm_fault *vmf)
5486 {
5487 /* No ->map_pages? No way to fault around... */
5488 if (!vmf->vma->vm_ops->map_pages)
5489 return false;
5490
5491 if (uffd_disable_fault_around(vmf->vma))
5492 return false;
5493
5494 /* A single page implies no faulting 'around' at all. */
5495 return fault_around_pages > 1;
5496 }
5497
do_read_fault(struct vm_fault * vmf)5498 static vm_fault_t do_read_fault(struct vm_fault *vmf)
5499 {
5500 vm_fault_t ret = 0;
5501 struct folio *folio;
5502
5503 /*
5504 * Let's call ->map_pages() first and use ->fault() as fallback
5505 * if page by the offset is not ready to be mapped (cold cache or
5506 * something).
5507 */
5508 if (should_fault_around(vmf)) {
5509 ret = do_fault_around(vmf);
5510 if (ret)
5511 return ret;
5512 }
5513
5514 ret = vmf_can_call_fault(vmf);
5515 if (ret)
5516 return ret;
5517
5518 ret = __do_fault(vmf);
5519 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5520 return ret;
5521
5522 ret |= finish_fault(vmf);
5523 folio = page_folio(vmf->page);
5524 folio_unlock(folio);
5525 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5526 folio_put(folio);
5527 return ret;
5528 }
5529
do_cow_fault(struct vm_fault * vmf)5530 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
5531 {
5532 struct vm_area_struct *vma = vmf->vma;
5533 struct folio *folio;
5534 vm_fault_t ret;
5535
5536 ret = vmf_can_call_fault(vmf);
5537 if (!ret)
5538 ret = vmf_anon_prepare(vmf);
5539 if (ret)
5540 return ret;
5541
5542 folio = folio_prealloc(vma->vm_mm, vma, vmf->address, false);
5543 if (!folio)
5544 return VM_FAULT_OOM;
5545
5546 vmf->cow_page = &folio->page;
5547
5548 ret = __do_fault(vmf);
5549 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5550 goto uncharge_out;
5551 if (ret & VM_FAULT_DONE_COW)
5552 return ret;
5553
5554 if (copy_mc_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma)) {
5555 ret = VM_FAULT_HWPOISON;
5556 goto unlock;
5557 }
5558 __folio_mark_uptodate(folio);
5559
5560 ret |= finish_fault(vmf);
5561 unlock:
5562 unlock_page(vmf->page);
5563 put_page(vmf->page);
5564 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5565 goto uncharge_out;
5566 return ret;
5567 uncharge_out:
5568 folio_put(folio);
5569 return ret;
5570 }
5571
do_shared_fault(struct vm_fault * vmf)5572 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
5573 {
5574 struct vm_area_struct *vma = vmf->vma;
5575 vm_fault_t ret, tmp;
5576 struct folio *folio;
5577
5578 ret = vmf_can_call_fault(vmf);
5579 if (ret)
5580 return ret;
5581
5582 ret = __do_fault(vmf);
5583 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
5584 return ret;
5585
5586 folio = page_folio(vmf->page);
5587
5588 /*
5589 * Check if the backing address space wants to know that the page is
5590 * about to become writable
5591 */
5592 if (vma->vm_ops->page_mkwrite) {
5593 folio_unlock(folio);
5594 tmp = do_page_mkwrite(vmf, folio);
5595 if (unlikely(!tmp ||
5596 (tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
5597 folio_put(folio);
5598 return tmp;
5599 }
5600 }
5601
5602 ret |= finish_fault(vmf);
5603 if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
5604 VM_FAULT_RETRY))) {
5605 folio_unlock(folio);
5606 folio_put(folio);
5607 return ret;
5608 }
5609
5610 ret |= fault_dirty_shared_page(vmf);
5611 return ret;
5612 }
5613
5614 /*
5615 * We enter with non-exclusive mmap_lock (to exclude vma changes,
5616 * but allow concurrent faults).
5617 * The mmap_lock may have been released depending on flags and our
5618 * return value. See filemap_fault() and __folio_lock_or_retry().
5619 * If mmap_lock is released, vma may become invalid (for example
5620 * by other thread calling munmap()).
5621 */
do_fault(struct vm_fault * vmf)5622 static vm_fault_t do_fault(struct vm_fault *vmf)
5623 {
5624 struct vm_area_struct *vma = vmf->vma;
5625 struct mm_struct *vm_mm = vma->vm_mm;
5626 vm_fault_t ret;
5627
5628 /*
5629 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
5630 */
5631 if (!vma->vm_ops->fault) {
5632 vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
5633 vmf->address, &vmf->ptl);
5634 if (unlikely(!vmf->pte))
5635 ret = VM_FAULT_SIGBUS;
5636 else {
5637 /*
5638 * Make sure this is not a temporary clearing of pte
5639 * by holding ptl and checking again. A R/M/W update
5640 * of pte involves: take ptl, clearing the pte so that
5641 * we don't have concurrent modification by hardware
5642 * followed by an update.
5643 */
5644 if (unlikely(pte_none(ptep_get(vmf->pte))))
5645 ret = VM_FAULT_SIGBUS;
5646 else
5647 ret = VM_FAULT_NOPAGE;
5648
5649 pte_unmap_unlock(vmf->pte, vmf->ptl);
5650 }
5651 } else if (!(vmf->flags & FAULT_FLAG_WRITE))
5652 ret = do_read_fault(vmf);
5653 else if (!(vma->vm_flags & VM_SHARED))
5654 ret = do_cow_fault(vmf);
5655 else
5656 ret = do_shared_fault(vmf);
5657
5658 /* preallocated pagetable is unused: free it */
5659 if (vmf->prealloc_pte) {
5660 pte_free(vm_mm, vmf->prealloc_pte);
5661 vmf->prealloc_pte = NULL;
5662 }
5663 return ret;
5664 }
5665
numa_migrate_check(struct folio * folio,struct vm_fault * vmf,unsigned long addr,int * flags,bool writable,int * last_cpupid)5666 int numa_migrate_check(struct folio *folio, struct vm_fault *vmf,
5667 unsigned long addr, int *flags,
5668 bool writable, int *last_cpupid)
5669 {
5670 struct vm_area_struct *vma = vmf->vma;
5671
5672 /*
5673 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
5674 * much anyway since they can be in shared cache state. This misses
5675 * the case where a mapping is writable but the process never writes
5676 * to it but pte_write gets cleared during protection updates and
5677 * pte_dirty has unpredictable behaviour between PTE scan updates,
5678 * background writeback, dirty balancing and application behaviour.
5679 */
5680 if (!writable)
5681 *flags |= TNF_NO_GROUP;
5682
5683 /*
5684 * Flag if the folio is shared between multiple address spaces. This
5685 * is later used when determining whether to group tasks together
5686 */
5687 if (folio_maybe_mapped_shared(folio) && (vma->vm_flags & VM_SHARED))
5688 *flags |= TNF_SHARED;
5689 /*
5690 * For memory tiering mode, cpupid of slow memory page is used
5691 * to record page access time. So use default value.
5692 */
5693 if (folio_use_access_time(folio))
5694 *last_cpupid = (-1 & LAST_CPUPID_MASK);
5695 else
5696 *last_cpupid = folio_last_cpupid(folio);
5697
5698 /* Record the current PID acceesing VMA */
5699 vma_set_access_pid_bit(vma);
5700
5701 count_vm_numa_event(NUMA_HINT_FAULTS);
5702 #ifdef CONFIG_NUMA_BALANCING
5703 count_memcg_folio_events(folio, NUMA_HINT_FAULTS, 1);
5704 #endif
5705 if (folio_nid(folio) == numa_node_id()) {
5706 count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
5707 *flags |= TNF_FAULT_LOCAL;
5708 }
5709
5710 return mpol_misplaced(folio, vmf, addr);
5711 }
5712
numa_rebuild_single_mapping(struct vm_fault * vmf,struct vm_area_struct * vma,unsigned long fault_addr,pte_t * fault_pte,bool writable)5713 static void numa_rebuild_single_mapping(struct vm_fault *vmf, struct vm_area_struct *vma,
5714 unsigned long fault_addr, pte_t *fault_pte,
5715 bool writable)
5716 {
5717 pte_t pte, old_pte;
5718
5719 old_pte = ptep_modify_prot_start(vma, fault_addr, fault_pte);
5720 pte = pte_modify(old_pte, vma->vm_page_prot);
5721 pte = pte_mkyoung(pte);
5722 if (writable)
5723 pte = pte_mkwrite(pte, vma);
5724 ptep_modify_prot_commit(vma, fault_addr, fault_pte, old_pte, pte);
5725 update_mmu_cache_range(vmf, vma, fault_addr, fault_pte, 1);
5726 }
5727
numa_rebuild_large_mapping(struct vm_fault * vmf,struct vm_area_struct * vma,struct folio * folio,pte_t fault_pte,bool ignore_writable,bool pte_write_upgrade)5728 static void numa_rebuild_large_mapping(struct vm_fault *vmf, struct vm_area_struct *vma,
5729 struct folio *folio, pte_t fault_pte,
5730 bool ignore_writable, bool pte_write_upgrade)
5731 {
5732 int nr = pte_pfn(fault_pte) - folio_pfn(folio);
5733 unsigned long start, end, addr = vmf->address;
5734 unsigned long addr_start = addr - (nr << PAGE_SHIFT);
5735 unsigned long pt_start = ALIGN_DOWN(addr, PMD_SIZE);
5736 pte_t *start_ptep;
5737
5738 /* Stay within the VMA and within the page table. */
5739 start = max3(addr_start, pt_start, vma->vm_start);
5740 end = min3(addr_start + folio_size(folio), pt_start + PMD_SIZE,
5741 vma->vm_end);
5742 start_ptep = vmf->pte - ((addr - start) >> PAGE_SHIFT);
5743
5744 /* Restore all PTEs' mapping of the large folio */
5745 for (addr = start; addr != end; start_ptep++, addr += PAGE_SIZE) {
5746 pte_t ptent = ptep_get(start_ptep);
5747 bool writable = false;
5748
5749 if (!pte_present(ptent) || !pte_protnone(ptent))
5750 continue;
5751
5752 if (pfn_folio(pte_pfn(ptent)) != folio)
5753 continue;
5754
5755 if (!ignore_writable) {
5756 ptent = pte_modify(ptent, vma->vm_page_prot);
5757 writable = pte_write(ptent);
5758 if (!writable && pte_write_upgrade &&
5759 can_change_pte_writable(vma, addr, ptent))
5760 writable = true;
5761 }
5762
5763 numa_rebuild_single_mapping(vmf, vma, addr, start_ptep, writable);
5764 }
5765 }
5766
do_numa_page(struct vm_fault * vmf)5767 static vm_fault_t do_numa_page(struct vm_fault *vmf)
5768 {
5769 struct vm_area_struct *vma = vmf->vma;
5770 struct folio *folio = NULL;
5771 int nid = NUMA_NO_NODE;
5772 bool writable = false, ignore_writable = false;
5773 bool pte_write_upgrade = vma_wants_manual_pte_write_upgrade(vma);
5774 int last_cpupid;
5775 int target_nid;
5776 pte_t pte, old_pte;
5777 int flags = 0, nr_pages;
5778
5779 /*
5780 * The pte cannot be used safely until we verify, while holding the page
5781 * table lock, that its contents have not changed during fault handling.
5782 */
5783 spin_lock(vmf->ptl);
5784 /* Read the live PTE from the page tables: */
5785 old_pte = ptep_get(vmf->pte);
5786
5787 if (unlikely(!pte_same(old_pte, vmf->orig_pte))) {
5788 pte_unmap_unlock(vmf->pte, vmf->ptl);
5789 return 0;
5790 }
5791
5792 pte = pte_modify(old_pte, vma->vm_page_prot);
5793
5794 /*
5795 * Detect now whether the PTE could be writable; this information
5796 * is only valid while holding the PT lock.
5797 */
5798 writable = pte_write(pte);
5799 if (!writable && pte_write_upgrade &&
5800 can_change_pte_writable(vma, vmf->address, pte))
5801 writable = true;
5802
5803 folio = vm_normal_folio(vma, vmf->address, pte);
5804 if (!folio || folio_is_zone_device(folio))
5805 goto out_map;
5806
5807 nid = folio_nid(folio);
5808 nr_pages = folio_nr_pages(folio);
5809
5810 target_nid = numa_migrate_check(folio, vmf, vmf->address, &flags,
5811 writable, &last_cpupid);
5812 if (target_nid == NUMA_NO_NODE)
5813 goto out_map;
5814 if (migrate_misplaced_folio_prepare(folio, vma, target_nid)) {
5815 flags |= TNF_MIGRATE_FAIL;
5816 goto out_map;
5817 }
5818 /* The folio is isolated and isolation code holds a folio reference. */
5819 pte_unmap_unlock(vmf->pte, vmf->ptl);
5820 writable = false;
5821 ignore_writable = true;
5822
5823 /* Migrate to the requested node */
5824 if (!migrate_misplaced_folio(folio, target_nid)) {
5825 nid = target_nid;
5826 flags |= TNF_MIGRATED;
5827 task_numa_fault(last_cpupid, nid, nr_pages, flags);
5828 return 0;
5829 }
5830
5831 flags |= TNF_MIGRATE_FAIL;
5832 vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
5833 vmf->address, &vmf->ptl);
5834 if (unlikely(!vmf->pte))
5835 return 0;
5836 if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
5837 pte_unmap_unlock(vmf->pte, vmf->ptl);
5838 return 0;
5839 }
5840 out_map:
5841 /*
5842 * Make it present again, depending on how arch implements
5843 * non-accessible ptes, some can allow access by kernel mode.
5844 */
5845 if (folio && folio_test_large(folio))
5846 numa_rebuild_large_mapping(vmf, vma, folio, pte, ignore_writable,
5847 pte_write_upgrade);
5848 else
5849 numa_rebuild_single_mapping(vmf, vma, vmf->address, vmf->pte,
5850 writable);
5851 pte_unmap_unlock(vmf->pte, vmf->ptl);
5852
5853 if (nid != NUMA_NO_NODE)
5854 task_numa_fault(last_cpupid, nid, nr_pages, flags);
5855 return 0;
5856 }
5857
create_huge_pmd(struct vm_fault * vmf)5858 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
5859 {
5860 struct vm_area_struct *vma = vmf->vma;
5861 if (vma_is_anonymous(vma))
5862 return do_huge_pmd_anonymous_page(vmf);
5863 if (vma->vm_ops->huge_fault)
5864 return vma->vm_ops->huge_fault(vmf, PMD_ORDER);
5865 return VM_FAULT_FALLBACK;
5866 }
5867
5868 /* `inline' is required to avoid gcc 4.1.2 build error */
wp_huge_pmd(struct vm_fault * vmf)5869 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf)
5870 {
5871 struct vm_area_struct *vma = vmf->vma;
5872 const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
5873 vm_fault_t ret;
5874
5875 if (vma_is_anonymous(vma)) {
5876 if (likely(!unshare) &&
5877 userfaultfd_huge_pmd_wp(vma, vmf->orig_pmd)) {
5878 if (userfaultfd_wp_async(vmf->vma))
5879 goto split;
5880 return handle_userfault(vmf, VM_UFFD_WP);
5881 }
5882 return do_huge_pmd_wp_page(vmf);
5883 }
5884
5885 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
5886 if (vma->vm_ops->huge_fault) {
5887 ret = vma->vm_ops->huge_fault(vmf, PMD_ORDER);
5888 if (!(ret & VM_FAULT_FALLBACK))
5889 return ret;
5890 }
5891 }
5892
5893 split:
5894 /* COW or write-notify handled on pte level: split pmd. */
5895 __split_huge_pmd(vma, vmf->pmd, vmf->address, false, NULL);
5896
5897 return VM_FAULT_FALLBACK;
5898 }
5899
create_huge_pud(struct vm_fault * vmf)5900 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
5901 {
5902 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
5903 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
5904 struct vm_area_struct *vma = vmf->vma;
5905 /* No support for anonymous transparent PUD pages yet */
5906 if (vma_is_anonymous(vma))
5907 return VM_FAULT_FALLBACK;
5908 if (vma->vm_ops->huge_fault)
5909 return vma->vm_ops->huge_fault(vmf, PUD_ORDER);
5910 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
5911 return VM_FAULT_FALLBACK;
5912 }
5913
wp_huge_pud(struct vm_fault * vmf,pud_t orig_pud)5914 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
5915 {
5916 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && \
5917 defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
5918 struct vm_area_struct *vma = vmf->vma;
5919 vm_fault_t ret;
5920
5921 /* No support for anonymous transparent PUD pages yet */
5922 if (vma_is_anonymous(vma))
5923 goto split;
5924 if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
5925 if (vma->vm_ops->huge_fault) {
5926 ret = vma->vm_ops->huge_fault(vmf, PUD_ORDER);
5927 if (!(ret & VM_FAULT_FALLBACK))
5928 return ret;
5929 }
5930 }
5931 split:
5932 /* COW or write-notify not handled on PUD level: split pud.*/
5933 __split_huge_pud(vma, vmf->pud, vmf->address);
5934 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
5935 return VM_FAULT_FALLBACK;
5936 }
5937
5938 /*
5939 * These routines also need to handle stuff like marking pages dirty
5940 * and/or accessed for architectures that don't do it in hardware (most
5941 * RISC architectures). The early dirtying is also good on the i386.
5942 *
5943 * There is also a hook called "update_mmu_cache()" that architectures
5944 * with external mmu caches can use to update those (ie the Sparc or
5945 * PowerPC hashed page tables that act as extended TLBs).
5946 *
5947 * We enter with non-exclusive mmap_lock (to exclude vma changes, but allow
5948 * concurrent faults).
5949 *
5950 * The mmap_lock may have been released depending on flags and our return value.
5951 * See filemap_fault() and __folio_lock_or_retry().
5952 */
handle_pte_fault(struct vm_fault * vmf)5953 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
5954 {
5955 pte_t entry;
5956
5957 if (unlikely(pmd_none(*vmf->pmd))) {
5958 /*
5959 * Leave __pte_alloc() until later: because vm_ops->fault may
5960 * want to allocate huge page, and if we expose page table
5961 * for an instant, it will be difficult to retract from
5962 * concurrent faults and from rmap lookups.
5963 */
5964 vmf->pte = NULL;
5965 vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID;
5966 } else {
5967 pmd_t dummy_pmdval;
5968
5969 /*
5970 * A regular pmd is established and it can't morph into a huge
5971 * pmd by anon khugepaged, since that takes mmap_lock in write
5972 * mode; but shmem or file collapse to THP could still morph
5973 * it into a huge pmd: just retry later if so.
5974 *
5975 * Use the maywrite version to indicate that vmf->pte may be
5976 * modified, but since we will use pte_same() to detect the
5977 * change of the !pte_none() entry, there is no need to recheck
5978 * the pmdval. Here we chooes to pass a dummy variable instead
5979 * of NULL, which helps new user think about why this place is
5980 * special.
5981 */
5982 vmf->pte = pte_offset_map_rw_nolock(vmf->vma->vm_mm, vmf->pmd,
5983 vmf->address, &dummy_pmdval,
5984 &vmf->ptl);
5985 if (unlikely(!vmf->pte))
5986 return 0;
5987 vmf->orig_pte = ptep_get_lockless(vmf->pte);
5988 vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID;
5989
5990 if (pte_none(vmf->orig_pte)) {
5991 pte_unmap(vmf->pte);
5992 vmf->pte = NULL;
5993 }
5994 }
5995
5996 if (!vmf->pte)
5997 return do_pte_missing(vmf);
5998
5999 if (!pte_present(vmf->orig_pte))
6000 return do_swap_page(vmf);
6001
6002 if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma))
6003 return do_numa_page(vmf);
6004
6005 spin_lock(vmf->ptl);
6006 entry = vmf->orig_pte;
6007 if (unlikely(!pte_same(ptep_get(vmf->pte), entry))) {
6008 update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
6009 goto unlock;
6010 }
6011 if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
6012 if (!pte_write(entry))
6013 return do_wp_page(vmf);
6014 else if (likely(vmf->flags & FAULT_FLAG_WRITE))
6015 entry = pte_mkdirty(entry);
6016 }
6017 entry = pte_mkyoung(entry);
6018 if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
6019 vmf->flags & FAULT_FLAG_WRITE)) {
6020 update_mmu_cache_range(vmf, vmf->vma, vmf->address,
6021 vmf->pte, 1);
6022 } else {
6023 /* Skip spurious TLB flush for retried page fault */
6024 if (vmf->flags & FAULT_FLAG_TRIED)
6025 goto unlock;
6026 /*
6027 * This is needed only for protection faults but the arch code
6028 * is not yet telling us if this is a protection fault or not.
6029 * This still avoids useless tlb flushes for .text page faults
6030 * with threads.
6031 */
6032 if (vmf->flags & FAULT_FLAG_WRITE)
6033 flush_tlb_fix_spurious_fault(vmf->vma, vmf->address,
6034 vmf->pte);
6035 }
6036 unlock:
6037 pte_unmap_unlock(vmf->pte, vmf->ptl);
6038 return 0;
6039 }
6040
6041 /*
6042 * On entry, we hold either the VMA lock or the mmap_lock
6043 * (FAULT_FLAG_VMA_LOCK tells you which). If VM_FAULT_RETRY is set in
6044 * the result, the mmap_lock is not held on exit. See filemap_fault()
6045 * and __folio_lock_or_retry().
6046 */
__handle_mm_fault(struct vm_area_struct * vma,unsigned long address,unsigned int flags)6047 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
6048 unsigned long address, unsigned int flags)
6049 {
6050 struct vm_fault vmf = {
6051 .vma = vma,
6052 .address = address & PAGE_MASK,
6053 .real_address = address,
6054 .flags = flags,
6055 .pgoff = linear_page_index(vma, address),
6056 .gfp_mask = __get_fault_gfp_mask(vma),
6057 };
6058 struct mm_struct *mm = vma->vm_mm;
6059 unsigned long vm_flags = vma->vm_flags;
6060 pgd_t *pgd;
6061 p4d_t *p4d;
6062 vm_fault_t ret;
6063
6064 pgd = pgd_offset(mm, address);
6065 p4d = p4d_alloc(mm, pgd, address);
6066 if (!p4d)
6067 return VM_FAULT_OOM;
6068
6069 vmf.pud = pud_alloc(mm, p4d, address);
6070 if (!vmf.pud)
6071 return VM_FAULT_OOM;
6072 retry_pud:
6073 if (pud_none(*vmf.pud) &&
6074 thp_vma_allowable_order(vma, vm_flags,
6075 TVA_IN_PF | TVA_ENFORCE_SYSFS, PUD_ORDER)) {
6076 ret = create_huge_pud(&vmf);
6077 if (!(ret & VM_FAULT_FALLBACK))
6078 return ret;
6079 } else {
6080 pud_t orig_pud = *vmf.pud;
6081
6082 barrier();
6083 if (pud_trans_huge(orig_pud) || pud_devmap(orig_pud)) {
6084
6085 /*
6086 * TODO once we support anonymous PUDs: NUMA case and
6087 * FAULT_FLAG_UNSHARE handling.
6088 */
6089 if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) {
6090 ret = wp_huge_pud(&vmf, orig_pud);
6091 if (!(ret & VM_FAULT_FALLBACK))
6092 return ret;
6093 } else {
6094 huge_pud_set_accessed(&vmf, orig_pud);
6095 return 0;
6096 }
6097 }
6098 }
6099
6100 vmf.pmd = pmd_alloc(mm, vmf.pud, address);
6101 if (!vmf.pmd)
6102 return VM_FAULT_OOM;
6103
6104 /* Huge pud page fault raced with pmd_alloc? */
6105 if (pud_trans_unstable(vmf.pud))
6106 goto retry_pud;
6107
6108 if (pmd_none(*vmf.pmd) &&
6109 thp_vma_allowable_order(vma, vm_flags,
6110 TVA_IN_PF | TVA_ENFORCE_SYSFS, PMD_ORDER)) {
6111 ret = create_huge_pmd(&vmf);
6112 if (!(ret & VM_FAULT_FALLBACK))
6113 return ret;
6114 } else {
6115 vmf.orig_pmd = pmdp_get_lockless(vmf.pmd);
6116
6117 if (unlikely(is_swap_pmd(vmf.orig_pmd))) {
6118 VM_BUG_ON(thp_migration_supported() &&
6119 !is_pmd_migration_entry(vmf.orig_pmd));
6120 if (is_pmd_migration_entry(vmf.orig_pmd))
6121 pmd_migration_entry_wait(mm, vmf.pmd);
6122 return 0;
6123 }
6124 if (pmd_trans_huge(vmf.orig_pmd) || pmd_devmap(vmf.orig_pmd)) {
6125 if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma))
6126 return do_huge_pmd_numa_page(&vmf);
6127
6128 if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
6129 !pmd_write(vmf.orig_pmd)) {
6130 ret = wp_huge_pmd(&vmf);
6131 if (!(ret & VM_FAULT_FALLBACK))
6132 return ret;
6133 } else {
6134 huge_pmd_set_accessed(&vmf);
6135 return 0;
6136 }
6137 }
6138 }
6139
6140 return handle_pte_fault(&vmf);
6141 }
6142
6143 /**
6144 * mm_account_fault - Do page fault accounting
6145 * @mm: mm from which memcg should be extracted. It can be NULL.
6146 * @regs: the pt_regs struct pointer. When set to NULL, will skip accounting
6147 * of perf event counters, but we'll still do the per-task accounting to
6148 * the task who triggered this page fault.
6149 * @address: the faulted address.
6150 * @flags: the fault flags.
6151 * @ret: the fault retcode.
6152 *
6153 * This will take care of most of the page fault accounting. Meanwhile, it
6154 * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
6155 * updates. However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
6156 * still be in per-arch page fault handlers at the entry of page fault.
6157 */
mm_account_fault(struct mm_struct * mm,struct pt_regs * regs,unsigned long address,unsigned int flags,vm_fault_t ret)6158 static inline void mm_account_fault(struct mm_struct *mm, struct pt_regs *regs,
6159 unsigned long address, unsigned int flags,
6160 vm_fault_t ret)
6161 {
6162 bool major;
6163
6164 /* Incomplete faults will be accounted upon completion. */
6165 if (ret & VM_FAULT_RETRY)
6166 return;
6167
6168 /*
6169 * To preserve the behavior of older kernels, PGFAULT counters record
6170 * both successful and failed faults, as opposed to perf counters,
6171 * which ignore failed cases.
6172 */
6173 count_vm_event(PGFAULT);
6174 count_memcg_event_mm(mm, PGFAULT);
6175
6176 /*
6177 * Do not account for unsuccessful faults (e.g. when the address wasn't
6178 * valid). That includes arch_vma_access_permitted() failing before
6179 * reaching here. So this is not a "this many hardware page faults"
6180 * counter. We should use the hw profiling for that.
6181 */
6182 if (ret & VM_FAULT_ERROR)
6183 return;
6184
6185 /*
6186 * We define the fault as a major fault when the final successful fault
6187 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
6188 * handle it immediately previously).
6189 */
6190 major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
6191
6192 if (major)
6193 current->maj_flt++;
6194 else
6195 current->min_flt++;
6196
6197 /*
6198 * If the fault is done for GUP, regs will be NULL. We only do the
6199 * accounting for the per thread fault counters who triggered the
6200 * fault, and we skip the perf event updates.
6201 */
6202 if (!regs)
6203 return;
6204
6205 if (major)
6206 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
6207 else
6208 perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
6209 }
6210
6211 #ifdef CONFIG_LRU_GEN
lru_gen_enter_fault(struct vm_area_struct * vma)6212 static void lru_gen_enter_fault(struct vm_area_struct *vma)
6213 {
6214 /* the LRU algorithm only applies to accesses with recency */
6215 current->in_lru_fault = vma_has_recency(vma);
6216 }
6217
lru_gen_exit_fault(void)6218 static void lru_gen_exit_fault(void)
6219 {
6220 current->in_lru_fault = false;
6221 }
6222 #else
lru_gen_enter_fault(struct vm_area_struct * vma)6223 static void lru_gen_enter_fault(struct vm_area_struct *vma)
6224 {
6225 }
6226
lru_gen_exit_fault(void)6227 static void lru_gen_exit_fault(void)
6228 {
6229 }
6230 #endif /* CONFIG_LRU_GEN */
6231
sanitize_fault_flags(struct vm_area_struct * vma,unsigned int * flags)6232 static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma,
6233 unsigned int *flags)
6234 {
6235 if (unlikely(*flags & FAULT_FLAG_UNSHARE)) {
6236 if (WARN_ON_ONCE(*flags & FAULT_FLAG_WRITE))
6237 return VM_FAULT_SIGSEGV;
6238 /*
6239 * FAULT_FLAG_UNSHARE only applies to COW mappings. Let's
6240 * just treat it like an ordinary read-fault otherwise.
6241 */
6242 if (!is_cow_mapping(vma->vm_flags))
6243 *flags &= ~FAULT_FLAG_UNSHARE;
6244 } else if (*flags & FAULT_FLAG_WRITE) {
6245 /* Write faults on read-only mappings are impossible ... */
6246 if (WARN_ON_ONCE(!(vma->vm_flags & VM_MAYWRITE)))
6247 return VM_FAULT_SIGSEGV;
6248 /* ... and FOLL_FORCE only applies to COW mappings. */
6249 if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE) &&
6250 !is_cow_mapping(vma->vm_flags)))
6251 return VM_FAULT_SIGSEGV;
6252 }
6253 #ifdef CONFIG_PER_VMA_LOCK
6254 /*
6255 * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of
6256 * the assumption that lock is dropped on VM_FAULT_RETRY.
6257 */
6258 if (WARN_ON_ONCE((*flags &
6259 (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) ==
6260 (FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)))
6261 return VM_FAULT_SIGSEGV;
6262 #endif
6263
6264 return 0;
6265 }
6266
6267 /*
6268 * By the time we get here, we already hold either the VMA lock or the
6269 * mmap_lock (FAULT_FLAG_VMA_LOCK tells you which).
6270 *
6271 * The mmap_lock may have been released depending on flags and our
6272 * return value. See filemap_fault() and __folio_lock_or_retry().
6273 */
handle_mm_fault(struct vm_area_struct * vma,unsigned long address,unsigned int flags,struct pt_regs * regs)6274 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
6275 unsigned int flags, struct pt_regs *regs)
6276 {
6277 /* If the fault handler drops the mmap_lock, vma may be freed */
6278 struct mm_struct *mm = vma->vm_mm;
6279 vm_fault_t ret;
6280 bool is_droppable;
6281
6282 __set_current_state(TASK_RUNNING);
6283
6284 ret = sanitize_fault_flags(vma, &flags);
6285 if (ret)
6286 goto out;
6287
6288 if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
6289 flags & FAULT_FLAG_INSTRUCTION,
6290 flags & FAULT_FLAG_REMOTE)) {
6291 ret = VM_FAULT_SIGSEGV;
6292 goto out;
6293 }
6294
6295 is_droppable = !!(vma->vm_flags & VM_DROPPABLE);
6296
6297 /*
6298 * Enable the memcg OOM handling for faults triggered in user
6299 * space. Kernel faults are handled more gracefully.
6300 */
6301 if (flags & FAULT_FLAG_USER)
6302 mem_cgroup_enter_user_fault();
6303
6304 lru_gen_enter_fault(vma);
6305
6306 if (unlikely(is_vm_hugetlb_page(vma)))
6307 ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
6308 else
6309 ret = __handle_mm_fault(vma, address, flags);
6310
6311 /*
6312 * Warning: It is no longer safe to dereference vma-> after this point,
6313 * because mmap_lock might have been dropped by __handle_mm_fault(), so
6314 * vma might be destroyed from underneath us.
6315 */
6316
6317 lru_gen_exit_fault();
6318
6319 /* If the mapping is droppable, then errors due to OOM aren't fatal. */
6320 if (is_droppable)
6321 ret &= ~VM_FAULT_OOM;
6322
6323 if (flags & FAULT_FLAG_USER) {
6324 mem_cgroup_exit_user_fault();
6325 /*
6326 * The task may have entered a memcg OOM situation but
6327 * if the allocation error was handled gracefully (no
6328 * VM_FAULT_OOM), there is no need to kill anything.
6329 * Just clean up the OOM state peacefully.
6330 */
6331 if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
6332 mem_cgroup_oom_synchronize(false);
6333 }
6334 out:
6335 mm_account_fault(mm, regs, address, flags, ret);
6336
6337 return ret;
6338 }
6339 EXPORT_SYMBOL_GPL(handle_mm_fault);
6340
6341 #ifdef CONFIG_LOCK_MM_AND_FIND_VMA
6342 #include <linux/extable.h>
6343
get_mmap_lock_carefully(struct mm_struct * mm,struct pt_regs * regs)6344 static inline bool get_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs)
6345 {
6346 if (likely(mmap_read_trylock(mm)))
6347 return true;
6348
6349 if (regs && !user_mode(regs)) {
6350 unsigned long ip = exception_ip(regs);
6351 if (!search_exception_tables(ip))
6352 return false;
6353 }
6354
6355 return !mmap_read_lock_killable(mm);
6356 }
6357
mmap_upgrade_trylock(struct mm_struct * mm)6358 static inline bool mmap_upgrade_trylock(struct mm_struct *mm)
6359 {
6360 /*
6361 * We don't have this operation yet.
6362 *
6363 * It should be easy enough to do: it's basically a
6364 * atomic_long_try_cmpxchg_acquire()
6365 * from RWSEM_READER_BIAS -> RWSEM_WRITER_LOCKED, but
6366 * it also needs the proper lockdep magic etc.
6367 */
6368 return false;
6369 }
6370
upgrade_mmap_lock_carefully(struct mm_struct * mm,struct pt_regs * regs)6371 static inline bool upgrade_mmap_lock_carefully(struct mm_struct *mm, struct pt_regs *regs)
6372 {
6373 mmap_read_unlock(mm);
6374 if (regs && !user_mode(regs)) {
6375 unsigned long ip = exception_ip(regs);
6376 if (!search_exception_tables(ip))
6377 return false;
6378 }
6379 return !mmap_write_lock_killable(mm);
6380 }
6381
6382 /*
6383 * Helper for page fault handling.
6384 *
6385 * This is kind of equivalent to "mmap_read_lock()" followed
6386 * by "find_extend_vma()", except it's a lot more careful about
6387 * the locking (and will drop the lock on failure).
6388 *
6389 * For example, if we have a kernel bug that causes a page
6390 * fault, we don't want to just use mmap_read_lock() to get
6391 * the mm lock, because that would deadlock if the bug were
6392 * to happen while we're holding the mm lock for writing.
6393 *
6394 * So this checks the exception tables on kernel faults in
6395 * order to only do this all for instructions that are actually
6396 * expected to fault.
6397 *
6398 * We can also actually take the mm lock for writing if we
6399 * need to extend the vma, which helps the VM layer a lot.
6400 */
lock_mm_and_find_vma(struct mm_struct * mm,unsigned long addr,struct pt_regs * regs)6401 struct vm_area_struct *lock_mm_and_find_vma(struct mm_struct *mm,
6402 unsigned long addr, struct pt_regs *regs)
6403 {
6404 struct vm_area_struct *vma;
6405
6406 if (!get_mmap_lock_carefully(mm, regs))
6407 return NULL;
6408
6409 vma = find_vma(mm, addr);
6410 if (likely(vma && (vma->vm_start <= addr)))
6411 return vma;
6412
6413 /*
6414 * Well, dang. We might still be successful, but only
6415 * if we can extend a vma to do so.
6416 */
6417 if (!vma || !(vma->vm_flags & VM_GROWSDOWN)) {
6418 mmap_read_unlock(mm);
6419 return NULL;
6420 }
6421
6422 /*
6423 * We can try to upgrade the mmap lock atomically,
6424 * in which case we can continue to use the vma
6425 * we already looked up.
6426 *
6427 * Otherwise we'll have to drop the mmap lock and
6428 * re-take it, and also look up the vma again,
6429 * re-checking it.
6430 */
6431 if (!mmap_upgrade_trylock(mm)) {
6432 if (!upgrade_mmap_lock_carefully(mm, regs))
6433 return NULL;
6434
6435 vma = find_vma(mm, addr);
6436 if (!vma)
6437 goto fail;
6438 if (vma->vm_start <= addr)
6439 goto success;
6440 if (!(vma->vm_flags & VM_GROWSDOWN))
6441 goto fail;
6442 }
6443
6444 if (expand_stack_locked(vma, addr))
6445 goto fail;
6446
6447 success:
6448 mmap_write_downgrade(mm);
6449 return vma;
6450
6451 fail:
6452 mmap_write_unlock(mm);
6453 return NULL;
6454 }
6455 #endif
6456
6457 #ifdef CONFIG_PER_VMA_LOCK
__vma_enter_locked(struct vm_area_struct * vma,bool detaching)6458 static inline bool __vma_enter_locked(struct vm_area_struct *vma, bool detaching)
6459 {
6460 unsigned int tgt_refcnt = VMA_LOCK_OFFSET;
6461
6462 /* Additional refcnt if the vma is attached. */
6463 if (!detaching)
6464 tgt_refcnt++;
6465
6466 /*
6467 * If vma is detached then only vma_mark_attached() can raise the
6468 * vm_refcnt. mmap_write_lock prevents racing with vma_mark_attached().
6469 */
6470 if (!refcount_add_not_zero(VMA_LOCK_OFFSET, &vma->vm_refcnt))
6471 return false;
6472
6473 rwsem_acquire(&vma->vmlock_dep_map, 0, 0, _RET_IP_);
6474 rcuwait_wait_event(&vma->vm_mm->vma_writer_wait,
6475 refcount_read(&vma->vm_refcnt) == tgt_refcnt,
6476 TASK_UNINTERRUPTIBLE);
6477 lock_acquired(&vma->vmlock_dep_map, _RET_IP_);
6478
6479 return true;
6480 }
6481
__vma_exit_locked(struct vm_area_struct * vma,bool * detached)6482 static inline void __vma_exit_locked(struct vm_area_struct *vma, bool *detached)
6483 {
6484 *detached = refcount_sub_and_test(VMA_LOCK_OFFSET, &vma->vm_refcnt);
6485 rwsem_release(&vma->vmlock_dep_map, _RET_IP_);
6486 }
6487
__vma_start_write(struct vm_area_struct * vma,unsigned int mm_lock_seq)6488 void __vma_start_write(struct vm_area_struct *vma, unsigned int mm_lock_seq)
6489 {
6490 bool locked;
6491
6492 /*
6493 * __vma_enter_locked() returns false immediately if the vma is not
6494 * attached, otherwise it waits until refcnt is indicating that vma
6495 * is attached with no readers.
6496 */
6497 locked = __vma_enter_locked(vma, false);
6498
6499 /*
6500 * We should use WRITE_ONCE() here because we can have concurrent reads
6501 * from the early lockless pessimistic check in vma_start_read().
6502 * We don't really care about the correctness of that early check, but
6503 * we should use WRITE_ONCE() for cleanliness and to keep KCSAN happy.
6504 */
6505 WRITE_ONCE(vma->vm_lock_seq, mm_lock_seq);
6506
6507 if (locked) {
6508 bool detached;
6509
6510 __vma_exit_locked(vma, &detached);
6511 WARN_ON_ONCE(detached); /* vma should remain attached */
6512 }
6513 }
6514 EXPORT_SYMBOL_GPL(__vma_start_write);
6515
vma_mark_detached(struct vm_area_struct * vma)6516 void vma_mark_detached(struct vm_area_struct *vma)
6517 {
6518 vma_assert_write_locked(vma);
6519 vma_assert_attached(vma);
6520
6521 /*
6522 * We are the only writer, so no need to use vma_refcount_put().
6523 * The condition below is unlikely because the vma has been already
6524 * write-locked and readers can increment vm_refcnt only temporarily
6525 * before they check vm_lock_seq, realize the vma is locked and drop
6526 * back the vm_refcnt. That is a narrow window for observing a raised
6527 * vm_refcnt.
6528 */
6529 if (unlikely(!refcount_dec_and_test(&vma->vm_refcnt))) {
6530 /* Wait until vma is detached with no readers. */
6531 if (__vma_enter_locked(vma, true)) {
6532 bool detached;
6533
6534 __vma_exit_locked(vma, &detached);
6535 WARN_ON_ONCE(!detached);
6536 }
6537 }
6538 }
6539
6540 /*
6541 * Lookup and lock a VMA under RCU protection. Returned VMA is guaranteed to be
6542 * stable and not isolated. If the VMA is not found or is being modified the
6543 * function returns NULL.
6544 */
lock_vma_under_rcu(struct mm_struct * mm,unsigned long address)6545 struct vm_area_struct *lock_vma_under_rcu(struct mm_struct *mm,
6546 unsigned long address)
6547 {
6548 MA_STATE(mas, &mm->mm_mt, address, address);
6549 struct vm_area_struct *vma;
6550
6551 rcu_read_lock();
6552 retry:
6553 vma = mas_walk(&mas);
6554 if (!vma)
6555 goto inval;
6556
6557 vma = vma_start_read(mm, vma);
6558 if (IS_ERR_OR_NULL(vma)) {
6559 /* Check if the VMA got isolated after we found it */
6560 if (PTR_ERR(vma) == -EAGAIN) {
6561 count_vm_vma_lock_event(VMA_LOCK_MISS);
6562 /* The area was replaced with another one */
6563 goto retry;
6564 }
6565
6566 /* Failed to lock the VMA */
6567 goto inval;
6568 }
6569 /*
6570 * At this point, we have a stable reference to a VMA: The VMA is
6571 * locked and we know it hasn't already been isolated.
6572 * From here on, we can access the VMA without worrying about which
6573 * fields are accessible for RCU readers.
6574 */
6575
6576 /* Check if the vma we locked is the right one. */
6577 if (unlikely(vma->vm_mm != mm ||
6578 address < vma->vm_start || address >= vma->vm_end))
6579 goto inval_end_read;
6580
6581 rcu_read_unlock();
6582 return vma;
6583
6584 inval_end_read:
6585 vma_end_read(vma);
6586 inval:
6587 rcu_read_unlock();
6588 count_vm_vma_lock_event(VMA_LOCK_ABORT);
6589 return NULL;
6590 }
6591 #endif /* CONFIG_PER_VMA_LOCK */
6592
6593 #ifndef __PAGETABLE_P4D_FOLDED
6594 /*
6595 * Allocate p4d page table.
6596 * We've already handled the fast-path in-line.
6597 */
__p4d_alloc(struct mm_struct * mm,pgd_t * pgd,unsigned long address)6598 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
6599 {
6600 p4d_t *new = p4d_alloc_one(mm, address);
6601 if (!new)
6602 return -ENOMEM;
6603
6604 spin_lock(&mm->page_table_lock);
6605 if (pgd_present(*pgd)) { /* Another has populated it */
6606 p4d_free(mm, new);
6607 } else {
6608 smp_wmb(); /* See comment in pmd_install() */
6609 pgd_populate(mm, pgd, new);
6610 }
6611 spin_unlock(&mm->page_table_lock);
6612 return 0;
6613 }
6614 #endif /* __PAGETABLE_P4D_FOLDED */
6615
6616 #ifndef __PAGETABLE_PUD_FOLDED
6617 /*
6618 * Allocate page upper directory.
6619 * We've already handled the fast-path in-line.
6620 */
__pud_alloc(struct mm_struct * mm,p4d_t * p4d,unsigned long address)6621 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
6622 {
6623 pud_t *new = pud_alloc_one(mm, address);
6624 if (!new)
6625 return -ENOMEM;
6626
6627 spin_lock(&mm->page_table_lock);
6628 if (!p4d_present(*p4d)) {
6629 mm_inc_nr_puds(mm);
6630 smp_wmb(); /* See comment in pmd_install() */
6631 p4d_populate(mm, p4d, new);
6632 } else /* Another has populated it */
6633 pud_free(mm, new);
6634 spin_unlock(&mm->page_table_lock);
6635 return 0;
6636 }
6637 #endif /* __PAGETABLE_PUD_FOLDED */
6638
6639 #ifndef __PAGETABLE_PMD_FOLDED
6640 /*
6641 * Allocate page middle directory.
6642 * We've already handled the fast-path in-line.
6643 */
__pmd_alloc(struct mm_struct * mm,pud_t * pud,unsigned long address)6644 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
6645 {
6646 spinlock_t *ptl;
6647 pmd_t *new = pmd_alloc_one(mm, address);
6648 if (!new)
6649 return -ENOMEM;
6650
6651 ptl = pud_lock(mm, pud);
6652 if (!pud_present(*pud)) {
6653 mm_inc_nr_pmds(mm);
6654 smp_wmb(); /* See comment in pmd_install() */
6655 pud_populate(mm, pud, new);
6656 } else { /* Another has populated it */
6657 pmd_free(mm, new);
6658 }
6659 spin_unlock(ptl);
6660 return 0;
6661 }
6662 #endif /* __PAGETABLE_PMD_FOLDED */
6663
pfnmap_args_setup(struct follow_pfnmap_args * args,spinlock_t * lock,pte_t * ptep,pgprot_t pgprot,unsigned long pfn_base,unsigned long addr_mask,bool writable,bool special)6664 static inline void pfnmap_args_setup(struct follow_pfnmap_args *args,
6665 spinlock_t *lock, pte_t *ptep,
6666 pgprot_t pgprot, unsigned long pfn_base,
6667 unsigned long addr_mask, bool writable,
6668 bool special)
6669 {
6670 args->lock = lock;
6671 args->ptep = ptep;
6672 args->pfn = pfn_base + ((args->address & ~addr_mask) >> PAGE_SHIFT);
6673 args->addr_mask = addr_mask;
6674 args->pgprot = pgprot;
6675 args->writable = writable;
6676 args->special = special;
6677 }
6678
pfnmap_lockdep_assert(struct vm_area_struct * vma)6679 static inline void pfnmap_lockdep_assert(struct vm_area_struct *vma)
6680 {
6681 #ifdef CONFIG_LOCKDEP
6682 struct file *file = vma->vm_file;
6683 struct address_space *mapping = file ? file->f_mapping : NULL;
6684
6685 if (mapping)
6686 lockdep_assert(lockdep_is_held(&mapping->i_mmap_rwsem) ||
6687 lockdep_is_held(&vma->vm_mm->mmap_lock));
6688 else
6689 lockdep_assert(lockdep_is_held(&vma->vm_mm->mmap_lock));
6690 #endif
6691 }
6692
6693 /**
6694 * follow_pfnmap_start() - Look up a pfn mapping at a user virtual address
6695 * @args: Pointer to struct @follow_pfnmap_args
6696 *
6697 * The caller needs to setup args->vma and args->address to point to the
6698 * virtual address as the target of such lookup. On a successful return,
6699 * the results will be put into other output fields.
6700 *
6701 * After the caller finished using the fields, the caller must invoke
6702 * another follow_pfnmap_end() to proper releases the locks and resources
6703 * of such look up request.
6704 *
6705 * During the start() and end() calls, the results in @args will be valid
6706 * as proper locks will be held. After the end() is called, all the fields
6707 * in @follow_pfnmap_args will be invalid to be further accessed. Further
6708 * use of such information after end() may require proper synchronizations
6709 * by the caller with page table updates, otherwise it can create a
6710 * security bug.
6711 *
6712 * If the PTE maps a refcounted page, callers are responsible to protect
6713 * against invalidation with MMU notifiers; otherwise access to the PFN at
6714 * a later point in time can trigger use-after-free.
6715 *
6716 * Only IO mappings and raw PFN mappings are allowed. The mmap semaphore
6717 * should be taken for read, and the mmap semaphore cannot be released
6718 * before the end() is invoked.
6719 *
6720 * This function must not be used to modify PTE content.
6721 *
6722 * Return: zero on success, negative otherwise.
6723 */
follow_pfnmap_start(struct follow_pfnmap_args * args)6724 int follow_pfnmap_start(struct follow_pfnmap_args *args)
6725 {
6726 struct vm_area_struct *vma = args->vma;
6727 unsigned long address = args->address;
6728 struct mm_struct *mm = vma->vm_mm;
6729 spinlock_t *lock;
6730 pgd_t *pgdp;
6731 p4d_t *p4dp, p4d;
6732 pud_t *pudp, pud;
6733 pmd_t *pmdp, pmd;
6734 pte_t *ptep, pte;
6735
6736 pfnmap_lockdep_assert(vma);
6737
6738 if (unlikely(address < vma->vm_start || address >= vma->vm_end))
6739 goto out;
6740
6741 if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
6742 goto out;
6743 retry:
6744 pgdp = pgd_offset(mm, address);
6745 if (pgd_none(*pgdp) || unlikely(pgd_bad(*pgdp)))
6746 goto out;
6747
6748 p4dp = p4d_offset(pgdp, address);
6749 p4d = READ_ONCE(*p4dp);
6750 if (p4d_none(p4d) || unlikely(p4d_bad(p4d)))
6751 goto out;
6752
6753 pudp = pud_offset(p4dp, address);
6754 pud = READ_ONCE(*pudp);
6755 if (pud_none(pud))
6756 goto out;
6757 if (pud_leaf(pud)) {
6758 lock = pud_lock(mm, pudp);
6759 if (!unlikely(pud_leaf(pud))) {
6760 spin_unlock(lock);
6761 goto retry;
6762 }
6763 pfnmap_args_setup(args, lock, NULL, pud_pgprot(pud),
6764 pud_pfn(pud), PUD_MASK, pud_write(pud),
6765 pud_special(pud));
6766 return 0;
6767 }
6768
6769 pmdp = pmd_offset(pudp, address);
6770 pmd = pmdp_get_lockless(pmdp);
6771 if (pmd_leaf(pmd)) {
6772 lock = pmd_lock(mm, pmdp);
6773 if (!unlikely(pmd_leaf(pmd))) {
6774 spin_unlock(lock);
6775 goto retry;
6776 }
6777 pfnmap_args_setup(args, lock, NULL, pmd_pgprot(pmd),
6778 pmd_pfn(pmd), PMD_MASK, pmd_write(pmd),
6779 pmd_special(pmd));
6780 return 0;
6781 }
6782
6783 ptep = pte_offset_map_lock(mm, pmdp, address, &lock);
6784 if (!ptep)
6785 goto out;
6786 pte = ptep_get(ptep);
6787 if (!pte_present(pte))
6788 goto unlock;
6789 pfnmap_args_setup(args, lock, ptep, pte_pgprot(pte),
6790 pte_pfn(pte), PAGE_MASK, pte_write(pte),
6791 pte_special(pte));
6792 return 0;
6793 unlock:
6794 pte_unmap_unlock(ptep, lock);
6795 out:
6796 return -EINVAL;
6797 }
6798 EXPORT_SYMBOL_GPL(follow_pfnmap_start);
6799
6800 /**
6801 * follow_pfnmap_end(): End a follow_pfnmap_start() process
6802 * @args: Pointer to struct @follow_pfnmap_args
6803 *
6804 * Must be used in pair of follow_pfnmap_start(). See the start() function
6805 * above for more information.
6806 */
follow_pfnmap_end(struct follow_pfnmap_args * args)6807 void follow_pfnmap_end(struct follow_pfnmap_args *args)
6808 {
6809 if (args->lock)
6810 spin_unlock(args->lock);
6811 if (args->ptep)
6812 pte_unmap(args->ptep);
6813 }
6814 EXPORT_SYMBOL_GPL(follow_pfnmap_end);
6815
6816 #ifdef CONFIG_HAVE_IOREMAP_PROT
6817 /**
6818 * generic_access_phys - generic implementation for iomem mmap access
6819 * @vma: the vma to access
6820 * @addr: userspace address, not relative offset within @vma
6821 * @buf: buffer to read/write
6822 * @len: length of transfer
6823 * @write: set to FOLL_WRITE when writing, otherwise reading
6824 *
6825 * This is a generic implementation for &vm_operations_struct.access for an
6826 * iomem mapping. This callback is used by access_process_vm() when the @vma is
6827 * not page based.
6828 */
generic_access_phys(struct vm_area_struct * vma,unsigned long addr,void * buf,int len,int write)6829 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
6830 void *buf, int len, int write)
6831 {
6832 resource_size_t phys_addr;
6833 pgprot_t prot = __pgprot(0);
6834 void __iomem *maddr;
6835 int offset = offset_in_page(addr);
6836 int ret = -EINVAL;
6837 bool writable;
6838 struct follow_pfnmap_args args = { .vma = vma, .address = addr };
6839
6840 retry:
6841 if (follow_pfnmap_start(&args))
6842 return -EINVAL;
6843 prot = args.pgprot;
6844 phys_addr = (resource_size_t)args.pfn << PAGE_SHIFT;
6845 writable = args.writable;
6846 follow_pfnmap_end(&args);
6847
6848 if ((write & FOLL_WRITE) && !writable)
6849 return -EINVAL;
6850
6851 maddr = ioremap_prot(phys_addr, PAGE_ALIGN(len + offset), prot);
6852 if (!maddr)
6853 return -ENOMEM;
6854
6855 if (follow_pfnmap_start(&args))
6856 goto out_unmap;
6857
6858 if ((pgprot_val(prot) != pgprot_val(args.pgprot)) ||
6859 (phys_addr != (args.pfn << PAGE_SHIFT)) ||
6860 (writable != args.writable)) {
6861 follow_pfnmap_end(&args);
6862 iounmap(maddr);
6863 goto retry;
6864 }
6865
6866 if (write)
6867 memcpy_toio(maddr + offset, buf, len);
6868 else
6869 memcpy_fromio(buf, maddr + offset, len);
6870 ret = len;
6871 follow_pfnmap_end(&args);
6872 out_unmap:
6873 iounmap(maddr);
6874
6875 return ret;
6876 }
6877 EXPORT_SYMBOL_GPL(generic_access_phys);
6878 #endif
6879
6880 /*
6881 * Access another process' address space as given in mm.
6882 */
__access_remote_vm(struct mm_struct * mm,unsigned long addr,void * buf,int len,unsigned int gup_flags)6883 static int __access_remote_vm(struct mm_struct *mm, unsigned long addr,
6884 void *buf, int len, unsigned int gup_flags)
6885 {
6886 void *old_buf = buf;
6887 int write = gup_flags & FOLL_WRITE;
6888
6889 if (mmap_read_lock_killable(mm))
6890 return 0;
6891
6892 /* Untag the address before looking up the VMA */
6893 addr = untagged_addr_remote(mm, addr);
6894
6895 /* Avoid triggering the temporary warning in __get_user_pages */
6896 if (!vma_lookup(mm, addr) && !expand_stack(mm, addr))
6897 return 0;
6898
6899 /* ignore errors, just check how much was successfully transferred */
6900 while (len) {
6901 int bytes, offset;
6902 void *maddr;
6903 struct vm_area_struct *vma = NULL;
6904 struct page *page = get_user_page_vma_remote(mm, addr,
6905 gup_flags, &vma);
6906
6907 if (IS_ERR(page)) {
6908 /* We might need to expand the stack to access it */
6909 vma = vma_lookup(mm, addr);
6910 if (!vma) {
6911 vma = expand_stack(mm, addr);
6912
6913 /* mmap_lock was dropped on failure */
6914 if (!vma)
6915 return buf - old_buf;
6916
6917 /* Try again if stack expansion worked */
6918 continue;
6919 }
6920
6921 /*
6922 * Check if this is a VM_IO | VM_PFNMAP VMA, which
6923 * we can access using slightly different code.
6924 */
6925 bytes = 0;
6926 #ifdef CONFIG_HAVE_IOREMAP_PROT
6927 if (vma->vm_ops && vma->vm_ops->access)
6928 bytes = vma->vm_ops->access(vma, addr, buf,
6929 len, write);
6930 #endif
6931 if (bytes <= 0)
6932 break;
6933 } else {
6934 bytes = len;
6935 offset = addr & (PAGE_SIZE-1);
6936 if (bytes > PAGE_SIZE-offset)
6937 bytes = PAGE_SIZE-offset;
6938
6939 maddr = kmap_local_page(page);
6940 if (write) {
6941 copy_to_user_page(vma, page, addr,
6942 maddr + offset, buf, bytes);
6943 set_page_dirty_lock(page);
6944 } else {
6945 copy_from_user_page(vma, page, addr,
6946 buf, maddr + offset, bytes);
6947 }
6948 unmap_and_put_page(page, maddr);
6949 }
6950 len -= bytes;
6951 buf += bytes;
6952 addr += bytes;
6953 }
6954 mmap_read_unlock(mm);
6955
6956 return buf - old_buf;
6957 }
6958
6959 /**
6960 * access_remote_vm - access another process' address space
6961 * @mm: the mm_struct of the target address space
6962 * @addr: start address to access
6963 * @buf: source or destination buffer
6964 * @len: number of bytes to transfer
6965 * @gup_flags: flags modifying lookup behaviour
6966 *
6967 * The caller must hold a reference on @mm.
6968 *
6969 * Return: number of bytes copied from source to destination.
6970 */
access_remote_vm(struct mm_struct * mm,unsigned long addr,void * buf,int len,unsigned int gup_flags)6971 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
6972 void *buf, int len, unsigned int gup_flags)
6973 {
6974 return __access_remote_vm(mm, addr, buf, len, gup_flags);
6975 }
6976
6977 /*
6978 * Access another process' address space.
6979 * Source/target buffer must be kernel space,
6980 * Do not walk the page table directly, use get_user_pages
6981 */
access_process_vm(struct task_struct * tsk,unsigned long addr,void * buf,int len,unsigned int gup_flags)6982 int access_process_vm(struct task_struct *tsk, unsigned long addr,
6983 void *buf, int len, unsigned int gup_flags)
6984 {
6985 struct mm_struct *mm;
6986 int ret;
6987
6988 mm = get_task_mm(tsk);
6989 if (!mm)
6990 return 0;
6991
6992 ret = __access_remote_vm(mm, addr, buf, len, gup_flags);
6993
6994 mmput(mm);
6995
6996 return ret;
6997 }
6998 EXPORT_SYMBOL_GPL(access_process_vm);
6999
7000 #ifdef CONFIG_BPF_SYSCALL
7001 /*
7002 * Copy a string from another process's address space as given in mm.
7003 * If there is any error return -EFAULT.
7004 */
__copy_remote_vm_str(struct mm_struct * mm,unsigned long addr,void * buf,int len,unsigned int gup_flags)7005 static int __copy_remote_vm_str(struct mm_struct *mm, unsigned long addr,
7006 void *buf, int len, unsigned int gup_flags)
7007 {
7008 void *old_buf = buf;
7009 int err = 0;
7010
7011 *(char *)buf = '\0';
7012
7013 if (mmap_read_lock_killable(mm))
7014 return -EFAULT;
7015
7016 addr = untagged_addr_remote(mm, addr);
7017
7018 /* Avoid triggering the temporary warning in __get_user_pages */
7019 if (!vma_lookup(mm, addr)) {
7020 err = -EFAULT;
7021 goto out;
7022 }
7023
7024 while (len) {
7025 int bytes, offset, retval;
7026 void *maddr;
7027 struct page *page;
7028 struct vm_area_struct *vma = NULL;
7029
7030 page = get_user_page_vma_remote(mm, addr, gup_flags, &vma);
7031 if (IS_ERR(page)) {
7032 /*
7033 * Treat as a total failure for now until we decide how
7034 * to handle the CONFIG_HAVE_IOREMAP_PROT case and
7035 * stack expansion.
7036 */
7037 *(char *)buf = '\0';
7038 err = -EFAULT;
7039 goto out;
7040 }
7041
7042 bytes = len;
7043 offset = addr & (PAGE_SIZE - 1);
7044 if (bytes > PAGE_SIZE - offset)
7045 bytes = PAGE_SIZE - offset;
7046
7047 maddr = kmap_local_page(page);
7048 retval = strscpy(buf, maddr + offset, bytes);
7049 if (retval >= 0) {
7050 /* Found the end of the string */
7051 buf += retval;
7052 unmap_and_put_page(page, maddr);
7053 break;
7054 }
7055
7056 buf += bytes - 1;
7057 /*
7058 * Because strscpy always NUL terminates we need to
7059 * copy the last byte in the page if we are going to
7060 * load more pages
7061 */
7062 if (bytes != len) {
7063 addr += bytes - 1;
7064 copy_from_user_page(vma, page, addr, buf, maddr + (PAGE_SIZE - 1), 1);
7065 buf += 1;
7066 addr += 1;
7067 }
7068 len -= bytes;
7069
7070 unmap_and_put_page(page, maddr);
7071 }
7072
7073 out:
7074 mmap_read_unlock(mm);
7075 if (err)
7076 return err;
7077 return buf - old_buf;
7078 }
7079
7080 /**
7081 * copy_remote_vm_str - copy a string from another process's address space.
7082 * @tsk: the task of the target address space
7083 * @addr: start address to read from
7084 * @buf: destination buffer
7085 * @len: number of bytes to copy
7086 * @gup_flags: flags modifying lookup behaviour
7087 *
7088 * The caller must hold a reference on @mm.
7089 *
7090 * Return: number of bytes copied from @addr (source) to @buf (destination);
7091 * not including the trailing NUL. Always guaranteed to leave NUL-terminated
7092 * buffer. On any error, return -EFAULT.
7093 */
copy_remote_vm_str(struct task_struct * tsk,unsigned long addr,void * buf,int len,unsigned int gup_flags)7094 int copy_remote_vm_str(struct task_struct *tsk, unsigned long addr,
7095 void *buf, int len, unsigned int gup_flags)
7096 {
7097 struct mm_struct *mm;
7098 int ret;
7099
7100 if (unlikely(len == 0))
7101 return 0;
7102
7103 mm = get_task_mm(tsk);
7104 if (!mm) {
7105 *(char *)buf = '\0';
7106 return -EFAULT;
7107 }
7108
7109 ret = __copy_remote_vm_str(mm, addr, buf, len, gup_flags);
7110
7111 mmput(mm);
7112
7113 return ret;
7114 }
7115 EXPORT_SYMBOL_GPL(copy_remote_vm_str);
7116 #endif /* CONFIG_BPF_SYSCALL */
7117
7118 /*
7119 * Print the name of a VMA.
7120 */
print_vma_addr(char * prefix,unsigned long ip)7121 void print_vma_addr(char *prefix, unsigned long ip)
7122 {
7123 struct mm_struct *mm = current->mm;
7124 struct vm_area_struct *vma;
7125
7126 /*
7127 * we might be running from an atomic context so we cannot sleep
7128 */
7129 if (!mmap_read_trylock(mm))
7130 return;
7131
7132 vma = vma_lookup(mm, ip);
7133 if (vma && vma->vm_file) {
7134 struct file *f = vma->vm_file;
7135 ip -= vma->vm_start;
7136 ip += vma->vm_pgoff << PAGE_SHIFT;
7137 printk("%s%pD[%lx,%lx+%lx]", prefix, f, ip,
7138 vma->vm_start,
7139 vma->vm_end - vma->vm_start);
7140 }
7141 mmap_read_unlock(mm);
7142 }
7143
7144 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
__might_fault(const char * file,int line)7145 void __might_fault(const char *file, int line)
7146 {
7147 if (pagefault_disabled())
7148 return;
7149 __might_sleep(file, line);
7150 if (current->mm)
7151 might_lock_read(¤t->mm->mmap_lock);
7152 }
7153 EXPORT_SYMBOL(__might_fault);
7154 #endif
7155
7156 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
7157 /*
7158 * Process all subpages of the specified huge page with the specified
7159 * operation. The target subpage will be processed last to keep its
7160 * cache lines hot.
7161 */
process_huge_page(unsigned long addr_hint,unsigned int nr_pages,int (* process_subpage)(unsigned long addr,int idx,void * arg),void * arg)7162 static inline int process_huge_page(
7163 unsigned long addr_hint, unsigned int nr_pages,
7164 int (*process_subpage)(unsigned long addr, int idx, void *arg),
7165 void *arg)
7166 {
7167 int i, n, base, l, ret;
7168 unsigned long addr = addr_hint &
7169 ~(((unsigned long)nr_pages << PAGE_SHIFT) - 1);
7170
7171 /* Process target subpage last to keep its cache lines hot */
7172 might_sleep();
7173 n = (addr_hint - addr) / PAGE_SIZE;
7174 if (2 * n <= nr_pages) {
7175 /* If target subpage in first half of huge page */
7176 base = 0;
7177 l = n;
7178 /* Process subpages at the end of huge page */
7179 for (i = nr_pages - 1; i >= 2 * n; i--) {
7180 cond_resched();
7181 ret = process_subpage(addr + i * PAGE_SIZE, i, arg);
7182 if (ret)
7183 return ret;
7184 }
7185 } else {
7186 /* If target subpage in second half of huge page */
7187 base = nr_pages - 2 * (nr_pages - n);
7188 l = nr_pages - n;
7189 /* Process subpages at the begin of huge page */
7190 for (i = 0; i < base; i++) {
7191 cond_resched();
7192 ret = process_subpage(addr + i * PAGE_SIZE, i, arg);
7193 if (ret)
7194 return ret;
7195 }
7196 }
7197 /*
7198 * Process remaining subpages in left-right-left-right pattern
7199 * towards the target subpage
7200 */
7201 for (i = 0; i < l; i++) {
7202 int left_idx = base + i;
7203 int right_idx = base + 2 * l - 1 - i;
7204
7205 cond_resched();
7206 ret = process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
7207 if (ret)
7208 return ret;
7209 cond_resched();
7210 ret = process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
7211 if (ret)
7212 return ret;
7213 }
7214 return 0;
7215 }
7216
clear_gigantic_page(struct folio * folio,unsigned long addr_hint,unsigned int nr_pages)7217 static void clear_gigantic_page(struct folio *folio, unsigned long addr_hint,
7218 unsigned int nr_pages)
7219 {
7220 unsigned long addr = ALIGN_DOWN(addr_hint, folio_size(folio));
7221 int i;
7222
7223 might_sleep();
7224 for (i = 0; i < nr_pages; i++) {
7225 cond_resched();
7226 clear_user_highpage(folio_page(folio, i), addr + i * PAGE_SIZE);
7227 }
7228 }
7229
clear_subpage(unsigned long addr,int idx,void * arg)7230 static int clear_subpage(unsigned long addr, int idx, void *arg)
7231 {
7232 struct folio *folio = arg;
7233
7234 clear_user_highpage(folio_page(folio, idx), addr);
7235 return 0;
7236 }
7237
7238 /**
7239 * folio_zero_user - Zero a folio which will be mapped to userspace.
7240 * @folio: The folio to zero.
7241 * @addr_hint: The address will be accessed or the base address if uncelar.
7242 */
folio_zero_user(struct folio * folio,unsigned long addr_hint)7243 void folio_zero_user(struct folio *folio, unsigned long addr_hint)
7244 {
7245 unsigned int nr_pages = folio_nr_pages(folio);
7246
7247 if (unlikely(nr_pages > MAX_ORDER_NR_PAGES))
7248 clear_gigantic_page(folio, addr_hint, nr_pages);
7249 else
7250 process_huge_page(addr_hint, nr_pages, clear_subpage, folio);
7251 }
7252
copy_user_gigantic_page(struct folio * dst,struct folio * src,unsigned long addr_hint,struct vm_area_struct * vma,unsigned int nr_pages)7253 static int copy_user_gigantic_page(struct folio *dst, struct folio *src,
7254 unsigned long addr_hint,
7255 struct vm_area_struct *vma,
7256 unsigned int nr_pages)
7257 {
7258 unsigned long addr = ALIGN_DOWN(addr_hint, folio_size(dst));
7259 struct page *dst_page;
7260 struct page *src_page;
7261 int i;
7262
7263 for (i = 0; i < nr_pages; i++) {
7264 dst_page = folio_page(dst, i);
7265 src_page = folio_page(src, i);
7266
7267 cond_resched();
7268 if (copy_mc_user_highpage(dst_page, src_page,
7269 addr + i*PAGE_SIZE, vma))
7270 return -EHWPOISON;
7271 }
7272 return 0;
7273 }
7274
7275 struct copy_subpage_arg {
7276 struct folio *dst;
7277 struct folio *src;
7278 struct vm_area_struct *vma;
7279 };
7280
copy_subpage(unsigned long addr,int idx,void * arg)7281 static int copy_subpage(unsigned long addr, int idx, void *arg)
7282 {
7283 struct copy_subpage_arg *copy_arg = arg;
7284 struct page *dst = folio_page(copy_arg->dst, idx);
7285 struct page *src = folio_page(copy_arg->src, idx);
7286
7287 if (copy_mc_user_highpage(dst, src, addr, copy_arg->vma))
7288 return -EHWPOISON;
7289 return 0;
7290 }
7291
copy_user_large_folio(struct folio * dst,struct folio * src,unsigned long addr_hint,struct vm_area_struct * vma)7292 int copy_user_large_folio(struct folio *dst, struct folio *src,
7293 unsigned long addr_hint, struct vm_area_struct *vma)
7294 {
7295 unsigned int nr_pages = folio_nr_pages(dst);
7296 struct copy_subpage_arg arg = {
7297 .dst = dst,
7298 .src = src,
7299 .vma = vma,
7300 };
7301
7302 if (unlikely(nr_pages > MAX_ORDER_NR_PAGES))
7303 return copy_user_gigantic_page(dst, src, addr_hint, vma, nr_pages);
7304
7305 return process_huge_page(addr_hint, nr_pages, copy_subpage, &arg);
7306 }
7307
copy_folio_from_user(struct folio * dst_folio,const void __user * usr_src,bool allow_pagefault)7308 long copy_folio_from_user(struct folio *dst_folio,
7309 const void __user *usr_src,
7310 bool allow_pagefault)
7311 {
7312 void *kaddr;
7313 unsigned long i, rc = 0;
7314 unsigned int nr_pages = folio_nr_pages(dst_folio);
7315 unsigned long ret_val = nr_pages * PAGE_SIZE;
7316 struct page *subpage;
7317
7318 for (i = 0; i < nr_pages; i++) {
7319 subpage = folio_page(dst_folio, i);
7320 kaddr = kmap_local_page(subpage);
7321 if (!allow_pagefault)
7322 pagefault_disable();
7323 rc = copy_from_user(kaddr, usr_src + i * PAGE_SIZE, PAGE_SIZE);
7324 if (!allow_pagefault)
7325 pagefault_enable();
7326 kunmap_local(kaddr);
7327
7328 ret_val -= (PAGE_SIZE - rc);
7329 if (rc)
7330 break;
7331
7332 flush_dcache_page(subpage);
7333
7334 cond_resched();
7335 }
7336 return ret_val;
7337 }
7338 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
7339
7340 #if defined(CONFIG_SPLIT_PTE_PTLOCKS) && ALLOC_SPLIT_PTLOCKS
7341
7342 static struct kmem_cache *page_ptl_cachep;
7343
ptlock_cache_init(void)7344 void __init ptlock_cache_init(void)
7345 {
7346 page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
7347 SLAB_PANIC, NULL);
7348 }
7349
ptlock_alloc(struct ptdesc * ptdesc)7350 bool ptlock_alloc(struct ptdesc *ptdesc)
7351 {
7352 spinlock_t *ptl;
7353
7354 ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
7355 if (!ptl)
7356 return false;
7357 ptdesc->ptl = ptl;
7358 return true;
7359 }
7360
ptlock_free(struct ptdesc * ptdesc)7361 void ptlock_free(struct ptdesc *ptdesc)
7362 {
7363 if (ptdesc->ptl)
7364 kmem_cache_free(page_ptl_cachep, ptdesc->ptl);
7365 }
7366 #endif
7367
vma_pgtable_walk_begin(struct vm_area_struct * vma)7368 void vma_pgtable_walk_begin(struct vm_area_struct *vma)
7369 {
7370 if (is_vm_hugetlb_page(vma))
7371 hugetlb_vma_lock_read(vma);
7372 }
7373
vma_pgtable_walk_end(struct vm_area_struct * vma)7374 void vma_pgtable_walk_end(struct vm_area_struct *vma)
7375 {
7376 if (is_vm_hugetlb_page(vma))
7377 hugetlb_vma_unlock_read(vma);
7378 }
7379