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