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