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