xref: /linux/mm/memory.c (revision a643a82e27eeb681cff6f8c1270eb565579d6157)
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_can_delay_rmap()) {
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 			entry = pte_mkdirty(entry);
4153 			if (pte_soft_dirty(vmf->orig_pte))
4154 				entry = pte_mksoft_dirty(entry);
4155 			else
4156 				entry = pte_clear_soft_dirty(entry);
4157 			if (pte_uffd(vmf->orig_pte)) {
4158 				entry = pte_mkuffd(entry);
4159 				if (userfaultfd_rwp(vma))
4160 					entry = pte_modify(entry, PAGE_NONE);
4161 			}
4162 		} else {
4163 			entry = maybe_mkwrite(pte_mkdirty(entry), vma);
4164 		}
4165 
4166 		/*
4167 		 * Clear the pte entry and flush it first, before updating the
4168 		 * pte with the new entry, to keep TLBs on different CPUs in
4169 		 * sync. This code used to set the new PTE then flush TLBs, but
4170 		 * that left a window where the new PTE could be loaded into
4171 		 * some TLBs while the old PTE remains in others.
4172 		 */
4173 		ptep_clear_flush(vma, vmf->address, vmf->pte);
4174 		folio_add_new_anon_rmap(new_folio, vma, vmf->address, RMAP_EXCLUSIVE);
4175 		folio_add_lru_vma(new_folio, vma);
4176 		BUG_ON(unshare && pte_write(entry));
4177 		set_pte_at(mm, vmf->address, vmf->pte, entry);
4178 		update_mmu_cache_range(vmf, vma, vmf->address, vmf->pte, 1);
4179 		if (old_folio) {
4180 			/*
4181 			 * Only after switching the pte to the new page may
4182 			 * we remove the mapcount here. Otherwise another
4183 			 * process may come and find the rmap count decremented
4184 			 * before the pte is switched to the new page, and
4185 			 * "reuse" the old page writing into it while our pte
4186 			 * here still points into it and can be read by other
4187 			 * threads.
4188 			 *
4189 			 * The critical issue is to order this
4190 			 * folio_remove_rmap_pte() with the ptp_clear_flush
4191 			 * above. Those stores are ordered by (if nothing else,)
4192 			 * the barrier present in the atomic_add_negative
4193 			 * in folio_remove_rmap_pte();
4194 			 *
4195 			 * Then the TLB flush in ptep_clear_flush ensures that
4196 			 * no process can access the old page before the
4197 			 * decremented mapcount is visible. And the old page
4198 			 * cannot be reused until after the decremented
4199 			 * mapcount is visible. So transitively, TLBs to
4200 			 * old page will be flushed before it can be reused.
4201 			 */
4202 			folio_remove_rmap_pte(old_folio, vmf->page, vma);
4203 		}
4204 
4205 		/* Free the old page.. */
4206 		new_folio = old_folio;
4207 		page_copied = 1;
4208 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4209 	} else if (vmf->pte) {
4210 		update_mmu_tlb(vma, vmf->address, vmf->pte);
4211 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4212 	}
4213 
4214 	mmu_notifier_invalidate_range_end(&range);
4215 
4216 	if (new_folio)
4217 		folio_put(new_folio);
4218 	if (old_folio) {
4219 		if (page_copied)
4220 			free_swap_cache(old_folio);
4221 		folio_put(old_folio);
4222 	}
4223 
4224 	delayacct_wpcopy_end();
4225 	return 0;
4226 oom:
4227 	ret = VM_FAULT_OOM;
4228 out:
4229 	if (old_folio)
4230 		folio_put(old_folio);
4231 
4232 	delayacct_wpcopy_end();
4233 	return ret;
4234 }
4235 
4236 /**
4237  * finish_mkwrite_fault - finish page fault for a shared mapping, making PTE
4238  *			  writeable once the page is prepared
4239  *
4240  * @vmf: structure describing the fault
4241  * @folio: the folio of vmf->page
4242  *
4243  * This function handles all that is needed to finish a write page fault in a
4244  * shared mapping due to PTE being read-only once the mapped page is prepared.
4245  * It handles locking of PTE and modifying it.
4246  *
4247  * The function expects the page to be locked or other protection against
4248  * concurrent faults / writeback (such as DAX radix tree locks).
4249  *
4250  * Return: %0 on success, %VM_FAULT_NOPAGE when PTE got changed before
4251  * we acquired PTE lock.
4252  */
4253 static vm_fault_t finish_mkwrite_fault(struct vm_fault *vmf, struct folio *folio)
4254 {
4255 	WARN_ON_ONCE(!(vmf->vma->vm_flags & VM_SHARED));
4256 	vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd, vmf->address,
4257 				       &vmf->ptl);
4258 	if (!vmf->pte)
4259 		return VM_FAULT_NOPAGE;
4260 	/*
4261 	 * We might have raced with another page fault while we released the
4262 	 * pte_offset_map_lock.
4263 	 */
4264 	if (!pte_same(ptep_get(vmf->pte), vmf->orig_pte)) {
4265 		update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
4266 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4267 		return VM_FAULT_NOPAGE;
4268 	}
4269 	wp_page_reuse(vmf, folio);
4270 	return 0;
4271 }
4272 
4273 /*
4274  * Handle write page faults for VM_MIXEDMAP or VM_PFNMAP for a VM_SHARED
4275  * mapping
4276  */
4277 static vm_fault_t wp_pfn_shared(struct vm_fault *vmf)
4278 {
4279 	struct vm_area_struct *vma = vmf->vma;
4280 
4281 	if (vma->vm_ops && vma->vm_ops->pfn_mkwrite) {
4282 		vm_fault_t ret;
4283 
4284 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4285 		ret = vmf_can_call_fault(vmf);
4286 		if (ret)
4287 			return ret;
4288 
4289 		vmf->flags |= FAULT_FLAG_MKWRITE;
4290 		ret = vma->vm_ops->pfn_mkwrite(vmf);
4291 		if (ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))
4292 			return ret;
4293 		return finish_mkwrite_fault(vmf, NULL);
4294 	}
4295 	wp_page_reuse(vmf, NULL);
4296 	return 0;
4297 }
4298 
4299 static vm_fault_t wp_page_shared(struct vm_fault *vmf, struct folio *folio)
4300 	__releases(vmf->ptl)
4301 {
4302 	struct vm_area_struct *vma = vmf->vma;
4303 	vm_fault_t ret = 0;
4304 
4305 	folio_get(folio);
4306 
4307 	if (vma->vm_ops && vma->vm_ops->page_mkwrite) {
4308 		vm_fault_t tmp;
4309 
4310 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4311 		tmp = vmf_can_call_fault(vmf);
4312 		if (tmp) {
4313 			folio_put(folio);
4314 			return tmp;
4315 		}
4316 
4317 		tmp = do_page_mkwrite(vmf, folio);
4318 		if (unlikely(!tmp || (tmp &
4319 				      (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
4320 			folio_put(folio);
4321 			return tmp;
4322 		}
4323 		tmp = finish_mkwrite_fault(vmf, folio);
4324 		if (unlikely(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE))) {
4325 			folio_unlock(folio);
4326 			folio_put(folio);
4327 			return tmp;
4328 		}
4329 	} else {
4330 		wp_page_reuse(vmf, folio);
4331 		folio_lock(folio);
4332 	}
4333 	ret |= fault_dirty_shared_page(vmf);
4334 	folio_put(folio);
4335 
4336 	return ret;
4337 }
4338 
4339 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4340 static bool __wp_can_reuse_large_anon_folio(struct folio *folio,
4341 		struct vm_area_struct *vma)
4342 {
4343 	bool exclusive = false;
4344 
4345 	/* Let's just free up a large folio if only a single page is mapped. */
4346 	if (folio_large_mapcount(folio) <= 1)
4347 		return false;
4348 
4349 	/*
4350 	 * The assumption for anonymous folios is that each page can only get
4351 	 * mapped once into each MM. The only exception are KSM folios, which
4352 	 * are always small.
4353 	 *
4354 	 * Each taken mapcount must be paired with exactly one taken reference,
4355 	 * whereby the refcount must be incremented before the mapcount when
4356 	 * mapping a page, and the refcount must be decremented after the
4357 	 * mapcount when unmapping a page.
4358 	 *
4359 	 * If all folio references are from mappings, and all mappings are in
4360 	 * the page tables of this MM, then this folio is exclusive to this MM.
4361 	 */
4362 	if (test_bit(FOLIO_MM_IDS_SHARED_BITNUM, &folio->_mm_ids))
4363 		return false;
4364 
4365 	VM_WARN_ON_ONCE(folio_test_ksm(folio));
4366 
4367 	if (unlikely(folio_test_swapcache(folio))) {
4368 		/*
4369 		 * Note: freeing up the swapcache will fail if some PTEs are
4370 		 * still swap entries.
4371 		 */
4372 		if (!folio_trylock(folio))
4373 			return false;
4374 		folio_free_swap(folio);
4375 		folio_unlock(folio);
4376 	}
4377 
4378 	if (folio_large_mapcount(folio) != folio_ref_count(folio))
4379 		return false;
4380 
4381 	/* Stabilize the mapcount vs. refcount and recheck. */
4382 	folio_lock_large_mapcount(folio);
4383 	VM_WARN_ON_ONCE_FOLIO(folio_large_mapcount(folio) > folio_ref_count(folio), folio);
4384 
4385 	if (test_bit(FOLIO_MM_IDS_SHARED_BITNUM, &folio->_mm_ids))
4386 		goto unlock;
4387 	if (folio_large_mapcount(folio) != folio_ref_count(folio))
4388 		goto unlock;
4389 
4390 	VM_WARN_ON_ONCE_FOLIO(folio_large_mapcount(folio) > folio_nr_pages(folio), folio);
4391 	VM_WARN_ON_ONCE_FOLIO(folio_entire_mapcount(folio), folio);
4392 	VM_WARN_ON_ONCE(folio_mm_id(folio, 0) != vma->vm_mm->mm_id &&
4393 			folio_mm_id(folio, 1) != vma->vm_mm->mm_id);
4394 
4395 	/*
4396 	 * Do we need the folio lock? Likely not. If there would have been
4397 	 * references from page migration/swapout, we would have detected
4398 	 * an additional folio reference and never ended up here.
4399 	 */
4400 	exclusive = true;
4401 unlock:
4402 	folio_unlock_large_mapcount(folio);
4403 	return exclusive;
4404 }
4405 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
4406 static bool __wp_can_reuse_large_anon_folio(struct folio *folio,
4407 		struct vm_area_struct *vma)
4408 {
4409 	BUILD_BUG();
4410 }
4411 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4412 
4413 static bool wp_can_reuse_anon_folio(struct folio *folio,
4414 				    struct vm_area_struct *vma)
4415 {
4416 	const bool maybe_in_lru_cache = !folio_test_lru(folio);
4417 	const bool in_swapcache = folio_test_swapcache(folio);
4418 
4419 	if (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) && folio_test_large(folio))
4420 		return __wp_can_reuse_large_anon_folio(folio, vma);
4421 
4422 	/*
4423 	 * We have to verify under folio lock: these early checks are
4424 	 * just an optimization to avoid locking the folio and freeing
4425 	 * the swapcache if there is little hope that we can reuse.
4426 	 *
4427 	 * KSM doesn't necessarily raise the folio refcount.
4428 	 */
4429 	if (folio_test_ksm(folio) ||
4430 	    folio_ref_count(folio) > 1 + maybe_in_lru_cache + in_swapcache)
4431 		return false;
4432 	if (maybe_in_lru_cache)
4433 		/*
4434 		 * We cannot easily detect+handle references from
4435 		 * remote LRU caches or references to LRU folios.
4436 		 */
4437 		lru_add_drain();
4438 	if (folio_ref_count(folio) > 1 + in_swapcache)
4439 		return false;
4440 	if (!folio_trylock(folio))
4441 		return false;
4442 	if (folio_test_swapcache(folio))
4443 		folio_free_swap(folio);
4444 	if (folio_test_ksm(folio) || folio_ref_count(folio) != 1) {
4445 		folio_unlock(folio);
4446 		return false;
4447 	}
4448 	/*
4449 	 * Ok, we've got the only folio reference from our mapping
4450 	 * and the folio is locked, it's dark out, and we're wearing
4451 	 * sunglasses. Hit it.
4452 	 */
4453 	folio_move_anon_rmap(folio, vma);
4454 	folio_unlock(folio);
4455 	return true;
4456 }
4457 
4458 /*
4459  * This routine handles present pages, when
4460  * * users try to write to a shared page (FAULT_FLAG_WRITE)
4461  * * GUP wants to take a R/O pin on a possibly shared anonymous page
4462  *   (FAULT_FLAG_UNSHARE)
4463  *
4464  * It is done by copying the page to a new address and decrementing the
4465  * shared-page counter for the old page.
4466  *
4467  * Note that this routine assumes that the protection checks have been
4468  * done by the caller (the low-level page fault routine in most cases).
4469  * Thus, with FAULT_FLAG_WRITE, we can safely just mark it writable once we've
4470  * done any necessary COW.
4471  *
4472  * In case of FAULT_FLAG_WRITE, we also mark the page dirty at this point even
4473  * though the page will change only once the write actually happens. This
4474  * avoids a few races, and potentially makes it more efficient.
4475  *
4476  * We enter with either the VMA lock or the mmap_lock held (see
4477  * FAULT_FLAG_VMA_LOCK) and pte both mapped and locked. We return with
4478  * the same lock still held, but pte unmapped and unlocked.
4479  */
4480 static vm_fault_t do_wp_page(struct vm_fault *vmf)
4481 	__releases(vmf->ptl)
4482 {
4483 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
4484 	struct vm_area_struct *vma = vmf->vma;
4485 	struct folio *folio = NULL;
4486 	pte_t pte;
4487 
4488 	if (likely(!unshare)) {
4489 		if (userfaultfd_pte_wp(vma, ptep_get(vmf->pte))) {
4490 			if (!userfaultfd_wp_async(vma)) {
4491 				pte_unmap_unlock(vmf->pte, vmf->ptl);
4492 				return handle_userfault(vmf, VM_UFFD_WP);
4493 			}
4494 
4495 			/*
4496 			 * Nothing needed (cache flush, TLB invalidations,
4497 			 * etc.) because we're only removing the uffd-wp bit,
4498 			 * which is completely invisible to the user.
4499 			 */
4500 			pte = pte_clear_uffd(ptep_get(vmf->pte));
4501 
4502 			set_pte_at(vma->vm_mm, vmf->address, vmf->pte, pte);
4503 			/*
4504 			 * Update this to be prepared for following up CoW
4505 			 * handling
4506 			 */
4507 			vmf->orig_pte = pte;
4508 		}
4509 
4510 		/*
4511 		 * Userfaultfd write-protect can defer flushes. Ensure the TLB
4512 		 * is flushed in this case before copying.
4513 		 */
4514 		if (unlikely(userfaultfd_wp(vmf->vma) &&
4515 			     mm_tlb_flush_pending(vmf->vma->vm_mm)))
4516 			flush_tlb_page(vmf->vma, vmf->address);
4517 	}
4518 
4519 	vmf->page = vm_normal_page(vma, vmf->address, vmf->orig_pte);
4520 
4521 	if (vmf->page)
4522 		folio = page_folio(vmf->page);
4523 
4524 	/*
4525 	 * Shared mapping: we are guaranteed to have VM_WRITE and
4526 	 * FAULT_FLAG_WRITE set at this point.
4527 	 */
4528 	if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
4529 		/*
4530 		 * VM_MIXEDMAP !pfn_valid() case, or VM_SOFTDIRTY clear on a
4531 		 * VM_PFNMAP VMA. FS DAX also wants ops->pfn_mkwrite called.
4532 		 *
4533 		 * We should not cow pages in a shared writeable mapping.
4534 		 * Just mark the pages writable and/or call ops->pfn_mkwrite.
4535 		 */
4536 		if (!vmf->page || is_fsdax_page(vmf->page)) {
4537 			vmf->page = NULL;
4538 			return wp_pfn_shared(vmf);
4539 		}
4540 		return wp_page_shared(vmf, folio);
4541 	}
4542 
4543 	/*
4544 	 * Private mapping: create an exclusive anonymous page copy if reuse
4545 	 * is impossible. We might miss VM_WRITE for FOLL_FORCE handling.
4546 	 *
4547 	 * If we encounter a page that is marked exclusive, we must reuse
4548 	 * the page without further checks.
4549 	 */
4550 	if (folio && folio_test_anon(folio) &&
4551 	    (PageAnonExclusive(vmf->page) || wp_can_reuse_anon_folio(folio, vma))) {
4552 		if (!PageAnonExclusive(vmf->page))
4553 			SetPageAnonExclusive(vmf->page);
4554 		if (unlikely(unshare)) {
4555 			pte_unmap_unlock(vmf->pte, vmf->ptl);
4556 			return 0;
4557 		}
4558 		wp_page_reuse(vmf, folio);
4559 		return 0;
4560 	}
4561 	/*
4562 	 * Ok, we need to copy. Oh, well..
4563 	 */
4564 	if (folio)
4565 		folio_get(folio);
4566 
4567 	pte_unmap_unlock(vmf->pte, vmf->ptl);
4568 #ifdef CONFIG_KSM
4569 	if (folio && folio_test_ksm(folio))
4570 		count_vm_event(COW_KSM);
4571 #endif
4572 	return wp_page_copy(vmf);
4573 }
4574 
4575 static inline void unmap_mapping_range_tree(struct address_space *mapping,
4576 					    pgoff_t first_index,
4577 					    pgoff_t last_index,
4578 					    struct zap_details *details)
4579 {
4580 	struct vm_area_struct *vma;
4581 	struct mmu_gather tlb;
4582 
4583 	mapping_rmap_tree_foreach(vma, mapping, first_index, last_index) {
4584 		const pgoff_t start_idx = max(first_index, vma_start_pgoff(vma));
4585 		const pgoff_t end_idx = min(last_index, vma_last_pgoff(vma)) + 1;
4586 		const pgoff_t offset = start_idx - vma_start_pgoff(vma);
4587 		const unsigned long offset_bytes = offset << PAGE_SHIFT;
4588 		const unsigned long start = vma->vm_start + offset_bytes;
4589 		const unsigned long size = (end_idx - start_idx) << PAGE_SHIFT;
4590 
4591 		tlb_gather_mmu(&tlb, vma->vm_mm);
4592 		zap_vma_range_batched(&tlb, vma, start, size, details);
4593 		tlb_finish_mmu(&tlb);
4594 	}
4595 }
4596 
4597 /**
4598  * unmap_mapping_folio() - Unmap single folio from processes.
4599  * @folio: The locked folio to be unmapped.
4600  *
4601  * Unmap this folio from any userspace process which still has it mmaped.
4602  * Typically, for efficiency, the range of nearby pages has already been
4603  * unmapped by unmap_mapping_pages() or unmap_mapping_range().  But once
4604  * truncation or invalidation holds the lock on a folio, it may find that
4605  * the page has been remapped again: and then uses unmap_mapping_folio()
4606  * to unmap it finally.
4607  */
4608 void unmap_mapping_folio(struct folio *folio)
4609 {
4610 	struct address_space *mapping = folio->mapping;
4611 	struct zap_details details = { };
4612 	pgoff_t	first_index;
4613 	pgoff_t	last_index;
4614 
4615 	VM_BUG_ON(!folio_test_locked(folio));
4616 
4617 	first_index = folio->index;
4618 	last_index = folio_next_index(folio) - 1;
4619 
4620 	details.skip_cows = true;
4621 	details.single_folio = folio;
4622 	details.zap_flags = ZAP_FLAG_DROP_MARKER;
4623 
4624 	i_mmap_lock_read(mapping);
4625 	if (unlikely(mapping_mapped(mapping)))
4626 		unmap_mapping_range_tree(mapping, first_index,
4627 					 last_index, &details);
4628 	i_mmap_unlock_read(mapping);
4629 }
4630 
4631 /**
4632  * unmap_mapping_pages() - Unmap pages from processes.
4633  * @mapping: The address space containing pages to be unmapped.
4634  * @start: Index of first page to be unmapped.
4635  * @nr: Number of pages to be unmapped.  0 to unmap to end of file.
4636  * @even_cows: Whether to unmap even private COWed pages.
4637  *
4638  * Unmap the pages in this address space from any userspace process which
4639  * has them mmaped.  Generally, you want to remove COWed pages as well when
4640  * a file is being truncated, but not when invalidating pages from the page
4641  * cache.
4642  */
4643 void unmap_mapping_pages(struct address_space *mapping, pgoff_t start,
4644 		pgoff_t nr, bool even_cows)
4645 {
4646 	struct zap_details details = { };
4647 	pgoff_t	first_index = start;
4648 	pgoff_t	last_index = start + nr - 1;
4649 
4650 	details.skip_cows = !even_cows;
4651 	if (last_index < first_index)
4652 		last_index = ULONG_MAX;
4653 
4654 	i_mmap_lock_read(mapping);
4655 	if (unlikely(mapping_mapped(mapping)))
4656 		unmap_mapping_range_tree(mapping, first_index,
4657 					 last_index, &details);
4658 	i_mmap_unlock_read(mapping);
4659 }
4660 EXPORT_SYMBOL_GPL(unmap_mapping_pages);
4661 
4662 /**
4663  * unmap_mapping_range - unmap the portion of all mmaps in the specified
4664  * address_space corresponding to the specified byte range in the underlying
4665  * file.
4666  *
4667  * @mapping: the address space containing mmaps to be unmapped.
4668  * @holebegin: byte in first page to unmap, relative to the start of
4669  * the underlying file.  This will be rounded down to a PAGE_SIZE
4670  * boundary.  Note that this is different from truncate_pagecache(), which
4671  * must keep the partial page.  In contrast, we must get rid of
4672  * partial pages.
4673  * @holelen: size of prospective hole in bytes.  This will be rounded
4674  * up to a PAGE_SIZE boundary.  A holelen of zero truncates to the
4675  * end of the file.
4676  * @even_cows: 1 when truncating a file, unmap even private COWed pages;
4677  * but 0 when invalidating pagecache, don't throw away private data.
4678  */
4679 void unmap_mapping_range(struct address_space *mapping,
4680 		loff_t const holebegin, loff_t const holelen, int even_cows)
4681 {
4682 	pgoff_t hba = (u64)holebegin >> PAGE_SHIFT;
4683 	pgoff_t hlen = ((u64)holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
4684 
4685 	/* Check for overflow. */
4686 	if (sizeof(holelen) > sizeof(hlen)) {
4687 		long long holeend =
4688 			(holebegin + holelen + PAGE_SIZE - 1) >> PAGE_SHIFT;
4689 		if (holeend & ~(long long)ULONG_MAX)
4690 			hlen = ULONG_MAX - hba + 1;
4691 	}
4692 
4693 	unmap_mapping_pages(mapping, hba, hlen, even_cows);
4694 }
4695 EXPORT_SYMBOL(unmap_mapping_range);
4696 
4697 /*
4698  * Restore a potential device exclusive pte to a working pte entry
4699  */
4700 static vm_fault_t remove_device_exclusive_entry(struct vm_fault *vmf)
4701 {
4702 	struct folio *folio = page_folio(vmf->page);
4703 	struct vm_area_struct *vma = vmf->vma;
4704 	struct mmu_notifier_range range;
4705 	vm_fault_t ret;
4706 
4707 	/*
4708 	 * We need a reference to lock the folio because we don't hold
4709 	 * the PTL so a racing thread can remove the device-exclusive
4710 	 * entry and unmap it. If the folio is free the entry must
4711 	 * have been removed already. If it happens to have already
4712 	 * been re-allocated after being freed all we do is lock and
4713 	 * unlock it.
4714 	 */
4715 	if (!folio_try_get(folio))
4716 		return 0;
4717 
4718 	ret = folio_lock_or_retry(folio, vmf);
4719 	if (ret) {
4720 		folio_put(folio);
4721 		return ret;
4722 	}
4723 	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_CLEAR, 0,
4724 				vma->vm_mm, vmf->address & PAGE_MASK,
4725 				(vmf->address & PAGE_MASK) + PAGE_SIZE, NULL);
4726 	mmu_notifier_invalidate_range_start(&range);
4727 
4728 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
4729 				&vmf->ptl);
4730 	if (likely(vmf->pte && pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
4731 		restore_exclusive_pte(vma, folio, vmf->page, vmf->address,
4732 				      vmf->pte, vmf->orig_pte);
4733 
4734 	if (vmf->pte)
4735 		pte_unmap_unlock(vmf->pte, vmf->ptl);
4736 	folio_unlock(folio);
4737 	folio_put(folio);
4738 
4739 	mmu_notifier_invalidate_range_end(&range);
4740 	return 0;
4741 }
4742 
4743 /*
4744  * Check if we should call folio_free_swap to free the swap cache.
4745  * folio_free_swap only frees the swap cache to release the slot if swap
4746  * count is zero, so we don't need to check the swap count here.
4747  */
4748 static inline bool should_try_to_free_swap(struct swap_info_struct *si,
4749 					   struct folio *folio,
4750 					   struct vm_area_struct *vma,
4751 					   bool exclusive,
4752 					   unsigned int fault_flags)
4753 {
4754 	if (!folio_test_swapcache(folio))
4755 		return false;
4756 	/*
4757 	 * Always try to free swap cache for SWP_SYNCHRONOUS_IO devices. Swap
4758 	 * cache can help save some IO or memory overhead, but these devices
4759 	 * are fast, and meanwhile, swap cache pinning the slot deferring the
4760 	 * release of metadata or fragmentation is a more critical issue.
4761 	 */
4762 	if (data_race(si->flags & SWP_SYNCHRONOUS_IO))
4763 		return true;
4764 	if (mem_cgroup_swap_full(folio) || (vma->vm_flags & VM_LOCKED) ||
4765 	    folio_test_mlocked(folio))
4766 		return true;
4767 
4768 	/*
4769 	 * Free the swapcache only if we are the exclusive user and
4770 	 * this is a write fault.
4771 	 */
4772 	return (fault_flags & FAULT_FLAG_WRITE) && exclusive;
4773 }
4774 
4775 static vm_fault_t pte_marker_clear(struct vm_fault *vmf)
4776 {
4777 	vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
4778 				       vmf->address, &vmf->ptl);
4779 	if (!vmf->pte)
4780 		return 0;
4781 	/*
4782 	 * Be careful so that we will only recover a special uffd-wp pte into a
4783 	 * none pte.  Otherwise it means the pte could have changed, so retry.
4784 	 *
4785 	 * This should also cover the case where e.g. the pte changed
4786 	 * quickly from a PTE_MARKER_UFFD_WP into PTE_MARKER_POISONED.
4787 	 * So pte_is_marker() check is not enough to safely drop the pte.
4788 	 */
4789 	if (pte_same(vmf->orig_pte, ptep_get(vmf->pte)))
4790 		pte_clear(vmf->vma->vm_mm, vmf->address, vmf->pte);
4791 	pte_unmap_unlock(vmf->pte, vmf->ptl);
4792 	return 0;
4793 }
4794 
4795 static vm_fault_t do_pte_missing(struct vm_fault *vmf)
4796 {
4797 	if (vma_is_anonymous(vmf->vma))
4798 		return do_anonymous_page(vmf);
4799 	else
4800 		return do_fault(vmf);
4801 }
4802 
4803 /*
4804  * This is actually a page-missing access, but with uffd-wp special pte
4805  * installed.  It means this pte was wr-protected before being unmapped.
4806  */
4807 static vm_fault_t pte_marker_handle_uffd_wp(struct vm_fault *vmf)
4808 {
4809 	/*
4810 	 * Just in case there're leftover special ptes even after the region
4811 	 * got unregistered - we can simply clear them.
4812 	 */
4813 	if (unlikely(!userfaultfd_wp(vmf->vma)))
4814 		return pte_marker_clear(vmf);
4815 
4816 	return do_pte_missing(vmf);
4817 }
4818 
4819 static vm_fault_t handle_pte_marker(struct vm_fault *vmf)
4820 {
4821 	const softleaf_t entry = softleaf_from_pte(vmf->orig_pte);
4822 	const pte_marker marker = softleaf_to_marker(entry);
4823 
4824 	/*
4825 	 * PTE markers should never be empty.  If anything weird happened,
4826 	 * the best thing to do is to kill the process along with its mm.
4827 	 */
4828 	if (WARN_ON_ONCE(!marker))
4829 		return VM_FAULT_SIGBUS;
4830 
4831 	/* Higher priority than uffd-wp when data corrupted */
4832 	if (marker & PTE_MARKER_POISONED)
4833 		return VM_FAULT_HWPOISON;
4834 
4835 	/* Hitting a guard page is always a fatal condition. */
4836 	if (marker & PTE_MARKER_GUARD)
4837 		return VM_FAULT_SIGSEGV;
4838 
4839 	if (softleaf_is_uffd_wp_marker(entry))
4840 		return pte_marker_handle_uffd_wp(vmf);
4841 
4842 	/* This is an unknown pte marker */
4843 	return VM_FAULT_SIGBUS;
4844 }
4845 
4846 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
4847 /*
4848  * Check if the PTEs within a range are contiguous swap entries.
4849  */
4850 static bool can_swapin_thp(struct vm_fault *vmf, pte_t *ptep, int nr_pages)
4851 {
4852 	unsigned long addr;
4853 	int idx;
4854 	pte_t pte;
4855 
4856 	addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE);
4857 	idx = (vmf->address - addr) / PAGE_SIZE;
4858 	pte = ptep_get(ptep);
4859 
4860 	if (!pte_same(pte, pte_move_swp_offset(vmf->orig_pte, -idx)))
4861 		return false;
4862 	/*
4863 	 * swap_read_folio() can't handle the case a large folio is hybridly
4864 	 * from different backends. And they are likely corner cases. Similar
4865 	 * things might be added once zswap support large folios.
4866 	 */
4867 	if (swap_pte_batch(ptep, nr_pages, pte) != nr_pages)
4868 		return false;
4869 	return true;
4870 }
4871 
4872 static inline unsigned long thp_swap_suitable_orders(pgoff_t swp_offset,
4873 						     unsigned long addr,
4874 						     unsigned long orders)
4875 {
4876 	int order, nr;
4877 
4878 	order = highest_order(orders);
4879 
4880 	/*
4881 	 * To swap in a THP with nr pages, we require that its first swap_offset
4882 	 * is aligned with that number, as it was when the THP was swapped out.
4883 	 * This helps filter out most invalid entries.
4884 	 */
4885 	while (orders) {
4886 		nr = 1 << order;
4887 		if ((addr >> PAGE_SHIFT) % nr == swp_offset % nr)
4888 			break;
4889 		order = next_order(&orders, order);
4890 	}
4891 
4892 	return orders;
4893 }
4894 
4895 static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf)
4896 {
4897 	struct vm_area_struct *vma = vmf->vma;
4898 	unsigned long orders;
4899 	unsigned long addr;
4900 	softleaf_t entry;
4901 	spinlock_t *ptl;
4902 	pte_t *pte;
4903 	int order;
4904 
4905 	/*
4906 	 * If uffd is active for the vma we need per-page fault fidelity to
4907 	 * maintain the uffd semantics.
4908 	 */
4909 	if (unlikely(userfaultfd_armed(vma)))
4910 		return 0;
4911 
4912 	/*
4913 	 * A large swapped out folio could be partially or fully in zswap. We
4914 	 * lack handling for such cases, so fallback to swapping in order-0
4915 	 * folio.
4916 	 */
4917 	if (!zswap_never_enabled())
4918 		return 0;
4919 
4920 	entry = softleaf_from_pte(vmf->orig_pte);
4921 	/*
4922 	 * Get a list of all the (large) orders below PMD_ORDER that are enabled
4923 	 * and suitable for swapping THP.
4924 	 */
4925 	orders = thp_vma_allowable_orders(vma, vma->vm_flags, TVA_PAGEFAULT,
4926 					  BIT(PMD_ORDER) - 1);
4927 	orders = thp_vma_suitable_orders(vma, vmf->address, orders);
4928 	orders = thp_swap_suitable_orders(swp_offset(entry),
4929 					  vmf->address, orders);
4930 
4931 	if (!orders)
4932 		return 0;
4933 
4934 	pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
4935 				  vmf->address & PMD_MASK, &ptl);
4936 	if (unlikely(!pte))
4937 		return 0;
4938 
4939 	/*
4940 	 * For do_swap_page, find the highest order where the aligned range is
4941 	 * completely swap entries with contiguous swap offsets.
4942 	 */
4943 	order = highest_order(orders);
4944 	while (orders) {
4945 		addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
4946 		if (can_swapin_thp(vmf, pte + pte_index(addr), 1 << order))
4947 			break;
4948 		order = next_order(&orders, order);
4949 	}
4950 
4951 	pte_unmap_unlock(pte, ptl);
4952 
4953 	return orders;
4954 }
4955 #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
4956 static unsigned long thp_swapin_suitable_orders(struct vm_fault *vmf)
4957 {
4958 	return 0;
4959 }
4960 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
4961 
4962 /* Sanity check that a folio is fully exclusive */
4963 static void check_swap_exclusive(struct folio *folio, swp_entry_t entry,
4964 				 unsigned int nr_pages)
4965 {
4966 	/* Called under PT locked and folio locked, the swap count is stable */
4967 	do {
4968 		VM_WARN_ON_ONCE_FOLIO(__swap_count(entry) != 1, folio);
4969 		entry.val++;
4970 	} while (--nr_pages);
4971 }
4972 
4973 /*
4974  * Get the address range in which a folio might be mapped, assuming its pages
4975  * are mapped consecutively and the folio page at the given idx is mapped at
4976  * the given address.
4977  */
4978 static void folio_pte_range(const struct folio *folio,
4979 		const struct vm_area_struct *vma, unsigned long addr,
4980 		unsigned long idx, unsigned long *start, unsigned long *end)
4981 {
4982 	/* Stay within the page table and VMA boundaries. */
4983 	const unsigned long pmd_start = addr & PMD_MASK;
4984 	const unsigned long lower = max(pmd_start, vma->vm_start);
4985 	const unsigned long upper = pte_table_clamped_end(addr, vma->vm_end);
4986 	const unsigned long offset = idx << PAGE_SHIFT;
4987 
4988 	/*
4989 	 * Avoid start/end addresses wrapping by not adding/subtracting more
4990 	 * than the lower/upper limits would allow.
4991 	 */
4992 	*start = addr - min(addr - lower, offset);
4993 	*end = addr + min(upper - addr, folio_size(folio) - offset);
4994 }
4995 
4996 /*
4997  * We enter with either the VMA lock or the mmap_lock held (see
4998  * FAULT_FLAG_VMA_LOCK), and pte mapped but not yet locked.
4999  * We return with pte unmapped and unlocked.
5000  *
5001  * When returning, the lock may have been released in the same cases
5002  * as done by filemap_fault().
5003  */
5004 vm_fault_t do_swap_page(struct vm_fault *vmf)
5005 {
5006 	struct vm_area_struct *vma = vmf->vma;
5007 	struct folio *swapcache = NULL, *folio;
5008 	struct page *page;
5009 	struct swap_info_struct *si = NULL;
5010 	rmap_t rmap_flags = RMAP_NONE;
5011 	bool exclusive = false;
5012 	bool rwp_restore = false;
5013 	softleaf_t entry;
5014 	pte_t pte;
5015 	vm_fault_t ret = 0;
5016 	int nr_pages;
5017 	unsigned long page_idx;
5018 	unsigned long address;
5019 	pte_t *ptep;
5020 
5021 	if (!pte_unmap_same(vmf))
5022 		goto out;
5023 
5024 	entry = softleaf_from_pte(vmf->orig_pte);
5025 	if (unlikely(!softleaf_is_swap(entry))) {
5026 		if (softleaf_is_migration(entry)) {
5027 			migration_entry_wait(vma->vm_mm, vmf->pmd,
5028 					     vmf->address);
5029 		} else if (softleaf_is_device_exclusive(entry)) {
5030 			vmf->page = softleaf_to_page(entry);
5031 			ret = remove_device_exclusive_entry(vmf);
5032 		} else if (softleaf_is_device_private(entry)) {
5033 			if (vmf->flags & FAULT_FLAG_VMA_LOCK) {
5034 				/*
5035 				 * migrate_to_ram is not yet ready to operate
5036 				 * under VMA lock.
5037 				 */
5038 				vma_end_read(vma);
5039 				ret = VM_FAULT_RETRY;
5040 				goto out;
5041 			}
5042 
5043 			vmf->page = softleaf_to_page(entry);
5044 			vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
5045 					vmf->address, &vmf->ptl);
5046 			if (unlikely(!vmf->pte ||
5047 				     !pte_same(ptep_get(vmf->pte),
5048 							vmf->orig_pte)))
5049 				goto unlock;
5050 
5051 			/*
5052 			 * Get a folio reference while we know the folio can't
5053 			 * be freed.
5054 			 */
5055 			folio = page_folio(vmf->page);
5056 			if (folio_trylock(folio)) {
5057 				struct dev_pagemap *pgmap;
5058 
5059 				folio_get(folio);
5060 				pte_unmap_unlock(vmf->pte, vmf->ptl);
5061 				pgmap = page_pgmap(vmf->page);
5062 				ret = pgmap->ops->migrate_to_ram(vmf);
5063 				/* migrate_to_ram() might have split the folio. */
5064 				folio = page_folio(vmf->page);
5065 				folio_unlock(folio);
5066 				folio_put(folio);
5067 			} else {
5068 				pte_unmap(vmf->pte);
5069 				softleaf_entry_wait_on_locked(entry, vmf->ptl);
5070 			}
5071 		} else if (softleaf_is_hwpoison(entry)) {
5072 			ret = VM_FAULT_HWPOISON;
5073 		} else if (softleaf_is_marker(entry)) {
5074 			ret = handle_pte_marker(vmf);
5075 		} else {
5076 			print_bad_pte(vma, vmf->address, vmf->orig_pte, NULL);
5077 			ret = VM_FAULT_SIGBUS;
5078 		}
5079 		goto out;
5080 	}
5081 
5082 	/* Prevent swapoff from happening to us, and reject a bad entry. */
5083 	si = get_swap_device(entry);
5084 	if (IS_ERR_OR_NULL(si)) {
5085 		if (IS_ERR(si))
5086 			ret = VM_FAULT_SIGBUS;
5087 		goto out;
5088 	}
5089 
5090 	folio = swap_cache_get_folio(entry);
5091 	if (folio)
5092 		swap_update_readahead(folio, vma, vmf->address);
5093 	if (!folio) {
5094 		/* Swapin bypasses readahead for SWP_SYNCHRONOUS_IO devices */
5095 		if (data_race(si->flags & SWP_SYNCHRONOUS_IO))
5096 			folio = swapin_sync(entry, GFP_HIGHUSER_MOVABLE,
5097 					    thp_swapin_suitable_orders(vmf) | BIT(0),
5098 					    vmf, NULL, 0);
5099 		else
5100 			folio = swapin_readahead(entry, GFP_HIGHUSER_MOVABLE, vmf);
5101 
5102 		if (IS_ERR_OR_NULL(folio)) {
5103 			/*
5104 			 * Back out if somebody else faulted in this pte
5105 			 * while we released the pte lock.
5106 			 */
5107 			vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
5108 					vmf->address, &vmf->ptl);
5109 			if (likely(vmf->pte &&
5110 				   pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
5111 				ret = VM_FAULT_OOM;
5112 			folio = NULL;
5113 			goto unlock;
5114 		}
5115 
5116 		/* Had to read the page from swap area: Major fault */
5117 		ret = VM_FAULT_MAJOR;
5118 		count_vm_event(PGMAJFAULT);
5119 		count_memcg_event_mm(vma->vm_mm, PGMAJFAULT);
5120 	}
5121 
5122 	swapcache = folio;
5123 	ret |= folio_lock_or_retry(folio, vmf);
5124 	if (ret & VM_FAULT_RETRY)
5125 		goto out_release;
5126 
5127 	page = folio_file_page(folio, swp_offset(entry));
5128 	/*
5129 	 * Make sure folio_free_swap() or swapoff did not release the
5130 	 * swapcache from under us.  The page pin, and pte_same test
5131 	 * below, are not enough to exclude that.  Even if it is still
5132 	 * swapcache, we need to check that the page's swap has not
5133 	 * changed.
5134 	 */
5135 	if (unlikely(!folio_matches_swap_entry(folio, entry)))
5136 		goto out_page;
5137 
5138 	if (unlikely(PageHWPoison(page))) {
5139 		/*
5140 		 * hwpoisoned dirty swapcache pages are kept for killing
5141 		 * owner processes (which may be unknown at hwpoison time)
5142 		 */
5143 		ret = VM_FAULT_HWPOISON;
5144 		goto out_page;
5145 	}
5146 
5147 	/*
5148 	 * KSM sometimes has to copy on read faults, for example, if
5149 	 * folio->index of non-ksm folios would be nonlinear inside the
5150 	 * anon VMA -- the ksm flag is lost on actual swapout.
5151 	 */
5152 	folio = ksm_might_need_to_copy(folio, page, vma, vmf->address);
5153 	if (unlikely(!folio)) {
5154 		ret = VM_FAULT_OOM;
5155 		folio = swapcache;
5156 		goto out_page;
5157 	} else if (unlikely(folio == ERR_PTR(-EHWPOISON))) {
5158 		ret = VM_FAULT_HWPOISON;
5159 		folio = swapcache;
5160 		goto out_page;
5161 	} else if (folio != swapcache)
5162 		page = folio_page(folio, 0);
5163 
5164 	folio_throttle_swaprate(folio, GFP_KERNEL);
5165 
5166 	/*
5167 	 * Back out if somebody else already faulted in this pte.
5168 	 */
5169 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, vmf->address,
5170 			&vmf->ptl);
5171 	if (unlikely(!vmf->pte || !pte_same(ptep_get(vmf->pte), vmf->orig_pte)))
5172 		goto out_nomap;
5173 
5174 	if (unlikely(!folio_test_uptodate(folio))) {
5175 		ret = VM_FAULT_SIGBUS;
5176 		goto out_nomap;
5177 	}
5178 
5179 	nr_pages = 1;
5180 	page_idx = 0;
5181 	address = vmf->address;
5182 	ptep = vmf->pte;
5183 	if (folio_test_large(folio) && folio_test_swapcache(folio)) {
5184 		const int nr = folio_nr_pages(folio);
5185 		const unsigned long idx = folio_page_idx(folio, page);
5186 		unsigned long folio_start, folio_end;
5187 		pte_t *folio_ptep;
5188 		pte_t folio_pte;
5189 
5190 		folio_pte_range(folio, vma, address, idx, &folio_start,
5191 				&folio_end);
5192 		if (unlikely((folio_end - folio_start) >> PAGE_SHIFT != nr))
5193 			goto check_folio;
5194 
5195 		folio_ptep = vmf->pte - idx;
5196 		folio_pte = ptep_get(folio_ptep);
5197 		if (!pte_same(folio_pte, pte_move_swp_offset(vmf->orig_pte, -idx)) ||
5198 		    swap_pte_batch(folio_ptep, nr, folio_pte) != nr)
5199 			goto check_folio;
5200 
5201 		page_idx = idx;
5202 		address = folio_start;
5203 		ptep = folio_ptep;
5204 		nr_pages = nr;
5205 		entry = folio->swap;
5206 		page = &folio->page;
5207 	}
5208 
5209 check_folio:
5210 	/*
5211 	 * PG_anon_exclusive reuses PG_mappedtodisk for anon pages. A swap pte
5212 	 * must never point at an anonymous page in the swapcache that is
5213 	 * PG_anon_exclusive. Sanity check that this holds and especially, that
5214 	 * no filesystem set PG_mappedtodisk on a page in the swapcache. Sanity
5215 	 * check after taking the PT lock and making sure that nobody
5216 	 * concurrently faulted in this page and set PG_anon_exclusive.
5217 	 */
5218 	BUG_ON(!folio_test_anon(folio) && folio_test_mappedtodisk(folio));
5219 	BUG_ON(folio_test_anon(folio) && PageAnonExclusive(page));
5220 
5221 	/*
5222 	 * If a large folio already belongs to anon mapping, then we
5223 	 * can just go on and map it partially.
5224 	 * If not, with the large swapin check above failing, the page table
5225 	 * have changed, so sub pages might got charged to the wrong cgroup,
5226 	 * or even should be shmem. So we have to free it and fallback.
5227 	 * Nothing should have touched it, both anon and shmem checks if a
5228 	 * large folio is fully applicable before use.
5229 	 *
5230 	 * This will be removed once we unify folio allocation in the swap cache
5231 	 * layer, where allocation of a folio stabilizes the swap entries.
5232 	 */
5233 	if (!folio_test_anon(folio) && folio_test_large(folio) &&
5234 	    nr_pages != folio_nr_pages(folio)) {
5235 		if (!WARN_ON_ONCE(folio_test_dirty(folio)))
5236 			swap_cache_del_folio(folio);
5237 		goto out_nomap;
5238 	}
5239 
5240 	/*
5241 	 * Check under PT lock (to protect against concurrent fork() sharing
5242 	 * the swap entry concurrently) for certainly exclusive pages.
5243 	 */
5244 	if (!folio_test_ksm(folio)) {
5245 		/*
5246 		 * The can_swapin_thp check above ensures all PTE have
5247 		 * same exclusiveness. Checking just one PTE is fine.
5248 		 */
5249 		exclusive = pte_swp_exclusive(vmf->orig_pte);
5250 		if (exclusive)
5251 			check_swap_exclusive(folio, entry, nr_pages);
5252 		if (folio != swapcache) {
5253 			/*
5254 			 * We have a fresh page that is not exposed to the
5255 			 * swapcache -> certainly exclusive.
5256 			 */
5257 			exclusive = true;
5258 		} else if (exclusive && folio_test_writeback(folio) &&
5259 			  data_race(si->flags & SWP_STABLE_WRITES)) {
5260 			/*
5261 			 * This is tricky: not all swap backends support
5262 			 * concurrent page modifications while under writeback.
5263 			 *
5264 			 * So if we stumble over such a page in the swapcache
5265 			 * we must not set the page exclusive, otherwise we can
5266 			 * map it writable without further checks and modify it
5267 			 * while still under writeback.
5268 			 *
5269 			 * For these problematic swap backends, simply drop the
5270 			 * exclusive marker: this is perfectly fine as we start
5271 			 * writeback only if we fully unmapped the page and
5272 			 * there are no unexpected references on the page after
5273 			 * unmapping succeeded. After fully unmapped, no
5274 			 * further GUP references (FOLL_GET and FOLL_PIN) can
5275 			 * appear, so dropping the exclusive marker and mapping
5276 			 * it only R/O is fine.
5277 			 */
5278 			exclusive = false;
5279 		}
5280 	}
5281 
5282 	/*
5283 	 * Some architectures may have to restore extra metadata to the page
5284 	 * when reading from swap. This metadata may be indexed by swap entry
5285 	 * so this must be called before folio_put_swap().
5286 	 */
5287 	arch_swap_restore(folio_swap(entry, folio), folio);
5288 
5289 	add_mm_counter(vma->vm_mm, MM_ANONPAGES, nr_pages);
5290 	add_mm_counter(vma->vm_mm, MM_SWAPENTS, -nr_pages);
5291 	pte = mk_pte(page, vma->vm_page_prot);
5292 	if (pte_swp_soft_dirty(vmf->orig_pte))
5293 		pte = pte_mksoft_dirty(pte);
5294 	if (pte_swp_uffd(vmf->orig_pte))
5295 		pte = pte_mkuffd(pte);
5296 
5297 	/*
5298 	 * A page reclaimed while RWP-protected carries the uffd bit on
5299 	 * its swap entry. Re-apply PAGE_NONE on swap-in so the first access
5300 	 * still traps as an RWP fault. pte_modify() preserves _PAGE_UFFD.
5301 	 */
5302 	if (pte_swp_uffd(vmf->orig_pte) && userfaultfd_rwp(vma)) {
5303 		pte = pte_modify(pte, PAGE_NONE);
5304 		rwp_restore = true;
5305 	}
5306 
5307 	/*
5308 	 * Similar logic as in do_wp_page(); however, optimize for pages that
5309 	 * are certainly exclusive.
5310 	 *
5311 	 * Skip the write upgrade for an RWP-restored pte: it must stay
5312 	 * PROT_NONE so the access retries through the RWP fault path
5313 	 * (do_uffd_rwp()) rather than being made writable here.
5314 	 */
5315 	if (exclusive) {
5316 		if (!rwp_restore &&
5317 		    (vma->vm_flags & VM_WRITE) && !userfaultfd_pte_wp(vma, pte) &&
5318 		    !pte_needs_soft_dirty_wp(vma, pte)) {
5319 			pte = pte_mkwrite(pte, vma);
5320 			if (vmf->flags & FAULT_FLAG_WRITE)
5321 				pte = pte_mkdirty(pte);
5322 		}
5323 		rmap_flags |= RMAP_EXCLUSIVE;
5324 	}
5325 	folio_ref_add(folio, nr_pages - 1);
5326 	flush_icache_pages(vma, page, nr_pages);
5327 	vmf->orig_pte = pte_advance_pfn(pte, page_idx);
5328 
5329 	/* ksm created a completely new copy */
5330 	if (unlikely(folio != swapcache)) {
5331 		folio_add_new_anon_rmap(folio, vma, address, RMAP_EXCLUSIVE);
5332 		folio_add_lru_vma(folio, vma);
5333 		folio_put_swap(swapcache,
5334 			       folio_file_page(swapcache, swp_offset(entry)));
5335 	} else if (!folio_test_anon(folio)) {
5336 		/*
5337 		 * We currently only expect !anon folios that are fully
5338 		 * mappable. See the comment after can_swapin_thp above.
5339 		 */
5340 		VM_WARN_ON_ONCE_FOLIO(folio_nr_pages(folio) != nr_pages, folio);
5341 		VM_WARN_ON_ONCE_FOLIO(folio_mapped(folio), folio);
5342 		folio_add_new_anon_rmap(folio, vma, address, rmap_flags);
5343 		folio_put_swap(folio, NULL);
5344 	} else {
5345 		VM_WARN_ON_ONCE(nr_pages != 1 && nr_pages != folio_nr_pages(folio));
5346 		folio_add_anon_rmap_ptes(folio, page, nr_pages, vma, address,
5347 					 rmap_flags);
5348 		folio_put_swap(folio, nr_pages == 1 ? page : NULL);
5349 	}
5350 
5351 	VM_BUG_ON(!folio_test_anon(folio) ||
5352 			(pte_write(pte) && !PageAnonExclusive(page)));
5353 	set_ptes(vma->vm_mm, address, ptep, pte, nr_pages);
5354 	arch_do_swap_page_nr(vma->vm_mm, vma, address,
5355 			pte, pte, nr_pages);
5356 
5357 	/*
5358 	 * Remove the swap entry and conditionally try to free up the swapcache.
5359 	 * Do it after mapping, so raced page faults will likely see the folio
5360 	 * in swap cache and wait on the folio lock.
5361 	 */
5362 	if (should_try_to_free_swap(si, folio, vma, exclusive, vmf->flags))
5363 		folio_free_swap(folio);
5364 
5365 	folio_unlock(folio);
5366 	if (unlikely(folio != swapcache)) {
5367 		/*
5368 		 * Hold the lock to avoid the swap entry to be reused
5369 		 * until we take the PT lock for the pte_same() check
5370 		 * (to avoid false positives from pte_same). For
5371 		 * further safety release the lock after the folio_put_swap
5372 		 * so that the swap count won't change under a
5373 		 * parallel locked swapcache.
5374 		 */
5375 		folio_unlock(swapcache);
5376 		folio_put(swapcache);
5377 	}
5378 
5379 	/*
5380 	 * For an RWP-restored pte, leave it PROT_NONE and let the write
5381 	 * retry through the RWP fault path; do not COW it here, which would
5382 	 * drop the marker for a non-exclusive page.
5383 	 */
5384 	if ((vmf->flags & FAULT_FLAG_WRITE) && !pte_write(pte) && !rwp_restore) {
5385 		ret |= do_wp_page(vmf);
5386 		if (ret & VM_FAULT_ERROR)
5387 			ret &= VM_FAULT_ERROR;
5388 		goto out;
5389 	}
5390 
5391 	/* No need to invalidate - it was non-present before */
5392 	update_mmu_cache_range(vmf, vma, address, ptep, nr_pages);
5393 unlock:
5394 	if (vmf->pte)
5395 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5396 out:
5397 	if (!IS_ERR_OR_NULL(si))
5398 		put_swap_device(si);
5399 	return ret;
5400 out_nomap:
5401 	if (vmf->pte)
5402 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5403 out_page:
5404 	if (folio_test_swapcache(folio))
5405 		folio_free_swap(folio);
5406 	folio_unlock(folio);
5407 out_release:
5408 	folio_put(folio);
5409 	if (folio != swapcache) {
5410 		folio_unlock(swapcache);
5411 		folio_put(swapcache);
5412 	}
5413 	if (si)
5414 		put_swap_device(si);
5415 	return ret;
5416 }
5417 
5418 static bool pte_range_none(pte_t *pte, int nr_pages)
5419 {
5420 	int i;
5421 
5422 	for (i = 0; i < nr_pages; i++) {
5423 		if (!pte_none(ptep_get_lockless(pte + i)))
5424 			return false;
5425 	}
5426 
5427 	return true;
5428 }
5429 
5430 static struct folio *alloc_anon_folio(struct vm_fault *vmf)
5431 {
5432 	struct vm_area_struct *vma = vmf->vma;
5433 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5434 	unsigned long orders;
5435 	struct folio *folio;
5436 	unsigned long addr;
5437 	pte_t *pte;
5438 	gfp_t gfp;
5439 	int order;
5440 
5441 	/*
5442 	 * If uffd is active for the vma we need per-page fault fidelity to
5443 	 * maintain the uffd semantics.
5444 	 */
5445 	if (unlikely(userfaultfd_armed(vma)))
5446 		goto fallback;
5447 
5448 	/*
5449 	 * Get a list of all the (large) orders below PMD_ORDER that are enabled
5450 	 * for this vma. Then filter out the orders that can't be allocated over
5451 	 * the faulting address and still be fully contained in the vma.
5452 	 */
5453 	orders = thp_vma_allowable_orders(vma, vma->vm_flags, TVA_PAGEFAULT,
5454 					  BIT(PMD_ORDER) - 1);
5455 	orders = thp_vma_suitable_orders(vma, vmf->address, orders);
5456 
5457 	if (!orders)
5458 		goto fallback;
5459 
5460 	pte = pte_offset_map(vmf->pmd, vmf->address & PMD_MASK);
5461 	if (!pte)
5462 		return ERR_PTR(-EAGAIN);
5463 
5464 	/*
5465 	 * Find the highest order where the aligned range is completely
5466 	 * pte_none(). Note that all remaining orders will be completely
5467 	 * pte_none().
5468 	 */
5469 	order = highest_order(orders);
5470 	while (orders) {
5471 		addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
5472 		if (pte_range_none(pte + pte_index(addr), 1 << order))
5473 			break;
5474 		order = next_order(&orders, order);
5475 	}
5476 
5477 	pte_unmap(pte);
5478 
5479 	if (!orders)
5480 		goto fallback;
5481 
5482 	/* Try allocating the highest of the remaining orders. */
5483 	gfp = vma_thp_gfp_mask(vma);
5484 	while (orders) {
5485 		addr = ALIGN_DOWN(vmf->address, PAGE_SIZE << order);
5486 		folio = vma_alloc_folio(gfp, order, vma, addr);
5487 		if (!folio)
5488 			goto next;
5489 		if (mem_cgroup_charge(folio, vma->vm_mm, gfp)) {
5490 			count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE);
5491 			folio_put(folio);
5492 			goto next;
5493 		}
5494 		if (order > 1 && folio_memcg_alloc_deferred(folio)) {
5495 			folio_put(folio);
5496 			goto fallback;
5497 		}
5498 		folio_throttle_swaprate(folio, gfp);
5499 		/*
5500 		 * When a folio is not zeroed during allocation
5501 		 * (__GFP_ZERO not used) or user folios require special
5502 		 * handling, folio_zero_user() is used to make sure
5503 		 * that the page corresponding to the faulting address
5504 		 * will be hot in the cache after zeroing.
5505 		 */
5506 		if (user_alloc_needs_zeroing())
5507 			folio_zero_user(folio, vmf->address);
5508 		return folio;
5509 next:
5510 		count_mthp_stat(order, MTHP_STAT_ANON_FAULT_FALLBACK);
5511 		order = next_order(&orders, order);
5512 	}
5513 
5514 fallback:
5515 #endif
5516 	return folio_prealloc(vma->vm_mm, vma, vmf->address, true);
5517 }
5518 
5519 void map_anon_folio_pte_nopf(struct folio *folio, pte_t *pte,
5520 		struct vm_area_struct *vma, unsigned long addr,
5521 		bool uffd_wp)
5522 {
5523 	const unsigned int nr_pages = folio_nr_pages(folio);
5524 	pte_t entry = folio_mk_pte(folio, vma->vm_page_prot);
5525 
5526 	entry = pte_sw_mkyoung(entry);
5527 
5528 	entry = maybe_mkwrite(pte_mkdirty(entry), vma);
5529 	if (uffd_wp)
5530 		entry = pte_mkuffd(entry);
5531 
5532 	folio_ref_add(folio, nr_pages - 1);
5533 	folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
5534 	folio_add_lru_vma(folio, vma);
5535 	set_ptes(vma->vm_mm, addr, pte, entry, nr_pages);
5536 	update_mmu_cache_range(NULL, vma, addr, pte, nr_pages);
5537 }
5538 
5539 static void map_anon_folio_pte_pf(struct folio *folio, pte_t *pte,
5540 		struct vm_area_struct *vma, unsigned long addr, bool uffd_wp)
5541 {
5542 	const unsigned int order = folio_order(folio);
5543 
5544 	map_anon_folio_pte_nopf(folio, pte, vma, addr, uffd_wp);
5545 	add_mm_counter(vma->vm_mm, MM_ANONPAGES, 1L << order);
5546 	count_mthp_stat(order, MTHP_STAT_ANON_FAULT_ALLOC);
5547 }
5548 
5549 /*
5550  * We enter with either the VMA lock or the mmap_lock held (see
5551  * FAULT_FLAG_VMA_LOCK), and pte unmapped and unlocked.
5552  * We return with the lock still held, but pte unmapped and unlocked.
5553  * If VM_FAULT_RETRY is returned, the lock may have been released.
5554  */
5555 static vm_fault_t do_anonymous_page(struct vm_fault *vmf)
5556 {
5557 	struct vm_area_struct *vma = vmf->vma;
5558 	unsigned long addr = vmf->address;
5559 	struct folio *folio;
5560 	vm_fault_t ret = 0;
5561 	int nr_pages;
5562 	pte_t entry;
5563 
5564 	/* File mapping without ->vm_ops ? */
5565 	if (vma->vm_flags & VM_SHARED)
5566 		return VM_FAULT_SIGBUS;
5567 
5568 	/*
5569 	 * Use pte_alloc() instead of pte_alloc_map(), so that OOM can
5570 	 * be distinguished from a transient failure of pte_offset_map().
5571 	 */
5572 	if (pte_alloc(vma->vm_mm, vmf->pmd))
5573 		return VM_FAULT_OOM;
5574 
5575 	/* Use the zero-page for reads */
5576 	if (!(vmf->flags & FAULT_FLAG_WRITE) &&
5577 			!mm_forbids_zeropage(vma->vm_mm)) {
5578 		entry = pte_mkspecial(pfn_pte(zero_pfn(vmf->address),
5579 						vma->vm_page_prot));
5580 		vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
5581 				vmf->address, &vmf->ptl);
5582 		if (!vmf->pte)
5583 			goto unlock;
5584 		if (vmf_pte_changed(vmf)) {
5585 			update_mmu_tlb(vma, vmf->address, vmf->pte);
5586 			goto unlock;
5587 		}
5588 		ret = check_stable_address_space(vma->vm_mm);
5589 		if (ret)
5590 			goto unlock;
5591 		/* Deliver the page fault to userland, check inside PT lock */
5592 		if (userfaultfd_missing(vma)) {
5593 			pte_unmap_unlock(vmf->pte, vmf->ptl);
5594 			return handle_userfault(vmf, VM_UFFD_MISSING);
5595 		}
5596 		if (vmf_orig_pte_uffd_wp(vmf))
5597 			entry = pte_mkuffd(entry);
5598 		set_pte_at(vma->vm_mm, addr, vmf->pte, entry);
5599 
5600 		/* No need to invalidate - it was non-present before */
5601 		update_mmu_cache(vma, addr, vmf->pte);
5602 		goto unlock;
5603 	}
5604 
5605 	/* Allocate our own private page. */
5606 	ret = vmf_anon_prepare(vmf);
5607 	if (ret)
5608 		return ret;
5609 	/* Returns NULL on OOM or ERR_PTR(-EAGAIN) if we must retry the fault */
5610 	folio = alloc_anon_folio(vmf);
5611 	if (IS_ERR(folio))
5612 		return 0;
5613 	if (!folio)
5614 		goto oom;
5615 
5616 	nr_pages = folio_nr_pages(folio);
5617 	addr = ALIGN_DOWN(vmf->address, nr_pages * PAGE_SIZE);
5618 
5619 	/*
5620 	 * The memory barrier inside __folio_mark_uptodate makes sure that
5621 	 * preceding stores to the page contents become visible before
5622 	 * the set_pte_at() write.
5623 	 */
5624 	__folio_mark_uptodate(folio);
5625 
5626 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd, addr, &vmf->ptl);
5627 	if (!vmf->pte)
5628 		goto release;
5629 	if (nr_pages == 1 && vmf_pte_changed(vmf)) {
5630 		update_mmu_tlb(vma, addr, vmf->pte);
5631 		goto release;
5632 	} else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) {
5633 		update_mmu_tlb_range(vma, addr, vmf->pte, nr_pages);
5634 		goto release;
5635 	}
5636 
5637 	ret = check_stable_address_space(vma->vm_mm);
5638 	if (ret)
5639 		goto release;
5640 
5641 	/* Deliver the page fault to userland, check inside PT lock */
5642 	if (userfaultfd_missing(vma)) {
5643 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5644 		folio_put(folio);
5645 		return handle_userfault(vmf, VM_UFFD_MISSING);
5646 	}
5647 	map_anon_folio_pte_pf(folio, vmf->pte, vma, addr,
5648 			      vmf_orig_pte_uffd_wp(vmf));
5649 unlock:
5650 	if (vmf->pte)
5651 		pte_unmap_unlock(vmf->pte, vmf->ptl);
5652 	return ret;
5653 release:
5654 	folio_put(folio);
5655 	goto unlock;
5656 oom:
5657 	return VM_FAULT_OOM;
5658 }
5659 
5660 /*
5661  * Either the VMA lock or the mmap_lock must have been held on entry
5662  * (see FAULT_FLAG_VMA_LOCK) and may have been released depending on
5663  * flags and vma->vm_ops->fault() return value.
5664  * See filemap_fault() and __folio_lock_or_retry().
5665  */
5666 static vm_fault_t __do_fault(struct vm_fault *vmf)
5667 {
5668 	struct vm_area_struct *vma = vmf->vma;
5669 	struct folio *folio;
5670 	vm_fault_t ret;
5671 
5672 	/*
5673 	 * Preallocate pte before we take folio lock because this might lead to
5674 	 * deadlocks for memcg reclaim which waits for folios under writeback:
5675 	 *				folio_lock(A)
5676 	 *				folio_set_writeback(A)
5677 	 *				folio_unlock(A)
5678 	 * folio_lock(B)
5679 	 *				folio_lock(B)
5680 	 * pte_alloc_one
5681 	 *   shrink_folio_list
5682 	 *     folio_wait_writeback(A)
5683 	 *				folio_set_writeback(B)
5684 	 *				folio_unlock(B)
5685 	 *				# flush A, B to clear the writeback
5686 	 */
5687 	if (pmd_none(*vmf->pmd) && !vmf->prealloc_pte) {
5688 		vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
5689 		if (!vmf->prealloc_pte)
5690 			return VM_FAULT_OOM;
5691 	}
5692 
5693 	ret = vma->vm_ops->fault(vmf);
5694 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY |
5695 			    VM_FAULT_DONE_COW)))
5696 		return ret;
5697 
5698 	folio = page_folio(vmf->page);
5699 	if (unlikely(PageHWPoison(vmf->page))) {
5700 		vm_fault_t poisonret = VM_FAULT_HWPOISON;
5701 		if (ret & VM_FAULT_LOCKED) {
5702 			if (folio_mapped(folio))
5703 				unmap_mapping_folio(folio);
5704 			/* Retry if a clean folio was removed from the cache. */
5705 			if (mapping_evict_folio(folio->mapping, folio))
5706 				poisonret = VM_FAULT_NOPAGE;
5707 			folio_unlock(folio);
5708 		}
5709 		folio_put(folio);
5710 		vmf->page = NULL;
5711 		return poisonret;
5712 	}
5713 
5714 	if (unlikely(!(ret & VM_FAULT_LOCKED)))
5715 		folio_lock(folio);
5716 	else
5717 		VM_BUG_ON_PAGE(!folio_test_locked(folio), vmf->page);
5718 
5719 	return ret;
5720 }
5721 
5722 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
5723 static void deposit_prealloc_pte(struct vm_fault *vmf)
5724 {
5725 	struct vm_area_struct *vma = vmf->vma;
5726 
5727 	pgtable_trans_huge_deposit(vma->vm_mm, vmf->pmd, vmf->prealloc_pte);
5728 	/*
5729 	 * We are going to consume the prealloc table,
5730 	 * count that as nr_ptes.
5731 	 */
5732 	mm_inc_nr_ptes(vma->vm_mm);
5733 	vmf->prealloc_pte = NULL;
5734 }
5735 
5736 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *page)
5737 {
5738 	struct vm_area_struct *vma = vmf->vma;
5739 	bool write = vmf->flags & FAULT_FLAG_WRITE;
5740 	unsigned long haddr = vmf->address & HPAGE_PMD_MASK;
5741 	pmd_t entry;
5742 	vm_fault_t ret = VM_FAULT_FALLBACK;
5743 
5744 	/*
5745 	 * It is too late to allocate a small folio, we already have a large
5746 	 * folio in the pagecache: especially s390 KVM cannot tolerate any
5747 	 * PMD mappings, but PTE-mapped THP are fine. So let's simply refuse any
5748 	 * PMD mappings if THPs are disabled. As we already have a THP,
5749 	 * behave as if we are forcing a collapse.
5750 	 */
5751 	if (thp_disabled_by_hw() || vma_thp_disabled(vma, vma->vm_flags,
5752 						     /* forced_collapse=*/ true))
5753 		return ret;
5754 
5755 	if (!thp_vma_suitable_order(vma, haddr, PMD_ORDER))
5756 		return ret;
5757 
5758 	if (!is_pmd_order(folio_order(folio)))
5759 		return ret;
5760 	page = &folio->page;
5761 
5762 	/*
5763 	 * Just backoff if any subpage of a THP is corrupted otherwise
5764 	 * the corrupted page may mapped by PMD silently to escape the
5765 	 * check.  This kind of THP just can be PTE mapped.  Access to
5766 	 * the corrupted subpage should trigger SIGBUS as expected.
5767 	 */
5768 	if (unlikely(folio_test_has_hwpoisoned(folio)))
5769 		return ret;
5770 
5771 	if (unlikely(folio_ref_count_over_limit(folio)))
5772 		return VM_FAULT_SIGBUS;
5773 
5774 	/*
5775 	 * Archs like ppc64 need additional space to store information
5776 	 * related to pte entry. Use the preallocated table for that.
5777 	 */
5778 	if (arch_needs_pgtable_deposit() && !vmf->prealloc_pte) {
5779 		vmf->prealloc_pte = pte_alloc_one(vma->vm_mm);
5780 		if (!vmf->prealloc_pte)
5781 			return VM_FAULT_OOM;
5782 	}
5783 
5784 	vmf->ptl = pmd_lock(vma->vm_mm, vmf->pmd);
5785 	if (unlikely(!pmd_none(*vmf->pmd)))
5786 		goto out;
5787 
5788 	flush_icache_pages(vma, page, HPAGE_PMD_NR);
5789 
5790 	entry = folio_mk_pmd(folio, vma->vm_page_prot);
5791 	if (write)
5792 		entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma);
5793 
5794 	add_mm_counter(vma->vm_mm, mm_counter_file(folio), HPAGE_PMD_NR);
5795 	folio_add_file_rmap_pmd(folio, page, vma);
5796 
5797 	/*
5798 	 * deposit and withdraw with pmd lock held
5799 	 */
5800 	if (arch_needs_pgtable_deposit())
5801 		deposit_prealloc_pte(vmf);
5802 
5803 	set_pmd_at(vma->vm_mm, haddr, vmf->pmd, entry);
5804 
5805 	update_mmu_cache_pmd(vma, haddr, vmf->pmd);
5806 
5807 	/* fault is handled */
5808 	ret = 0;
5809 	count_vm_event(THP_FILE_MAPPED);
5810 out:
5811 	spin_unlock(vmf->ptl);
5812 	return ret;
5813 }
5814 #else
5815 vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *page)
5816 {
5817 	return VM_FAULT_FALLBACK;
5818 }
5819 #endif
5820 
5821 /**
5822  * set_pte_range - Set a range of PTEs to point to pages in a folio.
5823  * @vmf: Fault description.
5824  * @folio: The folio that contains @page.
5825  * @page: The first page to create a PTE for.
5826  * @nr: The number of PTEs to create.
5827  * @addr: The first address to create a PTE for.
5828  *
5829  * For file mappings, the caller must check folio_ref_count_over_limit()
5830  * before installing PTEs.
5831  */
5832 void set_pte_range(struct vm_fault *vmf, struct folio *folio,
5833 		struct page *page, unsigned int nr, unsigned long addr)
5834 {
5835 	struct vm_area_struct *vma = vmf->vma;
5836 	bool write = vmf->flags & FAULT_FLAG_WRITE;
5837 	bool prefault = !in_range(vmf->address, addr, nr * PAGE_SIZE);
5838 	pte_t entry;
5839 
5840 	flush_icache_pages(vma, page, nr);
5841 	entry = mk_pte(page, vma->vm_page_prot);
5842 
5843 	if (prefault && arch_wants_old_prefaulted_pte())
5844 		entry = pte_mkold(entry);
5845 	else
5846 		entry = pte_sw_mkyoung(entry);
5847 
5848 	if (write)
5849 		entry = maybe_mkwrite(pte_mkdirty(entry), vma);
5850 	else if (pte_write(entry) && folio_test_dirty(folio))
5851 		entry = pte_mkdirty(entry);
5852 	if (unlikely(vmf_orig_pte_uffd_wp(vmf)))
5853 		entry = pte_mkuffd(entry);
5854 	/* copy-on-write page */
5855 	if (write && !(vma->vm_flags & VM_SHARED)) {
5856 		VM_BUG_ON_FOLIO(nr != 1, folio);
5857 		/*
5858 		 * Concurrent zapping might have dropped the PTL but not flushed
5859 		 * the TLB yet. Flush before installing a new folio.
5860 		 */
5861 		if (mm_tlb_flush_pending(vma->vm_mm))
5862 			flush_tlb_page(vma, addr);
5863 		folio_add_new_anon_rmap(folio, vma, addr, RMAP_EXCLUSIVE);
5864 		folio_add_lru_vma(folio, vma);
5865 	} else {
5866 		folio_add_file_rmap_ptes(folio, page, nr, vma);
5867 	}
5868 	set_ptes(vma->vm_mm, addr, vmf->pte, entry, nr);
5869 
5870 	/* no need to invalidate: a not-present page won't be cached */
5871 	update_mmu_cache_range(vmf, vma, addr, vmf->pte, nr);
5872 }
5873 
5874 static bool vmf_pte_changed(struct vm_fault *vmf)
5875 {
5876 	if (vmf->flags & FAULT_FLAG_ORIG_PTE_VALID)
5877 		return !pte_same(ptep_get(vmf->pte), vmf->orig_pte);
5878 
5879 	return !pte_none(ptep_get(vmf->pte));
5880 }
5881 
5882 /**
5883  * finish_fault - finish page fault once we have prepared the page to fault
5884  *
5885  * @vmf: structure describing the fault
5886  *
5887  * This function handles all that is needed to finish a page fault once the
5888  * page to fault in is prepared. It handles locking of PTEs, inserts PTE for
5889  * given page, adds reverse page mapping, handles memcg charges and LRU
5890  * addition.
5891  *
5892  * The function expects the page to be locked and on success it consumes a
5893  * reference of a page being mapped (for the PTE which maps it).
5894  *
5895  * Return: %0 on success, %VM_FAULT_ code in case of error.
5896  */
5897 vm_fault_t finish_fault(struct vm_fault *vmf)
5898 {
5899 	struct vm_area_struct *vma = vmf->vma;
5900 	struct page *page;
5901 	struct folio *folio;
5902 	vm_fault_t ret;
5903 	bool is_cow = (vmf->flags & FAULT_FLAG_WRITE) &&
5904 		      !(vma->vm_flags & VM_SHARED);
5905 	int type, nr_pages;
5906 	unsigned long addr;
5907 	bool needs_fallback = false;
5908 
5909 fallback:
5910 	addr = vmf->address;
5911 
5912 	/* Did we COW the page? */
5913 	if (is_cow)
5914 		page = vmf->cow_page;
5915 	else
5916 		page = vmf->page;
5917 
5918 	folio = page_folio(page);
5919 	/*
5920 	 * check even for read faults because we might have lost our CoWed
5921 	 * page
5922 	 */
5923 	if (!(vma->vm_flags & VM_SHARED)) {
5924 		ret = check_stable_address_space(vma->vm_mm);
5925 		if (ret)
5926 			return ret;
5927 	}
5928 
5929 	if (!needs_fallback && vma->vm_file) {
5930 		struct address_space *mapping = vma->vm_file->f_mapping;
5931 		pgoff_t file_end;
5932 
5933 		file_end = DIV_ROUND_UP(i_size_read(mapping->host), PAGE_SIZE);
5934 
5935 		/*
5936 		 * Do not allow to map with PTEs beyond i_size and with PMD
5937 		 * across i_size to preserve SIGBUS semantics.
5938 		 *
5939 		 * Make an exception for shmem/tmpfs that for long time
5940 		 * intentionally mapped with PMDs across i_size.
5941 		 */
5942 		needs_fallback = !shmem_mapping(mapping) &&
5943 			file_end < folio_next_index(folio);
5944 	}
5945 
5946 	if (pmd_none(*vmf->pmd)) {
5947 		if (!needs_fallback && folio_test_pmd_mappable(folio)) {
5948 			ret = do_set_pmd(vmf, folio, page);
5949 			if (ret != VM_FAULT_FALLBACK)
5950 				return ret;
5951 		}
5952 
5953 		if (vmf->prealloc_pte)
5954 			pmd_install(vma->vm_mm, vmf->pmd, &vmf->prealloc_pte);
5955 		else if (unlikely(pte_alloc(vma->vm_mm, vmf->pmd)))
5956 			return VM_FAULT_OOM;
5957 	}
5958 
5959 	nr_pages = folio_nr_pages(folio);
5960 
5961 	/* Using per-page fault to maintain the uffd semantics */
5962 	if (unlikely(userfaultfd_armed(vma)) || unlikely(needs_fallback)) {
5963 		nr_pages = 1;
5964 	} else if (nr_pages > 1) {
5965 		pgoff_t idx = folio_page_idx(folio, page);
5966 		/* The page offset of vmf->address within the VMA. */
5967 		pgoff_t vma_off = vmf->pgoff - vma_start_pgoff(vmf->vma);
5968 		/* The index of the entry in the pagetable for fault page. */
5969 		pgoff_t pte_off = pte_index(vmf->address);
5970 
5971 		/*
5972 		 * Fallback to per-page fault in case the folio size in page
5973 		 * cache beyond the VMA limits and PMD pagetable limits.
5974 		 */
5975 		if (unlikely(vma_off < idx ||
5976 			    vma_off + (nr_pages - idx) > vma_pages(vma) ||
5977 			    pte_off < idx ||
5978 			    pte_off + (nr_pages - idx)  > PTRS_PER_PTE)) {
5979 			nr_pages = 1;
5980 		} else {
5981 			/* Now we can set mappings for the whole large folio. */
5982 			addr = vmf->address - idx * PAGE_SIZE;
5983 			page = &folio->page;
5984 		}
5985 	}
5986 
5987 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
5988 				       addr, &vmf->ptl);
5989 	if (!vmf->pte)
5990 		return VM_FAULT_NOPAGE;
5991 
5992 	/* Re-check under ptl */
5993 	if (nr_pages == 1 && unlikely(vmf_pte_changed(vmf))) {
5994 		update_mmu_tlb(vma, addr, vmf->pte);
5995 		ret = VM_FAULT_NOPAGE;
5996 		goto unlock;
5997 	} else if (nr_pages > 1 && !pte_range_none(vmf->pte, nr_pages)) {
5998 		needs_fallback = true;
5999 		pte_unmap_unlock(vmf->pte, vmf->ptl);
6000 		goto fallback;
6001 	}
6002 
6003 	if (!is_cow && unlikely(folio_ref_count_over_limit(folio))) {
6004 		ret = VM_FAULT_SIGBUS;
6005 		goto unlock;
6006 	}
6007 	folio_ref_add(folio, nr_pages - 1);
6008 	set_pte_range(vmf, folio, page, nr_pages, addr);
6009 	type = is_cow ? MM_ANONPAGES : mm_counter_file(folio);
6010 	add_mm_counter(vma->vm_mm, type, nr_pages);
6011 	ret = 0;
6012 
6013 unlock:
6014 	pte_unmap_unlock(vmf->pte, vmf->ptl);
6015 	return ret;
6016 }
6017 
6018 static unsigned long fault_around_pages __read_mostly =
6019 	65536 >> PAGE_SHIFT;
6020 
6021 #ifdef CONFIG_DEBUG_FS
6022 static int fault_around_bytes_get(void *data, u64 *val)
6023 {
6024 	*val = fault_around_pages << PAGE_SHIFT;
6025 	return 0;
6026 }
6027 
6028 /*
6029  * fault_around_bytes must be rounded down to the nearest page order as it's
6030  * what do_fault_around() expects to see.
6031  */
6032 static int fault_around_bytes_set(void *data, u64 val)
6033 {
6034 	if (val / PAGE_SIZE > PTRS_PER_PTE)
6035 		return -EINVAL;
6036 
6037 	/*
6038 	 * The minimum value is 1 page, however this results in no fault-around
6039 	 * at all. See should_fault_around().
6040 	 */
6041 	val = max(val, PAGE_SIZE);
6042 	fault_around_pages = rounddown_pow_of_two(val) >> PAGE_SHIFT;
6043 
6044 	return 0;
6045 }
6046 DEFINE_DEBUGFS_ATTRIBUTE(fault_around_bytes_fops,
6047 		fault_around_bytes_get, fault_around_bytes_set, "%llu\n");
6048 
6049 static int __init fault_around_debugfs(void)
6050 {
6051 	debugfs_create_file_unsafe("fault_around_bytes", 0644, NULL, NULL,
6052 				   &fault_around_bytes_fops);
6053 	return 0;
6054 }
6055 late_initcall(fault_around_debugfs);
6056 #endif
6057 
6058 /*
6059  * do_fault_around() tries to map few pages around the fault address. The hope
6060  * is that the pages will be needed soon and this will lower the number of
6061  * faults to handle.
6062  *
6063  * It uses vm_ops->map_pages() to map the pages, which skips the page if it's
6064  * not ready to be mapped: not up-to-date, locked, etc.
6065  *
6066  * This function doesn't cross VMA or page table boundaries, in order to call
6067  * map_pages() and acquire a PTE lock only once.
6068  *
6069  * fault_around_pages defines how many pages we'll try to map.
6070  * do_fault_around() expects it to be set to a power of two less than or equal
6071  * to PTRS_PER_PTE.
6072  *
6073  * The virtual address of the area that we map is naturally aligned to
6074  * fault_around_pages * PAGE_SIZE rounded down to the machine page size
6075  * (and therefore to page order).  This way it's easier to guarantee
6076  * that we don't cross page table boundaries.
6077  */
6078 static vm_fault_t do_fault_around(struct vm_fault *vmf)
6079 {
6080 	pgoff_t nr_pages = READ_ONCE(fault_around_pages);
6081 	pgoff_t pte_off = pte_index(vmf->address);
6082 	/* The page offset of vmf->address within the VMA. */
6083 	pgoff_t vma_off = vmf->pgoff - vma_start_pgoff(vmf->vma);
6084 	pgoff_t from_pte, to_pte;
6085 	vm_fault_t ret;
6086 
6087 	/* The PTE offset of the start address, clamped to the VMA. */
6088 	from_pte = max(ALIGN_DOWN(pte_off, nr_pages),
6089 		       pte_off - min(pte_off, vma_off));
6090 
6091 	/* The PTE offset of the end address, clamped to the VMA and PTE. */
6092 	to_pte = min3(from_pte + nr_pages, (pgoff_t)PTRS_PER_PTE,
6093 		      pte_off + vma_pages(vmf->vma) - vma_off) - 1;
6094 
6095 	if (pmd_none(*vmf->pmd)) {
6096 		vmf->prealloc_pte = pte_alloc_one(vmf->vma->vm_mm);
6097 		if (!vmf->prealloc_pte)
6098 			return VM_FAULT_OOM;
6099 	}
6100 
6101 	rcu_read_lock();
6102 	ret = vmf->vma->vm_ops->map_pages(vmf,
6103 			vmf->pgoff + from_pte - pte_off,
6104 			vmf->pgoff + to_pte - pte_off);
6105 	rcu_read_unlock();
6106 
6107 	return ret;
6108 }
6109 
6110 /* Return true if we should do read fault-around, false otherwise */
6111 static inline bool should_fault_around(struct vm_fault *vmf)
6112 {
6113 	/* No ->map_pages?  No way to fault around... */
6114 	if (!vmf->vma->vm_ops->map_pages)
6115 		return false;
6116 
6117 	if (uffd_disable_fault_around(vmf->vma))
6118 		return false;
6119 
6120 	/* A single page implies no faulting 'around' at all. */
6121 	return fault_around_pages > 1;
6122 }
6123 
6124 static vm_fault_t do_read_fault(struct vm_fault *vmf)
6125 {
6126 	vm_fault_t ret = 0;
6127 	struct folio *folio;
6128 
6129 	/*
6130 	 * Let's call ->map_pages() first and use ->fault() as fallback
6131 	 * if page by the offset is not ready to be mapped (cold cache or
6132 	 * something).
6133 	 */
6134 	if (should_fault_around(vmf)) {
6135 		ret = do_fault_around(vmf);
6136 		if (ret)
6137 			return ret;
6138 	}
6139 
6140 	ret = vmf_can_call_fault(vmf);
6141 	if (ret)
6142 		return ret;
6143 
6144 	ret = __do_fault(vmf);
6145 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
6146 		return ret;
6147 
6148 	ret |= finish_fault(vmf);
6149 	folio = page_folio(vmf->page);
6150 	folio_unlock(folio);
6151 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
6152 		folio_put(folio);
6153 	return ret;
6154 }
6155 
6156 static vm_fault_t do_cow_fault(struct vm_fault *vmf)
6157 {
6158 	struct vm_area_struct *vma = vmf->vma;
6159 	struct folio *folio;
6160 	vm_fault_t ret;
6161 
6162 	ret = vmf_can_call_fault(vmf);
6163 	if (!ret)
6164 		ret = vmf_anon_prepare(vmf);
6165 	if (ret)
6166 		return ret;
6167 
6168 	folio = folio_prealloc(vma->vm_mm, vma, vmf->address, false);
6169 	if (!folio)
6170 		return VM_FAULT_OOM;
6171 
6172 	vmf->cow_page = &folio->page;
6173 
6174 	ret = __do_fault(vmf);
6175 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
6176 		goto uncharge_out;
6177 	if (ret & VM_FAULT_DONE_COW)
6178 		return ret;
6179 
6180 	if (copy_mc_user_highpage(vmf->cow_page, vmf->page, vmf->address, vma)) {
6181 		ret = VM_FAULT_HWPOISON;
6182 		goto unlock;
6183 	}
6184 	__folio_mark_uptodate(folio);
6185 
6186 	ret |= finish_fault(vmf);
6187 unlock:
6188 	unlock_page(vmf->page);
6189 	put_page(vmf->page);
6190 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
6191 		goto uncharge_out;
6192 	return ret;
6193 uncharge_out:
6194 	folio_put(folio);
6195 	return ret;
6196 }
6197 
6198 static vm_fault_t do_shared_fault(struct vm_fault *vmf)
6199 {
6200 	struct vm_area_struct *vma = vmf->vma;
6201 	vm_fault_t ret, tmp;
6202 	struct folio *folio;
6203 
6204 	ret = vmf_can_call_fault(vmf);
6205 	if (ret)
6206 		return ret;
6207 
6208 	ret = __do_fault(vmf);
6209 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE | VM_FAULT_RETRY)))
6210 		return ret;
6211 
6212 	folio = page_folio(vmf->page);
6213 
6214 	/*
6215 	 * Check if the backing address space wants to know that the page is
6216 	 * about to become writable
6217 	 */
6218 	if (vma->vm_ops->page_mkwrite) {
6219 		folio_unlock(folio);
6220 		tmp = do_page_mkwrite(vmf, folio);
6221 		if (unlikely(!tmp ||
6222 				(tmp & (VM_FAULT_ERROR | VM_FAULT_NOPAGE)))) {
6223 			folio_put(folio);
6224 			return tmp;
6225 		}
6226 	}
6227 
6228 	ret |= finish_fault(vmf);
6229 	if (unlikely(ret & (VM_FAULT_ERROR | VM_FAULT_NOPAGE |
6230 					VM_FAULT_RETRY))) {
6231 		folio_unlock(folio);
6232 		folio_put(folio);
6233 		return ret;
6234 	}
6235 
6236 	ret |= fault_dirty_shared_page(vmf);
6237 	return ret;
6238 }
6239 
6240 /*
6241  * We enter with either the VMA lock or the mmap_lock held (see
6242  * FAULT_FLAG_VMA_LOCK).
6243  * The lock may have been released depending on flags and our
6244  * return value.  See filemap_fault() and __folio_lock_or_retry().
6245  * If the lock is released, vma may become invalid (for example
6246  * by other thread calling munmap()).
6247  */
6248 static vm_fault_t do_fault(struct vm_fault *vmf)
6249 {
6250 	struct vm_area_struct *vma = vmf->vma;
6251 	struct mm_struct *vm_mm = vma->vm_mm;
6252 	vm_fault_t ret;
6253 
6254 	/*
6255 	 * The VMA was not fully populated on mmap() or missing VM_DONTEXPAND
6256 	 */
6257 	if (!vma->vm_ops->fault) {
6258 		vmf->pte = pte_offset_map_lock(vmf->vma->vm_mm, vmf->pmd,
6259 					       vmf->address, &vmf->ptl);
6260 		if (unlikely(!vmf->pte))
6261 			ret = VM_FAULT_SIGBUS;
6262 		else {
6263 			/*
6264 			 * Make sure this is not a temporary clearing of pte
6265 			 * by holding ptl and checking again. A R/M/W update
6266 			 * of pte involves: take ptl, clearing the pte so that
6267 			 * we don't have concurrent modification by hardware
6268 			 * followed by an update.
6269 			 */
6270 			if (unlikely(pte_none(ptep_get(vmf->pte))))
6271 				ret = VM_FAULT_SIGBUS;
6272 			else
6273 				ret = VM_FAULT_NOPAGE;
6274 
6275 			pte_unmap_unlock(vmf->pte, vmf->ptl);
6276 		}
6277 	} else if (!(vmf->flags & FAULT_FLAG_WRITE))
6278 		ret = do_read_fault(vmf);
6279 	else if (!(vma->vm_flags & VM_SHARED))
6280 		ret = do_cow_fault(vmf);
6281 	else
6282 		ret = do_shared_fault(vmf);
6283 
6284 	/* preallocated pagetable is unused: free it */
6285 	if (vmf->prealloc_pte) {
6286 		pte_free(vm_mm, vmf->prealloc_pte);
6287 		vmf->prealloc_pte = NULL;
6288 	}
6289 	return ret;
6290 }
6291 
6292 int numa_migrate_check(struct folio *folio, struct vm_fault *vmf,
6293 		      unsigned long addr, int *flags,
6294 		      bool writable, int *last_cpupid)
6295 {
6296 	struct vm_area_struct *vma = vmf->vma;
6297 
6298 	/*
6299 	 * Avoid grouping on RO pages in general. RO pages shouldn't hurt as
6300 	 * much anyway since they can be in shared cache state. This misses
6301 	 * the case where a mapping is writable but the process never writes
6302 	 * to it but pte_write gets cleared during protection updates and
6303 	 * pte_dirty has unpredictable behaviour between PTE scan updates,
6304 	 * background writeback, dirty balancing and application behaviour.
6305 	 */
6306 	if (!writable)
6307 		*flags |= TNF_NO_GROUP;
6308 
6309 	/*
6310 	 * Flag if the folio is shared between multiple address spaces. This
6311 	 * is later used when determining whether to group tasks together
6312 	 */
6313 	if (folio_maybe_mapped_shared(folio) && (vma->vm_flags & VM_SHARED))
6314 		*flags |= TNF_SHARED;
6315 	/*
6316 	 * For memory tiering mode, cpupid of slow memory page is used
6317 	 * to record page access time.  So use default value.
6318 	 */
6319 	if (folio_use_access_time(folio))
6320 		*last_cpupid = (-1 & LAST_CPUPID_MASK);
6321 	else
6322 		*last_cpupid = folio_last_cpupid(folio);
6323 
6324 	/* Record the current PID accessing VMA */
6325 	vma_set_access_pid_bit(vma);
6326 
6327 	count_vm_numa_event(NUMA_HINT_FAULTS);
6328 #ifdef CONFIG_NUMA_BALANCING
6329 	count_memcg_folio_events(folio, NUMA_HINT_FAULTS, 1);
6330 #endif
6331 	if (folio_nid(folio) == numa_node_id()) {
6332 		count_vm_numa_event(NUMA_HINT_FAULTS_LOCAL);
6333 		*flags |= TNF_FAULT_LOCAL;
6334 	}
6335 
6336 	return mpol_misplaced(folio, vmf, addr);
6337 }
6338 
6339 static void numa_rebuild_single_mapping(struct vm_fault *vmf, struct vm_area_struct *vma,
6340 					unsigned long fault_addr, pte_t *fault_pte,
6341 					bool writable)
6342 {
6343 	pte_t pte, old_pte;
6344 
6345 	old_pte = ptep_modify_prot_start(vma, fault_addr, fault_pte);
6346 	pte = pte_modify(old_pte, vma->vm_page_prot);
6347 	pte = pte_mkyoung(pte);
6348 	if (writable)
6349 		pte = pte_mkwrite(pte, vma);
6350 	ptep_modify_prot_commit(vma, fault_addr, fault_pte, old_pte, pte);
6351 	update_mmu_cache_range(vmf, vma, fault_addr, fault_pte, 1);
6352 }
6353 
6354 static void numa_rebuild_large_mapping(struct vm_fault *vmf, struct vm_area_struct *vma,
6355 				       struct folio *folio, pte_t fault_pte,
6356 				       bool ignore_writable, bool pte_write_upgrade)
6357 {
6358 	const unsigned long idx = pte_pfn(fault_pte) - folio_pfn(folio);
6359 	unsigned long start, end, addr = vmf->address;
6360 	pte_t *start_ptep;
6361 
6362 	folio_pte_range(folio, vma, addr, idx, &start, &end);
6363 	start_ptep = vmf->pte - ((addr - start) >> PAGE_SHIFT);
6364 
6365 	/* Restore all PTEs' mapping of the large folio */
6366 	for (addr = start; addr != end; start_ptep++, addr += PAGE_SIZE) {
6367 		pte_t ptent = ptep_get(start_ptep);
6368 		bool writable = false;
6369 
6370 		if (!pte_present(ptent) || !pte_protnone(ptent))
6371 			continue;
6372 
6373 		/*
6374 		 * RWP-armed PTEs are also protnone but carry _PAGE_UFFD as a
6375 		 * marker. Leave them alone -- rewriting to vm_page_prot would
6376 		 * stop the RWP trap. Gate on userfaultfd_rwp(vma) too:
6377 		 * NUMA balancing preserves _PAGE_UFFD on UFFD_WP-marked PTEs
6378 		 * when applying PROT_NONE, and those still need rebuilding.
6379 		 */
6380 		if (userfaultfd_rwp(vma) && pte_uffd(ptent))
6381 			continue;
6382 
6383 		if (pfn_folio(pte_pfn(ptent)) != folio)
6384 			continue;
6385 
6386 		if (!ignore_writable) {
6387 			ptent = pte_modify(ptent, vma->vm_page_prot);
6388 			writable = pte_write(ptent);
6389 			if (!writable && pte_write_upgrade &&
6390 			    can_change_pte_writable(vma, addr, ptent))
6391 				writable = true;
6392 		}
6393 
6394 		numa_rebuild_single_mapping(vmf, vma, addr, start_ptep, writable);
6395 	}
6396 }
6397 
6398 static vm_fault_t do_uffd_rwp(struct vm_fault *vmf)
6399 {
6400 	pte_t pte;
6401 
6402 	if (!userfaultfd_rwp_async(vmf->vma)) {
6403 		/* Sync mode: unmap PTE and deliver to userfaultfd handler */
6404 		pte_unmap(vmf->pte);
6405 		return handle_userfault(vmf, VM_UFFD_RWP);
6406 	}
6407 
6408 	spin_lock(vmf->ptl);
6409 	if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
6410 		pte_unmap_unlock(vmf->pte, vmf->ptl);
6411 		return 0;
6412 	}
6413 	pte = pte_modify(vmf->orig_pte, vmf->vma->vm_page_prot);
6414 	/* pte_modify() preserves _PAGE_UFFD; drop it on resolution */
6415 	pte = pte_clear_uffd(pte);
6416 	pte = pte_mkyoung(pte);
6417 	if (!pte_write(pte) &&
6418 	    vma_wants_manual_pte_write_upgrade(vmf->vma) &&
6419 	    can_change_pte_writable(vmf->vma, vmf->address, pte))
6420 		pte = pte_mkwrite(pte, vmf->vma);
6421 	set_pte_at(vmf->vma->vm_mm, vmf->address, vmf->pte, pte);
6422 	update_mmu_cache(vmf->vma, vmf->address, vmf->pte);
6423 	pte_unmap_unlock(vmf->pte, vmf->ptl);
6424 	return 0;
6425 }
6426 
6427 static vm_fault_t do_numa_page(struct vm_fault *vmf)
6428 {
6429 	struct vm_area_struct *vma = vmf->vma;
6430 	struct folio *folio = NULL;
6431 	int nid = NUMA_NO_NODE;
6432 	bool writable = false, ignore_writable = false;
6433 	bool pte_write_upgrade = vma_wants_manual_pte_write_upgrade(vma);
6434 	int last_cpupid;
6435 	int target_nid;
6436 	pte_t pte, old_pte;
6437 	int flags = 0, nr_pages;
6438 
6439 	/*
6440 	 * The pte cannot be used safely until we verify, while holding the page
6441 	 * table lock, that its contents have not changed during fault handling.
6442 	 */
6443 	spin_lock(vmf->ptl);
6444 	/* Read the live PTE from the page tables: */
6445 	old_pte = ptep_get(vmf->pte);
6446 
6447 	if (unlikely(!pte_same(old_pte, vmf->orig_pte))) {
6448 		pte_unmap_unlock(vmf->pte, vmf->ptl);
6449 		return 0;
6450 	}
6451 
6452 	pte = pte_modify(old_pte, vma->vm_page_prot);
6453 
6454 	/*
6455 	 * Detect now whether the PTE could be writable; this information
6456 	 * is only valid while holding the PT lock.
6457 	 */
6458 	writable = pte_write(pte);
6459 	if (!writable && pte_write_upgrade &&
6460 	    can_change_pte_writable(vma, vmf->address, pte))
6461 		writable = true;
6462 
6463 	folio = vm_normal_folio(vma, vmf->address, pte);
6464 	if (!folio || folio_is_zone_device(folio))
6465 		goto out_map;
6466 
6467 	nid = folio_nid(folio);
6468 	nr_pages = folio_nr_pages(folio);
6469 
6470 	target_nid = numa_migrate_check(folio, vmf, vmf->address, &flags,
6471 					writable, &last_cpupid);
6472 	if (target_nid == NUMA_NO_NODE)
6473 		goto out_map;
6474 	if (migrate_misplaced_folio_prepare(folio, vma, target_nid)) {
6475 		flags |= TNF_MIGRATE_FAIL;
6476 		goto out_map;
6477 	}
6478 	/* The folio is isolated and isolation code holds a folio reference. */
6479 	pte_unmap_unlock(vmf->pte, vmf->ptl);
6480 	writable = false;
6481 	ignore_writable = true;
6482 
6483 	/* Migrate to the requested node */
6484 	if (!migrate_misplaced_folio(folio, target_nid)) {
6485 		nid = target_nid;
6486 		flags |= TNF_MIGRATED;
6487 		task_numa_fault(last_cpupid, nid, nr_pages, flags);
6488 		return 0;
6489 	}
6490 
6491 	flags |= TNF_MIGRATE_FAIL;
6492 	vmf->pte = pte_offset_map_lock(vma->vm_mm, vmf->pmd,
6493 				       vmf->address, &vmf->ptl);
6494 	if (unlikely(!vmf->pte))
6495 		return 0;
6496 	if (unlikely(!pte_same(ptep_get(vmf->pte), vmf->orig_pte))) {
6497 		pte_unmap_unlock(vmf->pte, vmf->ptl);
6498 		return 0;
6499 	}
6500 out_map:
6501 	/*
6502 	 * Make it present again, depending on how arch implements
6503 	 * non-accessible ptes, some can allow access by kernel mode.
6504 	 */
6505 	if (folio && folio_test_large(folio))
6506 		numa_rebuild_large_mapping(vmf, vma, folio, pte, ignore_writable,
6507 					   pte_write_upgrade);
6508 	else
6509 		numa_rebuild_single_mapping(vmf, vma, vmf->address, vmf->pte,
6510 					    writable);
6511 	pte_unmap_unlock(vmf->pte, vmf->ptl);
6512 
6513 	if (nid != NUMA_NO_NODE)
6514 		task_numa_fault(last_cpupid, nid, nr_pages, flags);
6515 	return 0;
6516 }
6517 
6518 static inline vm_fault_t create_huge_pmd(struct vm_fault *vmf)
6519 {
6520 	struct vm_area_struct *vma = vmf->vma;
6521 	if (vma_is_anonymous(vma))
6522 		return do_huge_pmd_anonymous_page(vmf);
6523 	if (vma->vm_ops->huge_fault)
6524 		return vma->vm_ops->huge_fault(vmf, PMD_ORDER);
6525 	return VM_FAULT_FALLBACK;
6526 }
6527 
6528 /* `inline' is required to avoid gcc 4.1.2 build error */
6529 static inline vm_fault_t wp_huge_pmd(struct vm_fault *vmf)
6530 {
6531 	struct vm_area_struct *vma = vmf->vma;
6532 	const bool unshare = vmf->flags & FAULT_FLAG_UNSHARE;
6533 	vm_fault_t ret;
6534 
6535 	if (vma_is_anonymous(vma)) {
6536 		if (likely(!unshare) &&
6537 		    userfaultfd_huge_pmd_wp(vma, vmf->orig_pmd)) {
6538 			if (userfaultfd_wp_async(vmf->vma))
6539 				goto split;
6540 			return handle_userfault(vmf, VM_UFFD_WP);
6541 		}
6542 		return do_huge_pmd_wp_page(vmf);
6543 	}
6544 
6545 	if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
6546 		if (vma->vm_ops->huge_fault) {
6547 			ret = vma->vm_ops->huge_fault(vmf, PMD_ORDER);
6548 			if (!(ret & VM_FAULT_FALLBACK))
6549 				return ret;
6550 		}
6551 	}
6552 
6553 split:
6554 	/* COW or write-notify handled on pte level: split pmd. */
6555 	__split_huge_pmd(vma, vmf->pmd, vmf->address, false);
6556 
6557 	return VM_FAULT_FALLBACK;
6558 }
6559 
6560 static vm_fault_t create_huge_pud(struct vm_fault *vmf)
6561 {
6562 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) &&			\
6563 	defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
6564 	struct vm_area_struct *vma = vmf->vma;
6565 	/* No support for anonymous transparent PUD pages yet */
6566 	if (vma_is_anonymous(vma))
6567 		return VM_FAULT_FALLBACK;
6568 	if (vma->vm_ops->huge_fault)
6569 		return vma->vm_ops->huge_fault(vmf, PUD_ORDER);
6570 #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
6571 	return VM_FAULT_FALLBACK;
6572 }
6573 
6574 static vm_fault_t wp_huge_pud(struct vm_fault *vmf, pud_t orig_pud)
6575 {
6576 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) &&			\
6577 	defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)
6578 	struct vm_area_struct *vma = vmf->vma;
6579 	vm_fault_t ret;
6580 
6581 	/* No support for anonymous transparent PUD pages yet */
6582 	if (vma_is_anonymous(vma))
6583 		goto split;
6584 	if (vma->vm_flags & (VM_SHARED | VM_MAYSHARE)) {
6585 		if (vma->vm_ops->huge_fault) {
6586 			ret = vma->vm_ops->huge_fault(vmf, PUD_ORDER);
6587 			if (!(ret & VM_FAULT_FALLBACK))
6588 				return ret;
6589 		}
6590 	}
6591 split:
6592 	/* COW or write-notify not handled on PUD level: split pud.*/
6593 	__split_huge_pud(vma, vmf->pud, vmf->address);
6594 #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */
6595 	return VM_FAULT_FALLBACK;
6596 }
6597 
6598 /*
6599  * The page faults may be spurious because of the racy access to the
6600  * page table.  For example, a non-populated virtual page is accessed
6601  * on 2 CPUs simultaneously, thus the page faults are triggered on
6602  * both CPUs.  However, it's possible that one CPU (say CPU A) cannot
6603  * find the reason for the page fault if the other CPU (say CPU B) has
6604  * changed the page table before the PTE is checked on CPU A.  Most of
6605  * the time, the spurious page faults can be ignored safely.  However,
6606  * if the page fault is for the write access, it's possible that a
6607  * stale read-only TLB entry exists in the local CPU and needs to be
6608  * flushed on some architectures.  This is called the spurious page
6609  * fault fixing.
6610  *
6611  * Note: flush_tlb_fix_spurious_fault() is defined as flush_tlb_page()
6612  * by default and used as such on most architectures, while
6613  * flush_tlb_fix_spurious_fault_pmd() is defined as NOP by default and
6614  * used as such on most architectures.
6615  */
6616 static void fix_spurious_fault(struct vm_fault *vmf,
6617 			       enum pgtable_level ptlevel)
6618 {
6619 	/* Skip spurious TLB flush for retried page fault */
6620 	if (vmf->flags & FAULT_FLAG_TRIED)
6621 		return;
6622 	/*
6623 	 * This is needed only for protection faults but the arch code
6624 	 * is not yet telling us if this is a protection fault or not.
6625 	 * This still avoids useless tlb flushes for .text page faults
6626 	 * with threads.
6627 	 */
6628 	if (vmf->flags & FAULT_FLAG_WRITE) {
6629 		if (ptlevel == PGTABLE_LEVEL_PTE)
6630 			flush_tlb_fix_spurious_fault(vmf->vma, vmf->address,
6631 						     vmf->pte);
6632 		else
6633 			flush_tlb_fix_spurious_fault_pmd(vmf->vma, vmf->address,
6634 							 vmf->pmd);
6635 	}
6636 }
6637 /*
6638  * These routines also need to handle stuff like marking pages dirty
6639  * and/or accessed for architectures that don't do it in hardware (most
6640  * RISC architectures).  The early dirtying is also good on the i386.
6641  *
6642  * There is also a hook called "update_mmu_cache()" that architectures
6643  * with external mmu caches can use to update those (ie the Sparc or
6644  * PowerPC hashed page tables that act as extended TLBs).
6645  *
6646  * On entry, we hold either the VMA lock or the mmap_lock
6647  * (see FAULT_FLAG_VMA_LOCK).
6648  *
6649  * The mmap_lock or VMA lock may have been released depending on flags
6650  * and our return value.
6651  * See filemap_fault() and __folio_lock_or_retry().
6652  */
6653 static vm_fault_t handle_pte_fault(struct vm_fault *vmf)
6654 {
6655 	pte_t entry;
6656 
6657 	if (unlikely(pmd_none(*vmf->pmd))) {
6658 		/*
6659 		 * Leave __pte_alloc() until later: because vm_ops->fault may
6660 		 * want to allocate huge page, and if we expose page table
6661 		 * for an instant, it will be difficult to retract from
6662 		 * concurrent faults and from rmap lookups.
6663 		 */
6664 		vmf->pte = NULL;
6665 		vmf->flags &= ~FAULT_FLAG_ORIG_PTE_VALID;
6666 	} else {
6667 		pmd_t dummy_pmdval;
6668 
6669 		/*
6670 		 * A regular pmd is established and it can't morph into a huge
6671 		 * pmd by anon khugepaged, since that takes mmap_lock in write
6672 		 * mode; but shmem or file collapse to THP could still morph
6673 		 * it into a huge pmd: just retry later if so.
6674 		 *
6675 		 * Use the maywrite version to indicate that vmf->pte may be
6676 		 * modified, but since we will use pte_same() to detect the
6677 		 * change of the !pte_none() entry, there is no need to recheck
6678 		 * the pmdval. Here we choose to pass a dummy variable instead
6679 		 * of NULL, which helps new user think about why this place is
6680 		 * special.
6681 		 */
6682 		vmf->pte = pte_offset_map_rw_nolock(vmf->vma->vm_mm, vmf->pmd,
6683 						    vmf->address, &dummy_pmdval,
6684 						    &vmf->ptl);
6685 		if (unlikely(!vmf->pte))
6686 			return 0;
6687 		vmf->orig_pte = ptep_get_lockless(vmf->pte);
6688 		vmf->flags |= FAULT_FLAG_ORIG_PTE_VALID;
6689 
6690 		if (pte_none(vmf->orig_pte)) {
6691 			pte_unmap(vmf->pte);
6692 			vmf->pte = NULL;
6693 		}
6694 	}
6695 
6696 	if (!vmf->pte)
6697 		return do_pte_missing(vmf);
6698 
6699 	if (!pte_present(vmf->orig_pte))
6700 		return do_swap_page(vmf);
6701 
6702 	if (pte_protnone(vmf->orig_pte) && vma_is_accessible(vmf->vma)) {
6703 		/*
6704 		 * RWP-protected PTEs are protnone plus the uffd bit. On a
6705 		 * VM_UFFD_RWP VMA, a protnone PTE without the uffd bit is
6706 		 * NUMA hinting and must still fall through to do_numa_page().
6707 		 */
6708 		if (userfaultfd_pte_rwp(vmf->vma, vmf->orig_pte)) {
6709 			if (!(vmf->flags & FAULT_FLAG_UNSHARE))
6710 				return do_uffd_rwp(vmf);
6711 		} else {
6712 			return do_numa_page(vmf);
6713 		}
6714 	}
6715 
6716 	spin_lock(vmf->ptl);
6717 	entry = vmf->orig_pte;
6718 	if (unlikely(!pte_same(ptep_get(vmf->pte), entry))) {
6719 		update_mmu_tlb(vmf->vma, vmf->address, vmf->pte);
6720 		goto unlock;
6721 	}
6722 	if (vmf->flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) {
6723 		if (!pte_write(entry))
6724 			return do_wp_page(vmf);
6725 		else if (likely(vmf->flags & FAULT_FLAG_WRITE))
6726 			entry = pte_mkdirty(entry);
6727 	}
6728 	entry = pte_mkyoung(entry);
6729 	if (ptep_set_access_flags(vmf->vma, vmf->address, vmf->pte, entry,
6730 				vmf->flags & FAULT_FLAG_WRITE))
6731 		update_mmu_cache_range(vmf, vmf->vma, vmf->address,
6732 				vmf->pte, 1);
6733 	else
6734 		fix_spurious_fault(vmf, PGTABLE_LEVEL_PTE);
6735 unlock:
6736 	pte_unmap_unlock(vmf->pte, vmf->ptl);
6737 	return 0;
6738 }
6739 
6740 /*
6741  * On entry, we hold either the VMA lock or the mmap_lock
6742  * (see FAULT_FLAG_VMA_LOCK).  If VM_FAULT_RETRY is set in
6743  * the result, the lock is not held on exit.  See filemap_fault()
6744  * and __folio_lock_or_retry().
6745  */
6746 static vm_fault_t __handle_mm_fault(struct vm_area_struct *vma,
6747 		unsigned long address, unsigned int flags)
6748 {
6749 	struct vm_fault vmf = {
6750 		.vma = vma,
6751 		.address = address & PAGE_MASK,
6752 		.real_address = address,
6753 		.flags = flags,
6754 		.pgoff = linear_page_index(vma, address),
6755 		.gfp_mask = __get_fault_gfp_mask(vma),
6756 	};
6757 	struct mm_struct *mm = vma->vm_mm;
6758 	vm_flags_t vm_flags = vma->vm_flags;
6759 	pgd_t *pgd;
6760 	p4d_t *p4d;
6761 	vm_fault_t ret;
6762 
6763 	pgd = pgd_offset(mm, address);
6764 	p4d = p4d_alloc(mm, pgd, address);
6765 	if (!p4d)
6766 		return VM_FAULT_OOM;
6767 
6768 	vmf.pud = pud_alloc(mm, p4d, address);
6769 	if (!vmf.pud)
6770 		return VM_FAULT_OOM;
6771 retry_pud:
6772 	if (pud_none(*vmf.pud) &&
6773 	    thp_vma_allowable_order(vma, vm_flags, TVA_PAGEFAULT, PUD_ORDER)) {
6774 		ret = create_huge_pud(&vmf);
6775 		if (!(ret & VM_FAULT_FALLBACK))
6776 			return ret;
6777 	} else {
6778 		pud_t orig_pud = *vmf.pud;
6779 
6780 		barrier();
6781 		if (pud_trans_huge(orig_pud)) {
6782 
6783 			/*
6784 			 * TODO once we support anonymous PUDs: NUMA case and
6785 			 * FAULT_FLAG_UNSHARE handling.
6786 			 */
6787 			if ((flags & FAULT_FLAG_WRITE) && !pud_write(orig_pud)) {
6788 				ret = wp_huge_pud(&vmf, orig_pud);
6789 				if (!(ret & VM_FAULT_FALLBACK))
6790 					return ret;
6791 			} else {
6792 				huge_pud_set_accessed(&vmf, orig_pud);
6793 				return 0;
6794 			}
6795 		}
6796 	}
6797 
6798 	vmf.pmd = pmd_alloc(mm, vmf.pud, address);
6799 	if (!vmf.pmd)
6800 		return VM_FAULT_OOM;
6801 
6802 	/* Huge pud page fault raced with pmd_alloc? */
6803 	if (pud_trans_unstable(vmf.pud))
6804 		goto retry_pud;
6805 
6806 	if (pmd_none(*vmf.pmd) &&
6807 	    thp_vma_allowable_order(vma, vm_flags, TVA_PAGEFAULT, PMD_ORDER)) {
6808 		ret = create_huge_pmd(&vmf);
6809 		if (ret & VM_FAULT_FALLBACK)
6810 			goto fallback;
6811 		else
6812 			return ret;
6813 	}
6814 
6815 	vmf.orig_pmd = pmdp_get_lockless(vmf.pmd);
6816 	if (pmd_none(vmf.orig_pmd))
6817 		goto fallback;
6818 
6819 	if (unlikely(!pmd_present(vmf.orig_pmd))) {
6820 		if (pmd_is_device_private_entry(vmf.orig_pmd))
6821 			return do_huge_pmd_device_private(&vmf);
6822 
6823 		if (pmd_is_migration_entry(vmf.orig_pmd))
6824 			pmd_migration_entry_wait(mm, vmf.pmd);
6825 		return 0;
6826 	}
6827 	if (pmd_trans_huge(vmf.orig_pmd)) {
6828 		if (pmd_protnone(vmf.orig_pmd) && vma_is_accessible(vma)) {
6829 			if (userfaultfd_huge_pmd_rwp(vma, vmf.orig_pmd))
6830 				return do_huge_pmd_uffd_rwp(&vmf);
6831 			return do_huge_pmd_numa_page(&vmf);
6832 		}
6833 
6834 		if ((flags & (FAULT_FLAG_WRITE|FAULT_FLAG_UNSHARE)) &&
6835 		    !pmd_write(vmf.orig_pmd)) {
6836 			ret = wp_huge_pmd(&vmf);
6837 			if (!(ret & VM_FAULT_FALLBACK))
6838 				return ret;
6839 		} else {
6840 			vmf.ptl = pmd_lock(mm, vmf.pmd);
6841 			if (!huge_pmd_set_accessed(&vmf))
6842 				fix_spurious_fault(&vmf, PGTABLE_LEVEL_PMD);
6843 			spin_unlock(vmf.ptl);
6844 			return 0;
6845 		}
6846 	}
6847 
6848 fallback:
6849 	return handle_pte_fault(&vmf);
6850 }
6851 
6852 /**
6853  * mm_account_fault - Do page fault accounting
6854  * @mm: mm from which memcg should be extracted. It can be NULL.
6855  * @regs: the pt_regs struct pointer.  When set to NULL, will skip accounting
6856  *        of perf event counters, but we'll still do the per-task accounting to
6857  *        the task who triggered this page fault.
6858  * @address: the faulted address.
6859  * @flags: the fault flags.
6860  * @ret: the fault retcode.
6861  *
6862  * This will take care of most of the page fault accounting.  Meanwhile, it
6863  * will also include the PERF_COUNT_SW_PAGE_FAULTS_[MAJ|MIN] perf counter
6864  * updates.  However, note that the handling of PERF_COUNT_SW_PAGE_FAULTS should
6865  * still be in per-arch page fault handlers at the entry of page fault.
6866  */
6867 static inline void mm_account_fault(struct mm_struct *mm, struct pt_regs *regs,
6868 				    unsigned long address, unsigned int flags,
6869 				    vm_fault_t ret)
6870 {
6871 	bool major;
6872 
6873 	/* Incomplete faults will be accounted upon completion. */
6874 	if (ret & VM_FAULT_RETRY)
6875 		return;
6876 
6877 	/*
6878 	 * To preserve the behavior of older kernels, PGFAULT counters record
6879 	 * both successful and failed faults, as opposed to perf counters,
6880 	 * which ignore failed cases.
6881 	 */
6882 	count_vm_event(PGFAULT);
6883 	count_memcg_event_mm(mm, PGFAULT);
6884 
6885 	/*
6886 	 * Do not account for unsuccessful faults (e.g. when the address wasn't
6887 	 * valid).  That includes arch_vma_access_permitted() failing before
6888 	 * reaching here. So this is not a "this many hardware page faults"
6889 	 * counter.  We should use the hw profiling for that.
6890 	 */
6891 	if (ret & VM_FAULT_ERROR)
6892 		return;
6893 
6894 	/*
6895 	 * We define the fault as a major fault when the final successful fault
6896 	 * is VM_FAULT_MAJOR, or if it retried (which implies that we couldn't
6897 	 * handle it immediately previously).
6898 	 */
6899 	major = (ret & VM_FAULT_MAJOR) || (flags & FAULT_FLAG_TRIED);
6900 
6901 	if (major)
6902 		current->maj_flt++;
6903 	else
6904 		current->min_flt++;
6905 
6906 	/*
6907 	 * If the fault is done for GUP, regs will be NULL.  We only do the
6908 	 * accounting for the per thread fault counters who triggered the
6909 	 * fault, and we skip the perf event updates.
6910 	 */
6911 	if (!regs)
6912 		return;
6913 
6914 	if (major)
6915 		perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, address);
6916 	else
6917 		perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, address);
6918 }
6919 
6920 #ifdef CONFIG_LRU_GEN
6921 static void lru_gen_enter_fault(struct vm_area_struct *vma)
6922 {
6923 	/* the LRU algorithm only applies to accesses with recency */
6924 	current->in_lru_fault = vma_has_recency(vma);
6925 }
6926 
6927 static void lru_gen_exit_fault(void)
6928 {
6929 	current->in_lru_fault = false;
6930 }
6931 #else
6932 static void lru_gen_enter_fault(struct vm_area_struct *vma)
6933 {
6934 }
6935 
6936 static void lru_gen_exit_fault(void)
6937 {
6938 }
6939 #endif /* CONFIG_LRU_GEN */
6940 
6941 static vm_fault_t sanitize_fault_flags(struct vm_area_struct *vma,
6942 				       unsigned int *flags)
6943 {
6944 	if (unlikely(*flags & FAULT_FLAG_UNSHARE)) {
6945 		if (WARN_ON_ONCE(*flags & FAULT_FLAG_WRITE))
6946 			return VM_FAULT_SIGSEGV;
6947 		/*
6948 		 * FAULT_FLAG_UNSHARE only applies to COW mappings. Let's
6949 		 * just treat it like an ordinary read-fault otherwise.
6950 		 */
6951 		if (!vma_is_cow_mapping(vma))
6952 			*flags &= ~FAULT_FLAG_UNSHARE;
6953 	} else if (*flags & FAULT_FLAG_WRITE) {
6954 		/* Write faults on read-only mappings are impossible ... */
6955 		if (WARN_ON_ONCE(!(vma->vm_flags & VM_MAYWRITE)))
6956 			return VM_FAULT_SIGSEGV;
6957 		/* ... and FOLL_FORCE only applies to COW mappings. */
6958 		if (WARN_ON_ONCE(!(vma->vm_flags & VM_WRITE) &&
6959 				 !vma_is_cow_mapping(vma)))
6960 			return VM_FAULT_SIGSEGV;
6961 	}
6962 	/*
6963 	 * Per-VMA locks can't be used with FAULT_FLAG_RETRY_NOWAIT because of
6964 	 * the assumption that lock is dropped on VM_FAULT_RETRY.
6965 	 */
6966 	if (WARN_ON_ONCE((*flags &
6967 			(FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)) ==
6968 			(FAULT_FLAG_VMA_LOCK | FAULT_FLAG_RETRY_NOWAIT)))
6969 		return VM_FAULT_SIGSEGV;
6970 
6971 	return 0;
6972 }
6973 
6974 /*
6975  * By the time we get here, we already hold either the VMA lock or the
6976  * mmap_lock (see FAULT_FLAG_VMA_LOCK).
6977  *
6978  * The lock may have been released depending on flags and our
6979  * return value.  See filemap_fault() and __folio_lock_or_retry().
6980  */
6981 vm_fault_t handle_mm_fault(struct vm_area_struct *vma, unsigned long address,
6982 			   unsigned int flags, struct pt_regs *regs)
6983 {
6984 	/* If the fault handler drops the mmap_lock, vma may be freed */
6985 	struct mm_struct *mm = vma->vm_mm;
6986 	vm_fault_t ret;
6987 	bool is_droppable;
6988 
6989 	__set_current_state(TASK_RUNNING);
6990 
6991 	ret = sanitize_fault_flags(vma, &flags);
6992 	if (ret)
6993 		goto out;
6994 
6995 	if (!arch_vma_access_permitted(vma, flags & FAULT_FLAG_WRITE,
6996 					    flags & FAULT_FLAG_INSTRUCTION,
6997 					    flags & FAULT_FLAG_REMOTE)) {
6998 		ret = VM_FAULT_SIGSEGV;
6999 		goto out;
7000 	}
7001 
7002 	is_droppable = !!(vma->vm_flags & VM_DROPPABLE);
7003 
7004 	/*
7005 	 * Enable the memcg OOM handling for faults triggered in user
7006 	 * space.  Kernel faults are handled more gracefully.
7007 	 */
7008 	if (flags & FAULT_FLAG_USER)
7009 		mem_cgroup_enter_user_fault();
7010 
7011 	lru_gen_enter_fault(vma);
7012 
7013 	if (unlikely(vma_is_hugetlb(vma)))
7014 		ret = hugetlb_fault(vma->vm_mm, vma, address, flags);
7015 	else
7016 		ret = __handle_mm_fault(vma, address, flags);
7017 
7018 	/*
7019 	 * Warning: It is no longer safe to dereference vma-> after this point,
7020 	 * because mmap_lock might have been dropped by __handle_mm_fault(), so
7021 	 * vma might be destroyed from underneath us.
7022 	 */
7023 
7024 	lru_gen_exit_fault();
7025 
7026 	/*
7027 	 * If the mapping is droppable, then errors due to OOM aren't fatal: the
7028 	 * task returns to user mode, handles its signals and tries again. A
7029 	 * fault from kernel mode has no such return, so it must see the error.
7030 	 */
7031 	if (is_droppable && (flags & FAULT_FLAG_USER))
7032 		ret &= ~VM_FAULT_OOM;
7033 
7034 	if (flags & FAULT_FLAG_USER) {
7035 		mem_cgroup_exit_user_fault();
7036 		/*
7037 		 * The task may have entered a memcg OOM situation but
7038 		 * if the allocation error was handled gracefully (no
7039 		 * VM_FAULT_OOM), there is no need to kill anything.
7040 		 * Just clean up the OOM state peacefully.
7041 		 */
7042 		if (task_in_memcg_oom(current) && !(ret & VM_FAULT_OOM))
7043 			mem_cgroup_oom_synchronize(false);
7044 	}
7045 out:
7046 	mm_account_fault(mm, regs, address, flags, ret);
7047 
7048 	return ret;
7049 }
7050 EXPORT_SYMBOL_GPL(handle_mm_fault);
7051 
7052 #ifndef __PAGETABLE_P4D_FOLDED
7053 /*
7054  * Allocate p4d page table.
7055  * We've already handled the fast-path in-line.
7056  */
7057 int __p4d_alloc(struct mm_struct *mm, pgd_t *pgd, unsigned long address)
7058 {
7059 	p4d_t *new = p4d_alloc_one(mm, address);
7060 	if (!new)
7061 		return -ENOMEM;
7062 
7063 	spin_lock(&mm->page_table_lock);
7064 	if (pgd_present(*pgd)) {	/* Another has populated it */
7065 		p4d_free(mm, new);
7066 	} else {
7067 		smp_wmb(); /* See comment in pmd_install() */
7068 		pgd_populate(mm, pgd, new);
7069 	}
7070 	spin_unlock(&mm->page_table_lock);
7071 	return 0;
7072 }
7073 #endif /* __PAGETABLE_P4D_FOLDED */
7074 
7075 #ifndef __PAGETABLE_PUD_FOLDED
7076 /*
7077  * Allocate page upper directory.
7078  * We've already handled the fast-path in-line.
7079  */
7080 int __pud_alloc(struct mm_struct *mm, p4d_t *p4d, unsigned long address)
7081 {
7082 	pud_t *new = pud_alloc_one(mm, address);
7083 	if (!new)
7084 		return -ENOMEM;
7085 
7086 	spin_lock(&mm->page_table_lock);
7087 	if (!p4d_present(*p4d)) {
7088 		mm_inc_nr_puds(mm);
7089 		smp_wmb(); /* See comment in pmd_install() */
7090 		p4d_populate(mm, p4d, new);
7091 	} else	/* Another has populated it */
7092 		pud_free(mm, new);
7093 	spin_unlock(&mm->page_table_lock);
7094 	return 0;
7095 }
7096 #endif /* __PAGETABLE_PUD_FOLDED */
7097 
7098 #ifndef __PAGETABLE_PMD_FOLDED
7099 /*
7100  * Allocate page middle directory.
7101  * We've already handled the fast-path in-line.
7102  */
7103 int __pmd_alloc(struct mm_struct *mm, pud_t *pud, unsigned long address)
7104 {
7105 	spinlock_t *ptl;
7106 	pmd_t *new = pmd_alloc_one(mm, address);
7107 	if (!new)
7108 		return -ENOMEM;
7109 
7110 	ptl = pud_lock(mm, pud);
7111 	if (!pud_present(*pud)) {
7112 		mm_inc_nr_pmds(mm);
7113 		smp_wmb(); /* See comment in pmd_install() */
7114 		pud_populate(mm, pud, new);
7115 	} else {	/* Another has populated it */
7116 		pmd_free(mm, new);
7117 	}
7118 	spin_unlock(ptl);
7119 	return 0;
7120 }
7121 #endif /* __PAGETABLE_PMD_FOLDED */
7122 
7123 static inline void pfnmap_args_setup(struct follow_pfnmap_args *args,
7124 				     spinlock_t *lock, pte_t *ptep,
7125 				     pgprot_t pgprot, unsigned long pfn_base,
7126 				     unsigned long addr_mask, bool writable,
7127 				     bool special)
7128 {
7129 	args->lock = lock;
7130 	args->ptep = ptep;
7131 	args->pfn = pfn_base + ((args->address & ~addr_mask) >> PAGE_SHIFT);
7132 	args->addr_mask = addr_mask;
7133 	args->pgprot = pgprot;
7134 	args->writable = writable;
7135 	args->special = special;
7136 }
7137 
7138 static inline void pfnmap_lockdep_assert(struct vm_area_struct *vma)
7139 {
7140 #ifdef CONFIG_LOCKDEP
7141 	struct file *file = vma->vm_file;
7142 	struct address_space *mapping = file ? file->f_mapping : NULL;
7143 
7144 	if (mapping)
7145 		lockdep_assert(lockdep_is_held(&mapping->i_mmap_rwsem) ||
7146 			       lockdep_is_held(&vma->vm_mm->mmap_lock));
7147 	else
7148 		lockdep_assert(lockdep_is_held(&vma->vm_mm->mmap_lock));
7149 #endif
7150 }
7151 
7152 /**
7153  * follow_pfnmap_start() - Look up a pfn mapping at a user virtual address
7154  * @args: Pointer to struct @follow_pfnmap_args
7155  *
7156  * The caller needs to setup args->vma and args->address to point to the
7157  * virtual address as the target of such lookup.  On a successful return,
7158  * the results will be put into other output fields.
7159  *
7160  * After the caller finished using the fields, the caller must invoke
7161  * another follow_pfnmap_end() to proper releases the locks and resources
7162  * of such look up request.
7163  *
7164  * During the start() and end() calls, the results in @args will be valid
7165  * as proper locks will be held.  After the end() is called, all the fields
7166  * in @follow_pfnmap_args will be invalid to be further accessed.  Further
7167  * use of such information after end() may require proper synchronizations
7168  * by the caller with page table updates, otherwise it can create a
7169  * security bug.
7170  *
7171  * If the PTE maps a refcounted page, callers are responsible to protect
7172  * against invalidation with MMU notifiers; otherwise access to the PFN at
7173  * a later point in time can trigger use-after-free.
7174  *
7175  * Only IO mappings and raw PFN mappings are allowed.  The mmap semaphore
7176  * should be taken for read, and the mmap semaphore cannot be released
7177  * before the end() is invoked.
7178  *
7179  * This function must not be used to modify PTE content.
7180  *
7181  * Return: zero on success, negative otherwise.
7182  */
7183 int follow_pfnmap_start(struct follow_pfnmap_args *args)
7184 {
7185 	struct vm_area_struct *vma = args->vma;
7186 	unsigned long address = args->address;
7187 	struct mm_struct *mm = vma->vm_mm;
7188 	spinlock_t *lock;
7189 	pgd_t *pgdp;
7190 	p4d_t *p4dp, p4d;
7191 	pud_t *pudp, pud;
7192 	pmd_t *pmdp, pmd;
7193 	pte_t *ptep, pte;
7194 
7195 	pfnmap_lockdep_assert(vma);
7196 
7197 	if (unlikely(address < vma->vm_start || address >= vma->vm_end))
7198 		goto out;
7199 
7200 	if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
7201 		goto out;
7202 retry:
7203 	pgdp = pgd_offset(mm, address);
7204 	if (pgd_none(*pgdp) || unlikely(pgd_bad(*pgdp)))
7205 		goto out;
7206 
7207 	p4dp = p4d_offset(pgdp, address);
7208 	p4d = p4dp_get(p4dp);
7209 	if (p4d_none(p4d) || unlikely(p4d_bad(p4d)))
7210 		goto out;
7211 
7212 	pudp = pud_offset(p4dp, address);
7213 	pud = pudp_get(pudp);
7214 	if (!pud_present(pud))
7215 		goto out;
7216 	if (pud_leaf(pud)) {
7217 		lock = pud_lock(mm, pudp);
7218 		pud = pudp_get(pudp);
7219 
7220 		if (unlikely(!pud_present(pud))) {
7221 			spin_unlock(lock);
7222 			goto out;
7223 		} else if (unlikely(!pud_leaf(pud))) {
7224 			spin_unlock(lock);
7225 			goto retry;
7226 		}
7227 		pfnmap_args_setup(args, lock, NULL, pud_pgprot(pud),
7228 				  pud_pfn(pud), PUD_MASK, pud_write(pud),
7229 				  pud_special(pud));
7230 		return 0;
7231 	}
7232 
7233 	pmdp = pmd_offset(pudp, address);
7234 	pmd = pmdp_get_lockless(pmdp);
7235 	if (!pmd_present(pmd))
7236 		goto out;
7237 	if (pmd_leaf(pmd)) {
7238 		lock = pmd_lock(mm, pmdp);
7239 		pmd = pmdp_get(pmdp);
7240 
7241 		if (unlikely(!pmd_present(pmd))) {
7242 			spin_unlock(lock);
7243 			goto out;
7244 		} else if (unlikely(!pmd_leaf(pmd))) {
7245 			spin_unlock(lock);
7246 			goto retry;
7247 		}
7248 		pfnmap_args_setup(args, lock, NULL, pmd_pgprot(pmd),
7249 				  pmd_pfn(pmd), PMD_MASK, pmd_write(pmd),
7250 				  pmd_special(pmd));
7251 		return 0;
7252 	}
7253 
7254 	ptep = pte_offset_map_lock(mm, pmdp, address, &lock);
7255 	if (!ptep)
7256 		goto out;
7257 	pte = ptep_get(ptep);
7258 	if (!pte_present(pte))
7259 		goto unlock;
7260 	pfnmap_args_setup(args, lock, ptep, pte_pgprot(pte),
7261 			  pte_pfn(pte), PAGE_MASK, pte_write(pte),
7262 			  pte_special(pte));
7263 	return 0;
7264 unlock:
7265 	pte_unmap_unlock(ptep, lock);
7266 out:
7267 	return -EINVAL;
7268 }
7269 EXPORT_SYMBOL_GPL(follow_pfnmap_start);
7270 
7271 /**
7272  * follow_pfnmap_end(): End a follow_pfnmap_start() process
7273  * @args: Pointer to struct @follow_pfnmap_args
7274  *
7275  * Must be used in pair of follow_pfnmap_start().  See the start() function
7276  * above for more information.
7277  */
7278 void follow_pfnmap_end(struct follow_pfnmap_args *args)
7279 {
7280 	if (args->lock)
7281 		spin_unlock(args->lock);
7282 	if (args->ptep)
7283 		pte_unmap(args->ptep);
7284 }
7285 EXPORT_SYMBOL_GPL(follow_pfnmap_end);
7286 
7287 #ifdef CONFIG_HAVE_IOREMAP_PROT
7288 /**
7289  * generic_access_phys - generic implementation for iomem mmap access
7290  * @vma: the vma to access
7291  * @addr: userspace address, not relative offset within @vma
7292  * @buf: buffer to read/write
7293  * @len: length of transfer
7294  * @write: set to FOLL_WRITE when writing, otherwise reading
7295  *
7296  * This is a generic implementation for &vm_operations_struct.access for an
7297  * iomem mapping. This callback is used by access_process_vm() when the @vma is
7298  * not page based.
7299  */
7300 int generic_access_phys(struct vm_area_struct *vma, unsigned long addr,
7301 			void *buf, int len, int write)
7302 {
7303 	resource_size_t phys_addr;
7304 	pgprot_t prot = __pgprot(0);
7305 	void __iomem *maddr;
7306 	struct page *page;
7307 	int offset = offset_in_page(addr);
7308 	int ret = -EINVAL;
7309 	bool writable;
7310 	struct follow_pfnmap_args args = { .vma = vma, .address = addr };
7311 
7312 	/*
7313 	 * Limit access to one page at a time, as that's what follow_pfnmap_start()
7314 	 * guarantees; expect the caller to retry to read larger ranges.
7315 	 */
7316 	len = min_t(int, len, PAGE_SIZE - offset);
7317 
7318 retry:
7319 	if (follow_pfnmap_start(&args))
7320 		return -EINVAL;
7321 
7322 	/*
7323 	 * Reject anything that looks like ordinary RAM, including anonymous
7324 	 * folios in CoW mappings or allocated kernel memory. Note that we
7325 	 * cannot distinguish memblock allocations from non-RAM reliably, so
7326 	 * we cannot easily reject them here.
7327 	 */
7328 	page = pfn_to_online_page(args.pfn);
7329 	if (page && !PageReserved(page)) {
7330 		follow_pfnmap_end(&args);
7331 		return -EINVAL;
7332 	}
7333 
7334 	prot = args.pgprot;
7335 	phys_addr = (resource_size_t)args.pfn << PAGE_SHIFT;
7336 	writable = args.writable;
7337 	follow_pfnmap_end(&args);
7338 
7339 	if ((write & FOLL_WRITE) && !writable)
7340 		return -EINVAL;
7341 
7342 	maddr = ioremap_prot(phys_addr, PAGE_SIZE, prot);
7343 	if (!maddr)
7344 		return -ENOMEM;
7345 
7346 	if (follow_pfnmap_start(&args))
7347 		goto out_unmap;
7348 
7349 	if ((pgprot_val(prot) != pgprot_val(args.pgprot)) ||
7350 	    (phys_addr != ((resource_size_t)args.pfn << PAGE_SHIFT)) ||
7351 	    (writable != args.writable)) {
7352 		follow_pfnmap_end(&args);
7353 		iounmap(maddr);
7354 		goto retry;
7355 	}
7356 
7357 	if (write)
7358 		memcpy_toio(maddr + offset, buf, len);
7359 	else
7360 		memcpy_fromio(buf, maddr + offset, len);
7361 	ret = len;
7362 	follow_pfnmap_end(&args);
7363 out_unmap:
7364 	iounmap(maddr);
7365 
7366 	return ret;
7367 }
7368 EXPORT_SYMBOL_GPL(generic_access_phys);
7369 #endif
7370 
7371 /*
7372  * Access another process' address space as given in mm.
7373  */
7374 static int __access_remote_vm(struct mm_struct *mm, unsigned long addr,
7375 			      void *buf, int len, unsigned int gup_flags)
7376 {
7377 	void *old_buf = buf;
7378 	int write = gup_flags & FOLL_WRITE;
7379 
7380 	if (mmap_read_lock_killable(mm))
7381 		return 0;
7382 
7383 	/* Untag the address before looking up the VMA */
7384 	addr = untagged_addr_remote(mm, addr);
7385 
7386 	/* Avoid triggering the temporary warning in __get_user_pages */
7387 	if (!vma_lookup(mm, addr) && !expand_stack(mm, addr))
7388 		return 0;
7389 
7390 	/* ignore errors, just check how much was successfully transferred */
7391 	while (len) {
7392 		int bytes, offset;
7393 		void *maddr;
7394 		struct folio *folio;
7395 		struct vm_area_struct *vma = NULL;
7396 		struct page *page = get_user_page_vma_remote(mm, addr,
7397 							     gup_flags, &vma);
7398 
7399 		if (IS_ERR(page)) {
7400 			/* We might need to expand the stack to access it */
7401 			vma = vma_lookup(mm, addr);
7402 			if (!vma) {
7403 				vma = expand_stack(mm, addr);
7404 
7405 				/* mmap_lock was dropped on failure */
7406 				if (!vma)
7407 					return buf - old_buf;
7408 
7409 				/* Try again if stack expansion worked */
7410 				continue;
7411 			}
7412 
7413 			/*
7414 			 * Check if this is a VM_IO | VM_PFNMAP VMA, which
7415 			 * we can access using slightly different code.
7416 			 */
7417 			bytes = 0;
7418 #ifdef CONFIG_HAVE_IOREMAP_PROT
7419 			if (vma->vm_ops && vma->vm_ops->access)
7420 				bytes = vma->vm_ops->access(vma, addr, buf,
7421 							    len, write);
7422 #endif
7423 			if (bytes <= 0)
7424 				break;
7425 		} else {
7426 			folio = page_folio(page);
7427 			bytes = len;
7428 			offset = addr & (PAGE_SIZE-1);
7429 			if (bytes > PAGE_SIZE-offset)
7430 				bytes = PAGE_SIZE-offset;
7431 
7432 			maddr = kmap_local_folio(folio, folio_page_idx(folio, page) * PAGE_SIZE);
7433 			if (write) {
7434 				copy_to_user_page(vma, page, addr,
7435 						  maddr + offset, buf, bytes);
7436 				folio_mark_dirty_lock(folio);
7437 			} else {
7438 				copy_from_user_page(vma, page, addr,
7439 						    buf, maddr + offset, bytes);
7440 			}
7441 			folio_release_kmap(folio, maddr);
7442 		}
7443 		len -= bytes;
7444 		buf += bytes;
7445 		addr += bytes;
7446 	}
7447 	mmap_read_unlock(mm);
7448 
7449 	return buf - old_buf;
7450 }
7451 
7452 /**
7453  * access_remote_vm - access another process' address space
7454  * @mm:		the mm_struct of the target address space
7455  * @addr:	start address to access
7456  * @buf:	source or destination buffer
7457  * @len:	number of bytes to transfer
7458  * @gup_flags:	flags modifying lookup behaviour
7459  *
7460  * The caller must hold a reference on @mm.
7461  *
7462  * Return: number of bytes copied from source to destination.
7463  */
7464 int access_remote_vm(struct mm_struct *mm, unsigned long addr,
7465 		void *buf, int len, unsigned int gup_flags)
7466 {
7467 	return __access_remote_vm(mm, addr, buf, len, gup_flags);
7468 }
7469 
7470 /*
7471  * Access another process' address space.
7472  * Source/target buffer must be kernel space,
7473  * Do not walk the page table directly, use get_user_pages
7474  */
7475 int access_process_vm(struct task_struct *tsk, unsigned long addr,
7476 		void *buf, int len, unsigned int gup_flags)
7477 {
7478 	struct mm_struct *mm;
7479 	int ret;
7480 
7481 	mm = get_task_mm(tsk);
7482 	if (!mm)
7483 		return 0;
7484 
7485 	ret = __access_remote_vm(mm, addr, buf, len, gup_flags);
7486 
7487 	mmput(mm);
7488 
7489 	return ret;
7490 }
7491 EXPORT_SYMBOL_GPL(access_process_vm);
7492 
7493 /*
7494  * Copy a string from another process's address space as given in mm.
7495  * If there is any error return -EFAULT.
7496  */
7497 int __copy_remote_mm_str(struct mm_struct *mm, unsigned long addr,
7498 		void *buf, int len, unsigned int gup_flags)
7499 {
7500 	void *old_buf = buf;
7501 	int err = 0;
7502 
7503 	*(char *)buf = '\0';
7504 
7505 	if (mmap_read_lock_killable(mm))
7506 		return -EFAULT;
7507 
7508 	addr = untagged_addr_remote(mm, addr);
7509 
7510 	/* Avoid triggering the temporary warning in __get_user_pages */
7511 	if (!vma_lookup(mm, addr)) {
7512 		err = -EFAULT;
7513 		goto out;
7514 	}
7515 
7516 	while (len) {
7517 		int bytes, offset, retval;
7518 		void *maddr;
7519 		struct folio *folio;
7520 		struct page *page;
7521 		struct vm_area_struct *vma = NULL;
7522 
7523 		page = get_user_page_vma_remote(mm, addr, gup_flags, &vma);
7524 		if (IS_ERR(page)) {
7525 			/*
7526 			 * Treat as a total failure for now until we decide how
7527 			 * to handle the CONFIG_HAVE_IOREMAP_PROT case and
7528 			 * stack expansion.
7529 			 */
7530 			*(char *)buf = '\0';
7531 			err = -EFAULT;
7532 			goto out;
7533 		}
7534 
7535 		folio = page_folio(page);
7536 		bytes = len;
7537 		offset = addr & (PAGE_SIZE - 1);
7538 		if (bytes > PAGE_SIZE - offset)
7539 			bytes = PAGE_SIZE - offset;
7540 
7541 		maddr = kmap_local_folio(folio, folio_page_idx(folio, page) * PAGE_SIZE);
7542 		retval = strscpy(buf, maddr + offset, bytes);
7543 		if (retval >= 0) {
7544 			/* Found the end of the string */
7545 			buf += retval;
7546 			folio_release_kmap(folio, maddr);
7547 			break;
7548 		}
7549 
7550 		buf += bytes - 1;
7551 		/*
7552 		 * Because strscpy always NUL terminates we need to
7553 		 * copy the last byte in the page if we are going to
7554 		 * load more pages
7555 		 */
7556 		if (bytes != len) {
7557 			addr += bytes - 1;
7558 			copy_from_user_page(vma, page, addr, buf, maddr + (PAGE_SIZE - 1), 1);
7559 			buf += 1;
7560 			addr += 1;
7561 		}
7562 		len -= bytes;
7563 
7564 		folio_release_kmap(folio, maddr);
7565 	}
7566 
7567 out:
7568 	mmap_read_unlock(mm);
7569 	if (err)
7570 		return err;
7571 	return buf - old_buf;
7572 }
7573 
7574 /*
7575  * Print the name of a VMA.
7576  */
7577 void print_vma_addr(char *prefix, unsigned long ip)
7578 {
7579 	struct mm_struct *mm = current->mm;
7580 	struct vm_area_struct *vma;
7581 
7582 	/*
7583 	 * we might be running from an atomic context so we cannot sleep
7584 	 */
7585 	if (!mmap_read_trylock(mm))
7586 		return;
7587 
7588 	vma = vma_lookup(mm, ip);
7589 	if (vma && vma->vm_file) {
7590 		struct file *f = vma->vm_file;
7591 		ip -= vma->vm_start;
7592 		ip += vma_start_pgoff(vma) << PAGE_SHIFT;
7593 		printk("%s%pD[%lx,%lx+%lx]", prefix, f, ip,
7594 				vma->vm_start,
7595 				vma->vm_end - vma->vm_start);
7596 	}
7597 	mmap_read_unlock(mm);
7598 }
7599 
7600 #if defined(CONFIG_PROVE_LOCKING) || defined(CONFIG_DEBUG_ATOMIC_SLEEP)
7601 void __might_fault(const char *file, int line)
7602 {
7603 	if (pagefault_disabled())
7604 		return;
7605 	__might_sleep(file, line);
7606 	if (current->mm)
7607 		might_lock_read(&current->mm->mmap_lock);
7608 }
7609 EXPORT_SYMBOL(__might_fault);
7610 #endif
7611 
7612 #if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_HUGETLBFS)
7613 /*
7614  * Process all subpages of the specified huge page with the specified
7615  * operation.  The target subpage will be processed last to keep its
7616  * cache lines hot.
7617  */
7618 static inline int process_huge_page(
7619 	unsigned long addr_hint, unsigned int nr_pages,
7620 	int (*process_subpage)(unsigned long addr, int idx, void *arg),
7621 	void *arg)
7622 {
7623 	int i, n, base, l, ret;
7624 	unsigned long addr = addr_hint &
7625 		~(((unsigned long)nr_pages << PAGE_SHIFT) - 1);
7626 
7627 	/* Process target subpage last to keep its cache lines hot */
7628 	might_sleep();
7629 	n = (addr_hint - addr) / PAGE_SIZE;
7630 	if (2 * n <= nr_pages) {
7631 		/* If target subpage in first half of huge page */
7632 		base = 0;
7633 		l = n;
7634 		/* Process subpages at the end of huge page */
7635 		for (i = nr_pages - 1; i >= 2 * n; i--) {
7636 			cond_resched();
7637 			ret = process_subpage(addr + i * PAGE_SIZE, i, arg);
7638 			if (ret)
7639 				return ret;
7640 		}
7641 	} else {
7642 		/* If target subpage in second half of huge page */
7643 		base = nr_pages - 2 * (nr_pages - n);
7644 		l = nr_pages - n;
7645 		/* Process subpages at the begin of huge page */
7646 		for (i = 0; i < base; i++) {
7647 			cond_resched();
7648 			ret = process_subpage(addr + i * PAGE_SIZE, i, arg);
7649 			if (ret)
7650 				return ret;
7651 		}
7652 	}
7653 	/*
7654 	 * Process remaining subpages in left-right-left-right pattern
7655 	 * towards the target subpage
7656 	 */
7657 	for (i = 0; i < l; i++) {
7658 		int left_idx = base + i;
7659 		int right_idx = base + 2 * l - 1 - i;
7660 
7661 		cond_resched();
7662 		ret = process_subpage(addr + left_idx * PAGE_SIZE, left_idx, arg);
7663 		if (ret)
7664 			return ret;
7665 		cond_resched();
7666 		ret = process_subpage(addr + right_idx * PAGE_SIZE, right_idx, arg);
7667 		if (ret)
7668 			return ret;
7669 	}
7670 	return 0;
7671 }
7672 
7673 static void clear_contig_highpages(struct page *page, unsigned long addr,
7674 				   unsigned int nr_pages)
7675 {
7676 	unsigned int i, count;
7677 	/*
7678 	 * When clearing we want to operate on the largest extent possible to
7679 	 * allow for architecture specific extent based optimizations.
7680 	 *
7681 	 * However, since clear_user_highpages() (and primitives clear_user_pages(),
7682 	 * clear_pages()), do not call cond_resched(), limit the unit size when
7683 	 * running under non-preemptible scheduling models.
7684 	 */
7685 	const unsigned int unit = preempt_model_preemptible() ?
7686 				   nr_pages : PROCESS_PAGES_NON_PREEMPT_BATCH;
7687 
7688 	might_sleep();
7689 
7690 	for (i = 0; i < nr_pages; i += count) {
7691 		cond_resched();
7692 
7693 		count = min(unit, nr_pages - i);
7694 		clear_user_highpages(page + i, addr + i * PAGE_SIZE, count);
7695 	}
7696 }
7697 
7698 /*
7699  * When zeroing a folio, we want to differentiate between pages in the
7700  * vicinity of the faulting address where we have spatial and temporal
7701  * locality, and those far away where we don't.
7702  *
7703  * Use a radius of 2 for determining the local neighbourhood.
7704  */
7705 #define FOLIO_ZERO_LOCALITY_RADIUS	2
7706 
7707 /**
7708  * folio_zero_user - Zero a folio which will be mapped to userspace.
7709  * @folio: The folio to zero.
7710  * @addr_hint: The address accessed by the user or the base address.
7711  */
7712 void folio_zero_user(struct folio *folio, unsigned long addr_hint)
7713 {
7714 	const unsigned long base_addr = ALIGN_DOWN(addr_hint, folio_size(folio));
7715 	const long fault_idx = (addr_hint - base_addr) / PAGE_SIZE;
7716 	const struct range pg = DEFINE_RANGE(0, folio_nr_pages(folio) - 1);
7717 	const long radius = FOLIO_ZERO_LOCALITY_RADIUS;
7718 	struct range r[3];
7719 	int i;
7720 
7721 	/*
7722 	 * Faulting page and its immediate neighbourhood. Will be cleared at the
7723 	 * end to keep its cachelines hot.
7724 	 */
7725 	r[2] = DEFINE_RANGE(fault_idx - radius < (long)pg.start ? pg.start : fault_idx - radius,
7726 			    fault_idx + radius > (long)pg.end   ? pg.end   : fault_idx + radius);
7727 
7728 
7729 	/* Region to the left of the fault */
7730 	r[1] = DEFINE_RANGE(pg.start, r[2].start - 1);
7731 
7732 	/* Region to the right of the fault: always valid for the common fault_idx=0 case. */
7733 	r[0] = DEFINE_RANGE(r[2].end + 1, pg.end);
7734 
7735 	for (i = 0; i < ARRAY_SIZE(r); i++) {
7736 		const unsigned long addr = base_addr + r[i].start * PAGE_SIZE;
7737 		const long nr_pages = (long)range_len(&r[i]);
7738 		struct page *page = folio_page(folio, r[i].start);
7739 
7740 		if (nr_pages > 0)
7741 			clear_contig_highpages(page, addr, nr_pages);
7742 	}
7743 }
7744 
7745 static int copy_user_gigantic_page(struct folio *dst, struct folio *src,
7746 				   unsigned long addr_hint,
7747 				   struct vm_area_struct *vma,
7748 				   unsigned int nr_pages)
7749 {
7750 	unsigned long addr = ALIGN_DOWN(addr_hint, folio_size(dst));
7751 	struct page *dst_page;
7752 	struct page *src_page;
7753 	int i;
7754 
7755 	for (i = 0; i < nr_pages; i++) {
7756 		dst_page = folio_page(dst, i);
7757 		src_page = folio_page(src, i);
7758 
7759 		cond_resched();
7760 		if (copy_mc_user_highpage(dst_page, src_page,
7761 					  addr + i*PAGE_SIZE, vma))
7762 			return -EHWPOISON;
7763 	}
7764 	return 0;
7765 }
7766 
7767 struct copy_subpage_arg {
7768 	struct folio *dst;
7769 	struct folio *src;
7770 	struct vm_area_struct *vma;
7771 };
7772 
7773 static int copy_subpage(unsigned long addr, int idx, void *arg)
7774 {
7775 	struct copy_subpage_arg *copy_arg = arg;
7776 	struct page *dst = folio_page(copy_arg->dst, idx);
7777 	struct page *src = folio_page(copy_arg->src, idx);
7778 
7779 	if (copy_mc_user_highpage(dst, src, addr, copy_arg->vma))
7780 		return -EHWPOISON;
7781 	return 0;
7782 }
7783 
7784 int copy_user_large_folio(struct folio *dst, struct folio *src,
7785 			  unsigned long addr_hint, struct vm_area_struct *vma)
7786 {
7787 	unsigned int nr_pages = folio_nr_pages(dst);
7788 	struct copy_subpage_arg arg = {
7789 		.dst = dst,
7790 		.src = src,
7791 		.vma = vma,
7792 	};
7793 
7794 	if (unlikely(nr_pages > MAX_ORDER_NR_PAGES))
7795 		return copy_user_gigantic_page(dst, src, addr_hint, vma, nr_pages);
7796 
7797 	return process_huge_page(addr_hint, nr_pages, copy_subpage, &arg);
7798 }
7799 
7800 long copy_folio_from_user(struct folio *dst_folio,
7801 			   const void __user *usr_src,
7802 			   bool allow_pagefault)
7803 {
7804 	void *kaddr;
7805 	unsigned long i, rc = 0;
7806 	unsigned int nr_pages = folio_nr_pages(dst_folio);
7807 	unsigned long ret_val = nr_pages * PAGE_SIZE;
7808 	struct page *subpage;
7809 
7810 	for (i = 0; i < nr_pages; i++) {
7811 		subpage = folio_page(dst_folio, i);
7812 		kaddr = kmap_local_page(subpage);
7813 		if (!allow_pagefault)
7814 			pagefault_disable();
7815 		rc = copy_from_user(kaddr, usr_src + i * PAGE_SIZE, PAGE_SIZE);
7816 		if (!allow_pagefault)
7817 			pagefault_enable();
7818 		kunmap_local(kaddr);
7819 
7820 		ret_val -= (PAGE_SIZE - rc);
7821 		if (rc)
7822 			break;
7823 
7824 		flush_dcache_page(subpage);
7825 
7826 		cond_resched();
7827 	}
7828 	return ret_val;
7829 }
7830 #endif /* CONFIG_TRANSPARENT_HUGEPAGE || CONFIG_HUGETLBFS */
7831 
7832 #if defined(CONFIG_SPLIT_PTE_PTLOCKS) && ALLOC_SPLIT_PTLOCKS
7833 
7834 static struct kmem_cache *page_ptl_cachep;
7835 
7836 void __init ptlock_cache_init(void)
7837 {
7838 	page_ptl_cachep = kmem_cache_create("page->ptl", sizeof(spinlock_t), 0,
7839 			SLAB_PANIC, NULL);
7840 }
7841 
7842 bool ptlock_alloc(struct ptdesc *ptdesc)
7843 {
7844 	spinlock_t *ptl;
7845 
7846 	ptl = kmem_cache_alloc(page_ptl_cachep, GFP_KERNEL);
7847 	if (!ptl)
7848 		return false;
7849 	ptdesc->ptl = ptl;
7850 	return true;
7851 }
7852 
7853 void ptlock_free(struct ptdesc *ptdesc)
7854 {
7855 	if (ptdesc->ptl)
7856 		kmem_cache_free(page_ptl_cachep, ptdesc->ptl);
7857 }
7858 #endif
7859 
7860 void vma_pgtable_walk_begin(struct vm_area_struct *vma)
7861 {
7862 	if (vma_is_hugetlb(vma))
7863 		hugetlb_vma_lock_read(vma);
7864 }
7865 
7866 void vma_pgtable_walk_end(struct vm_area_struct *vma)
7867 {
7868 	if (vma_is_hugetlb(vma))
7869 		hugetlb_vma_unlock_read(vma);
7870 }
7871