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