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