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