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