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