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