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