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