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