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