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