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