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