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