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